test.cc 635 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555
  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, DoNotForwardCookie) {
  2289. Server svr1;
  2290. std::string captured_cookie;
  2291. bool target_hit = false;
  2292. svr1.Get("/target", [&](const Request &req, Response &res) {
  2293. captured_cookie = req.get_header_value("Cookie");
  2294. target_hit = true;
  2295. res.set_content("OK", "text/plain");
  2296. });
  2297. int svr1_port = 0;
  2298. auto thread1 = std::thread([&]() {
  2299. svr1_port = svr1.bind_to_any_port(HOST);
  2300. svr1.listen_after_bind();
  2301. });
  2302. Server svr2;
  2303. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2304. res.set_redirect(
  2305. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2306. });
  2307. int svr2_port = 0;
  2308. auto thread2 = std::thread([&]() {
  2309. svr2_port = svr2.bind_to_any_port(HOST);
  2310. svr2.listen_after_bind();
  2311. });
  2312. auto se = detail::scope_exit([&] {
  2313. svr2.stop();
  2314. thread2.join();
  2315. svr1.stop();
  2316. thread1.join();
  2317. ASSERT_FALSE(svr2.is_running());
  2318. ASSERT_FALSE(svr1.is_running());
  2319. });
  2320. svr1.wait_until_ready();
  2321. svr2.wait_until_ready();
  2322. Client cli("localhost", svr2_port);
  2323. cli.set_follow_location(true);
  2324. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2325. auto res = cli.Get("/redir", headers);
  2326. ASSERT_TRUE(res);
  2327. EXPECT_EQ(StatusCode::OK_200, res->status);
  2328. EXPECT_TRUE(target_hit);
  2329. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2330. EXPECT_TRUE(captured_cookie.empty());
  2331. }
  2332. TEST(RedirectToSamePort, ForwardCookie) {
  2333. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2334. // header so that ordinary session flows keep working.
  2335. Server svr;
  2336. std::string captured_cookie;
  2337. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2338. res.set_redirect("/target", 302);
  2339. });
  2340. svr.Get("/target", [&](const Request &req, Response &res) {
  2341. captured_cookie = req.get_header_value("Cookie");
  2342. res.set_content("OK", "text/plain");
  2343. });
  2344. auto port = svr.bind_to_any_port(HOST);
  2345. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2346. auto se = detail::scope_exit([&] {
  2347. svr.stop();
  2348. thread.join();
  2349. ASSERT_FALSE(svr.is_running());
  2350. });
  2351. svr.wait_until_ready();
  2352. Client cli(HOST, port);
  2353. cli.set_follow_location(true);
  2354. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2355. auto res = cli.Get("/redir", headers);
  2356. ASSERT_TRUE(res);
  2357. EXPECT_EQ(StatusCode::OK_200, res->status);
  2358. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2359. }
  2360. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2361. Server svr;
  2362. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2363. // Port number that overflows int — should not crash
  2364. res.set_redirect("http://localhost:99999999999999999999/target");
  2365. });
  2366. auto port = svr.bind_to_any_port(HOST);
  2367. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2368. auto se = detail::scope_exit([&] {
  2369. svr.stop();
  2370. thread.join();
  2371. ASSERT_FALSE(svr.is_running());
  2372. });
  2373. svr.wait_until_ready();
  2374. Client cli(HOST, port);
  2375. cli.set_follow_location(true);
  2376. auto res = cli.Get("/redir");
  2377. // Should fail gracefully, not crash (no valid response due to bad port)
  2378. EXPECT_FALSE(res);
  2379. }
  2380. TEST(RedirectFromPageWithContent, Redirect) {
  2381. Server svr;
  2382. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2383. res.set_content("___", "text/plain");
  2384. res.set_redirect("/2");
  2385. });
  2386. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content("Hello World!", "text/plain");
  2388. });
  2389. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. th.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. {
  2397. Client cli("localhost", PORT);
  2398. cli.set_follow_location(true);
  2399. std::string body;
  2400. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2401. body.append(data, data_length);
  2402. return true;
  2403. });
  2404. ASSERT_TRUE(res);
  2405. EXPECT_EQ(StatusCode::OK_200, res->status);
  2406. EXPECT_EQ("Hello World!", body);
  2407. }
  2408. {
  2409. Client cli("localhost", PORT);
  2410. std::string body;
  2411. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2412. body.append(data, data_length);
  2413. return true;
  2414. });
  2415. ASSERT_TRUE(res);
  2416. EXPECT_EQ(StatusCode::Found_302, res->status);
  2417. EXPECT_EQ("___", body);
  2418. }
  2419. }
  2420. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2421. Server svr;
  2422. auto port_str = std::to_string(PORT);
  2423. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2424. auto expected_host = "[::1]:" + port_str;
  2425. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2426. res.set_content("___", "text/plain");
  2427. // res.set_redirect("/2");
  2428. res.set_redirect(redirect_url);
  2429. });
  2430. svr.Get("/2", [&](const Request &req, Response &res) {
  2431. auto host_header = req.headers.find("Host");
  2432. ASSERT_TRUE(host_header != req.headers.end());
  2433. EXPECT_EQ(expected_host, host_header->second);
  2434. res.set_content("Hello World!", "text/plain");
  2435. });
  2436. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2437. auto se = detail::scope_exit([&] {
  2438. svr.stop();
  2439. th.join();
  2440. ASSERT_FALSE(svr.is_running());
  2441. });
  2442. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2443. // actually starts anything, so the condition !svr.is_running() will
  2444. // always remain true, and the loop never stops.
  2445. // This basically counts how many milliseconds have passed since the
  2446. // call to svr.listen(), and if after 5 seconds nothing started yet
  2447. // aborts the test.
  2448. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2449. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2450. ASSERT_LT(milliseconds, 5000U);
  2451. }
  2452. {
  2453. Client cli("::1", PORT);
  2454. cli.set_follow_location(true);
  2455. std::string body;
  2456. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2457. body.append(data, data_length);
  2458. return true;
  2459. });
  2460. ASSERT_TRUE(res);
  2461. EXPECT_EQ(StatusCode::OK_200, res->status);
  2462. EXPECT_EQ("Hello World!", body);
  2463. }
  2464. {
  2465. Client cli("::1", PORT);
  2466. std::string body;
  2467. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2468. body.append(data, data_length);
  2469. return true;
  2470. });
  2471. ASSERT_TRUE(res);
  2472. EXPECT_EQ(StatusCode::Found_302, res->status);
  2473. EXPECT_EQ("___", body);
  2474. }
  2475. }
  2476. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2477. Server svr;
  2478. svr.Get("/foo", [](const Request &req, Response &res) {
  2479. auto a = req.params.find("a");
  2480. if (a != req.params.end()) {
  2481. res.set_content((*a).second, "text/plain");
  2482. res.status = StatusCode::OK_200;
  2483. } else {
  2484. res.status = StatusCode::BadRequest_400;
  2485. }
  2486. });
  2487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2488. auto se = detail::scope_exit([&] {
  2489. svr.stop();
  2490. thread.join();
  2491. ASSERT_FALSE(svr.is_running());
  2492. });
  2493. svr.wait_until_ready();
  2494. {
  2495. Client cli(HOST, PORT);
  2496. cli.set_path_encode(false);
  2497. auto res = cli.Get("/foo?a=explicitly+encoded");
  2498. ASSERT_TRUE(res);
  2499. EXPECT_EQ(StatusCode::OK_200, res->status);
  2500. // This expects it back with a space, as the `+` won't have been
  2501. // url-encoded, and server-side the params get decoded turning `+`
  2502. // into spaces.
  2503. EXPECT_EQ("explicitly encoded", res->body);
  2504. }
  2505. }
  2506. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2507. // When path encoding is disabled the client must transmit the supplied
  2508. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2509. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2510. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2511. // than a space (0x20). Assert on the raw wire target to catch this.
  2512. Server svr;
  2513. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2514. svr.Get("/foo", [&](const Request &req, Response &res) {
  2515. EXPECT_EQ(expected_target, req.target);
  2516. res.status = StatusCode::OK_200;
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. {
  2526. Client cli(HOST, PORT);
  2527. cli.set_path_encode(false);
  2528. auto res = cli.Get(expected_target.c_str());
  2529. ASSERT_TRUE(res);
  2530. EXPECT_EQ(StatusCode::OK_200, res->status);
  2531. }
  2532. }
  2533. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2534. Server svr;
  2535. svr.Get("/", [](const Request &req, Response &) {
  2536. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2537. });
  2538. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2539. auto se = detail::scope_exit([&] {
  2540. svr.stop();
  2541. thread.join();
  2542. ASSERT_FALSE(svr.is_running());
  2543. });
  2544. svr.wait_until_ready();
  2545. {
  2546. Client cli(HOST, PORT);
  2547. cli.set_path_encode(false);
  2548. auto res = cli.Get("/?something=%0A");
  2549. ASSERT_TRUE(res);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. }
  2553. TEST(BindServerTest, BindDualStack) {
  2554. Server svr;
  2555. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2556. res.set_content("Hello World!", "text/plain");
  2557. });
  2558. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2559. auto se = detail::scope_exit([&] {
  2560. svr.stop();
  2561. thread.join();
  2562. ASSERT_FALSE(svr.is_running());
  2563. });
  2564. svr.wait_until_ready();
  2565. {
  2566. Client cli("127.0.0.1", PORT);
  2567. auto res = cli.Get("/1");
  2568. ASSERT_TRUE(res);
  2569. EXPECT_EQ(StatusCode::OK_200, res->status);
  2570. EXPECT_EQ("Hello World!", res->body);
  2571. }
  2572. {
  2573. Client cli("::1", PORT);
  2574. auto res = cli.Get("/1");
  2575. ASSERT_TRUE(res);
  2576. EXPECT_EQ(StatusCode::OK_200, res->status);
  2577. EXPECT_EQ("Hello World!", res->body);
  2578. }
  2579. }
  2580. TEST(BindServerTest, BindAndListenSeparately) {
  2581. Server svr;
  2582. int port = svr.bind_to_any_port("0.0.0.0");
  2583. ASSERT_TRUE(svr.is_valid());
  2584. ASSERT_TRUE(port > 0);
  2585. svr.stop();
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2589. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2590. CLIENT_CA_CERT_DIR);
  2591. int port = svr.bind_to_any_port("0.0.0.0");
  2592. ASSERT_TRUE(svr.is_valid());
  2593. ASSERT_TRUE(port > 0);
  2594. svr.stop();
  2595. }
  2596. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2597. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2598. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2599. int port = svr.bind_to_any_port("0.0.0.0");
  2600. ASSERT_TRUE(svr.is_valid());
  2601. ASSERT_TRUE(port > 0);
  2602. svr.stop();
  2603. }
  2604. TEST(BindServerTest, UpdateCertsPem) {
  2605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2606. int port = svr.bind_to_any_port("0.0.0.0");
  2607. ASSERT_TRUE(svr.is_valid());
  2608. ASSERT_TRUE(port > 0);
  2609. // Read PEM files
  2610. std::string cert_pem, key_pem, ca_pem;
  2611. read_file(SERVER_CERT_FILE, cert_pem);
  2612. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2613. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2614. // Update server certificates using PEM API
  2615. ASSERT_TRUE(
  2616. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2617. ASSERT_TRUE(svr.is_valid());
  2618. svr.stop();
  2619. }
  2620. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2621. // Start server with client CA (enables client auth)
  2622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2623. ASSERT_TRUE(svr.is_valid());
  2624. bool handler_called = false;
  2625. svr.Get("/test", [&](const Request &req, Response &res) {
  2626. handler_called = true;
  2627. // Verify client certificate is present
  2628. auto cert = req.peer_cert();
  2629. EXPECT_TRUE(static_cast<bool>(cert));
  2630. res.set_content("ok", "text/plain");
  2631. });
  2632. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2633. auto se = detail::scope_exit([&] {
  2634. svr.stop();
  2635. t.join();
  2636. ASSERT_FALSE(svr.is_running());
  2637. });
  2638. svr.wait_until_ready();
  2639. // Read PEM files
  2640. std::string cert_pem, key_pem, ca_pem;
  2641. read_file(SERVER_CERT_FILE, cert_pem);
  2642. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2643. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2644. // Update server certificates and client CA using PEM API while server running
  2645. ASSERT_TRUE(
  2646. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2647. // Connect with client certificate
  2648. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2649. cli.enable_server_certificate_verification(false);
  2650. cli.set_connection_timeout(30);
  2651. auto res = cli.Get("/test");
  2652. ASSERT_TRUE(res);
  2653. ASSERT_EQ(StatusCode::OK_200, res->status);
  2654. ASSERT_TRUE(handler_called);
  2655. EXPECT_EQ("ok", res->body);
  2656. }
  2657. #endif
  2658. TEST(ErrorHandlerTest, ContentLength) {
  2659. Server svr;
  2660. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2661. res.status = StatusCode::OK_200;
  2662. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2663. "text/html"); // <= Content-Length still 13
  2664. });
  2665. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2666. res.set_content("Hello World!\n", "text/plain");
  2667. res.status = 524;
  2668. });
  2669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. thread.join();
  2673. ASSERT_FALSE(svr.is_running());
  2674. });
  2675. svr.wait_until_ready();
  2676. {
  2677. Client cli(HOST, PORT);
  2678. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2679. ASSERT_TRUE(res);
  2680. EXPECT_EQ(StatusCode::OK_200, res->status);
  2681. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2682. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2683. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2684. }
  2685. }
  2686. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2687. TEST(ExceptionTest, WithoutExceptionHandler) {
  2688. Server svr;
  2689. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2690. throw std::runtime_error("exception...");
  2691. });
  2692. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2693. throw std::runtime_error("exception\r\n...");
  2694. });
  2695. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2696. auto se = detail::scope_exit([&] {
  2697. svr.stop();
  2698. listen_thread.join();
  2699. ASSERT_FALSE(svr.is_running());
  2700. });
  2701. svr.wait_until_ready();
  2702. Client cli("localhost", PORT);
  2703. {
  2704. auto res = cli.Get("/exception");
  2705. ASSERT_TRUE(res);
  2706. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2707. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2708. }
  2709. {
  2710. auto res = cli.Get("/unknown");
  2711. ASSERT_TRUE(res);
  2712. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2713. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2714. }
  2715. }
  2716. TEST(ExceptionTest, WithExceptionHandler) {
  2717. Server svr;
  2718. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2719. std::exception_ptr ep) {
  2720. EXPECT_FALSE(ep == nullptr);
  2721. try {
  2722. std::rethrow_exception(ep);
  2723. } catch (std::exception &e) {
  2724. EXPECT_EQ("abc", std::string(e.what()));
  2725. } catch (...) {}
  2726. res.status = StatusCode::InternalServerError_500;
  2727. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2728. "text/html"); // <= Content-Length still 13 at this point
  2729. });
  2730. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2731. res.set_content("Hello World!\n", "text/plain");
  2732. throw std::runtime_error("abc");
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. for (size_t i = 0; i < 10; i++) {
  2742. Client cli(HOST, PORT);
  2743. for (size_t j = 0; j < 100; j++) {
  2744. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2745. ASSERT_TRUE(res);
  2746. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2747. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2748. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2749. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2750. }
  2751. cli.set_keep_alive(true);
  2752. for (size_t j = 0; j < 100; j++) {
  2753. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2754. ASSERT_TRUE(res);
  2755. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2756. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2757. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2758. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2759. }
  2760. }
  2761. }
  2762. TEST(ExceptionTest, AndErrorHandler) {
  2763. Server svr;
  2764. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2765. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2766. });
  2767. svr.set_exception_handler(
  2768. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2769. EXPECT_FALSE(ep == nullptr);
  2770. try {
  2771. std::rethrow_exception(ep);
  2772. } catch (std::exception &e) {
  2773. res.set_content(e.what(), "text/html");
  2774. } catch (...) {}
  2775. res.status = StatusCode::InternalServerError_500;
  2776. });
  2777. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2778. throw std::runtime_error("EXCEPTION");
  2779. });
  2780. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2781. res.set_content("ERROR", "text/html");
  2782. res.status = StatusCode::InternalServerError_500;
  2783. });
  2784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2785. auto se = detail::scope_exit([&] {
  2786. svr.stop();
  2787. thread.join();
  2788. ASSERT_FALSE(svr.is_running());
  2789. });
  2790. svr.wait_until_ready();
  2791. Client cli(HOST, PORT);
  2792. {
  2793. auto res = cli.Get("/exception");
  2794. ASSERT_TRUE(res);
  2795. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2796. EXPECT_EQ("EXCEPTION", res->body);
  2797. }
  2798. {
  2799. auto res = cli.Get("/error");
  2800. ASSERT_TRUE(res);
  2801. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2802. EXPECT_EQ("ERROR", res->body);
  2803. }
  2804. {
  2805. auto res = cli.Get("/invalid");
  2806. ASSERT_TRUE(res);
  2807. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2808. EXPECT_EQ("NOT_FOUND", res->body);
  2809. }
  2810. }
  2811. #endif
  2812. TEST(NoContentTest, ContentLength) {
  2813. Server svr;
  2814. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2815. res.status = StatusCode::NoContent_204;
  2816. });
  2817. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2818. auto se = detail::scope_exit([&] {
  2819. svr.stop();
  2820. thread.join();
  2821. ASSERT_FALSE(svr.is_running());
  2822. });
  2823. svr.wait_until_ready();
  2824. {
  2825. Client cli(HOST, PORT);
  2826. auto res = cli.Get("/hi");
  2827. ASSERT_TRUE(res);
  2828. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2829. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2830. }
  2831. }
  2832. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2833. #ifdef CPPHTTPLIB_SSL_ENABLED
  2834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2835. ASSERT_TRUE(svr.is_valid());
  2836. #else
  2837. Server svr;
  2838. #endif
  2839. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2840. if (req.path == "/routing_handler") {
  2841. res.set_header("PRE_ROUTING", "on");
  2842. res.set_content("Routing Handler", "text/plain");
  2843. return httplib::Server::HandlerResponse::Handled;
  2844. }
  2845. return httplib::Server::HandlerResponse::Unhandled;
  2846. });
  2847. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2848. res.set_content("Error", "text/html");
  2849. });
  2850. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2851. if (req.path == "/routing_handler") {
  2852. res.set_header("POST_ROUTING", "on");
  2853. }
  2854. });
  2855. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2856. res.set_content("Hello World!\n", "text/plain");
  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. {
  2866. #ifdef CPPHTTPLIB_SSL_ENABLED
  2867. SSLClient cli(HOST, PORT);
  2868. cli.enable_server_certificate_verification(false);
  2869. #else
  2870. Client cli(HOST, PORT);
  2871. #endif
  2872. auto res = cli.Get("/routing_handler");
  2873. ASSERT_TRUE(res);
  2874. EXPECT_EQ(StatusCode::OK_200, res->status);
  2875. EXPECT_EQ("Routing Handler", res->body);
  2876. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2877. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2878. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2879. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2880. }
  2881. {
  2882. #ifdef CPPHTTPLIB_SSL_ENABLED
  2883. SSLClient cli(HOST, PORT);
  2884. cli.enable_server_certificate_verification(false);
  2885. #else
  2886. Client cli(HOST, PORT);
  2887. #endif
  2888. auto res = cli.Get("/hi");
  2889. ASSERT_TRUE(res);
  2890. EXPECT_EQ(StatusCode::OK_200, res->status);
  2891. EXPECT_EQ("Hello World!\n", res->body);
  2892. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2893. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2894. }
  2895. {
  2896. #ifdef CPPHTTPLIB_SSL_ENABLED
  2897. SSLClient cli(HOST, PORT);
  2898. cli.enable_server_certificate_verification(false);
  2899. #else
  2900. Client cli(HOST, PORT);
  2901. #endif
  2902. auto res = cli.Get("/aaa");
  2903. ASSERT_TRUE(res);
  2904. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2905. EXPECT_EQ("Error", res->body);
  2906. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2907. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2908. }
  2909. }
  2910. TEST(RequestHandlerTest, PreRequestHandler) {
  2911. auto route_path = "/user/:user";
  2912. Server svr;
  2913. svr.Get("/hi", [](const Request &, Response &res) {
  2914. res.set_content("hi", "text/plain");
  2915. });
  2916. svr.Get(route_path, [](const Request &req, Response &res) {
  2917. res.set_content(req.path_params.at("user"), "text/plain");
  2918. });
  2919. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2920. if (req.matched_route == route_path) {
  2921. auto user = req.path_params.at("user");
  2922. if (user != "john") {
  2923. res.status = StatusCode::Forbidden_403;
  2924. res.set_content("error", "text/html");
  2925. return Server::HandlerResponse::Handled;
  2926. }
  2927. }
  2928. return Server::HandlerResponse::Unhandled;
  2929. });
  2930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2931. auto se = detail::scope_exit([&] {
  2932. svr.stop();
  2933. thread.join();
  2934. ASSERT_FALSE(svr.is_running());
  2935. });
  2936. svr.wait_until_ready();
  2937. Client cli(HOST, PORT);
  2938. {
  2939. auto res = cli.Get("/hi");
  2940. ASSERT_TRUE(res);
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. EXPECT_EQ("hi", res->body);
  2943. }
  2944. {
  2945. auto res = cli.Get("/user/john");
  2946. ASSERT_TRUE(res);
  2947. EXPECT_EQ(StatusCode::OK_200, res->status);
  2948. EXPECT_EQ("john", res->body);
  2949. }
  2950. {
  2951. auto res = cli.Get("/user/invalid-user");
  2952. ASSERT_TRUE(res);
  2953. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2954. EXPECT_EQ("error", res->body);
  2955. }
  2956. }
  2957. // The pre-request handler must run before the request body is read, so a
  2958. // rejected request never forces the server to buffer a (potentially large)
  2959. // body. Here the posted body is larger than the payload limit: if the body
  2960. // were read first the server would answer 413, but because the pre-request
  2961. // handler runs first it answers 403 and the body is never read.
  2962. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2963. Server svr;
  2964. svr.set_payload_max_length(8);
  2965. auto handler_ran = false;
  2966. svr.Post("/reject", [&](const Request &req, Response &res) {
  2967. handler_ran = true;
  2968. res.set_content(req.body, "text/plain");
  2969. });
  2970. svr.Post("/accept", [](const Request &req, Response &res) {
  2971. res.set_content(req.body, "text/plain");
  2972. });
  2973. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2974. if (req.matched_route == "/reject") {
  2975. res.status = StatusCode::Forbidden_403;
  2976. res.set_content("denied", "text/plain");
  2977. return Server::HandlerResponse::Handled;
  2978. }
  2979. return Server::HandlerResponse::Unhandled;
  2980. });
  2981. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2982. auto se = detail::scope_exit([&] {
  2983. svr.stop();
  2984. thread.join();
  2985. ASSERT_FALSE(svr.is_running());
  2986. });
  2987. svr.wait_until_ready();
  2988. Client cli(HOST, PORT);
  2989. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2990. // rejects with 403 before the body is read, so 413 is never reached.
  2991. {
  2992. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2993. ASSERT_TRUE(res);
  2994. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2995. EXPECT_EQ("denied", res->body);
  2996. EXPECT_FALSE(handler_ran);
  2997. }
  2998. // An approved route still reads the body and enforces the payload limit.
  2999. {
  3000. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3001. ASSERT_TRUE(res);
  3002. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3003. }
  3004. }
  3005. TEST(UserDataTest, BasicOperations) {
  3006. httplib::UserData ud;
  3007. // Initially empty
  3008. EXPECT_FALSE(ud.has("key"));
  3009. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3010. // set and get
  3011. ud.set("key", 42);
  3012. EXPECT_TRUE(ud.has("key"));
  3013. auto *p = ud.get<int>("key");
  3014. ASSERT_NE(nullptr, p);
  3015. EXPECT_EQ(42, *p);
  3016. // Type mismatch → nullptr
  3017. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3018. // Overwrite with different type
  3019. ud.set("key", std::string("hello"));
  3020. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3021. auto *s = ud.get<std::string>("key");
  3022. ASSERT_NE(nullptr, s);
  3023. EXPECT_EQ("hello", *s);
  3024. // erase
  3025. ud.erase("key");
  3026. EXPECT_FALSE(ud.has("key"));
  3027. // clear
  3028. ud.set("a", 1);
  3029. ud.set("b", 2);
  3030. ud.clear();
  3031. EXPECT_FALSE(ud.has("a"));
  3032. EXPECT_FALSE(ud.has("b"));
  3033. }
  3034. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3035. struct AuthCtx {
  3036. std::string user_id;
  3037. };
  3038. Server svr;
  3039. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3040. res.user_data.set("auth", AuthCtx{"alice"});
  3041. return Server::HandlerResponse::Unhandled;
  3042. });
  3043. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3044. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3045. ASSERT_NE(nullptr, ctx);
  3046. res.set_content("Hello " + ctx->user_id, "text/plain");
  3047. });
  3048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3049. auto se = detail::scope_exit([&] {
  3050. svr.stop();
  3051. thread.join();
  3052. ASSERT_FALSE(svr.is_running());
  3053. });
  3054. svr.wait_until_ready();
  3055. Client cli(HOST, PORT);
  3056. auto res = cli.Get("/me");
  3057. ASSERT_TRUE(res);
  3058. EXPECT_EQ(StatusCode::OK_200, res->status);
  3059. EXPECT_EQ("Hello alice", res->body);
  3060. }
  3061. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3062. struct RoleCtx {
  3063. std::string role;
  3064. };
  3065. Server svr;
  3066. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3067. res.user_data.set("role", RoleCtx{"admin"});
  3068. return Server::HandlerResponse::Unhandled;
  3069. });
  3070. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3071. auto *ctx = res.user_data.get<RoleCtx>("role");
  3072. ASSERT_NE(nullptr, ctx);
  3073. res.set_content(ctx->role, "text/plain");
  3074. });
  3075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3076. auto se = detail::scope_exit([&] {
  3077. svr.stop();
  3078. thread.join();
  3079. ASSERT_FALSE(svr.is_running());
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, PORT);
  3083. auto res = cli.Get("/role");
  3084. ASSERT_TRUE(res);
  3085. EXPECT_EQ(StatusCode::OK_200, res->status);
  3086. EXPECT_EQ("admin", res->body);
  3087. }
  3088. TEST(InvalidFormatTest, StatusCode) {
  3089. Server svr;
  3090. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3091. res.set_content("Hello World!\n", "text/plain");
  3092. res.status = 9999; // Status should be a three-digit code...
  3093. });
  3094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3095. auto se = detail::scope_exit([&] {
  3096. svr.stop();
  3097. thread.join();
  3098. ASSERT_FALSE(svr.is_running());
  3099. });
  3100. svr.wait_until_ready();
  3101. {
  3102. Client cli(HOST, PORT);
  3103. auto res = cli.Get("/hi");
  3104. ASSERT_FALSE(res);
  3105. }
  3106. }
  3107. TEST(URLFragmentTest, WithFragment) {
  3108. Server svr;
  3109. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3110. EXPECT_TRUE(req.target == "/hi");
  3111. });
  3112. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3113. auto se = detail::scope_exit([&] {
  3114. svr.stop();
  3115. thread.join();
  3116. ASSERT_FALSE(svr.is_running());
  3117. });
  3118. svr.wait_until_ready();
  3119. {
  3120. Client cli(HOST, PORT);
  3121. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3122. EXPECT_TRUE(res);
  3123. EXPECT_EQ(StatusCode::OK_200, res->status);
  3124. res = cli.Get("/hi%23key1=val1=key2=val2");
  3125. EXPECT_TRUE(res);
  3126. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3127. }
  3128. }
  3129. TEST(HeaderWriter, SetHeaderWriter) {
  3130. Server svr;
  3131. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3132. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3133. return detail::write_headers(strm, hdrs);
  3134. });
  3135. svr.Get("/hi", [](const Request &req, Response &res) {
  3136. auto it = req.headers.find("CustomClientHeader");
  3137. EXPECT_TRUE(it != req.headers.end());
  3138. EXPECT_EQ(it->second, "CustomClientValue");
  3139. res.set_content("Hello World!\n", "text/plain");
  3140. });
  3141. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3142. auto se = detail::scope_exit([&] {
  3143. svr.stop();
  3144. thread.join();
  3145. ASSERT_FALSE(svr.is_running());
  3146. });
  3147. svr.wait_until_ready();
  3148. {
  3149. Client cli(HOST, PORT);
  3150. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3151. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3152. return detail::write_headers(strm, hdrs);
  3153. });
  3154. auto res = cli.Get("/hi");
  3155. EXPECT_TRUE(res);
  3156. EXPECT_EQ(StatusCode::OK_200, res->status);
  3157. auto it = res->headers.find("CustomServerHeader");
  3158. EXPECT_TRUE(it != res->headers.end());
  3159. EXPECT_EQ(it->second, "CustomServerValue");
  3160. }
  3161. }
  3162. class ServerTest : public ::testing::Test {
  3163. protected:
  3164. ServerTest()
  3165. : cli_(HOST, PORT)
  3166. #ifdef CPPHTTPLIB_SSL_ENABLED
  3167. ,
  3168. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3169. #endif
  3170. {
  3171. #ifdef CPPHTTPLIB_SSL_ENABLED
  3172. cli_.enable_server_certificate_verification(false);
  3173. #endif
  3174. // Allow LARGE_DATA (100MB) responses
  3175. cli_.set_payload_max_length(200 * 1024 * 1024);
  3176. }
  3177. virtual void SetUp() {
  3178. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3179. svr_.set_payload_max_length(200 * 1024 * 1024);
  3180. svr_.set_mount_point("/", "./www");
  3181. svr_.set_mount_point("/mount", "./www2");
  3182. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3183. svr_.Get("/hi",
  3184. [&](const Request & /*req*/, Response &res) {
  3185. res.set_content("Hello World!", "text/plain");
  3186. })
  3187. .Get("/file_content",
  3188. [&](const Request & /*req*/, Response &res) {
  3189. res.set_file_content("./www/dir/test.html");
  3190. })
  3191. .Get("/file_content_with_content_type",
  3192. [&](const Request & /*req*/, Response &res) {
  3193. res.set_file_content("./www/file", "text/plain");
  3194. })
  3195. .Get("/invalid_file_content",
  3196. [&](const Request & /*req*/, Response &res) {
  3197. res.set_file_content("./www/dir/invalid_file_path");
  3198. })
  3199. .Get("/http_response_splitting",
  3200. [&](const Request & /*req*/, Response &res) {
  3201. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3202. EXPECT_EQ(0U, res.headers.size());
  3203. EXPECT_FALSE(res.has_header("a"));
  3204. res.set_header("a", "1\nSet-Cookie: a=1");
  3205. EXPECT_EQ(0U, res.headers.size());
  3206. EXPECT_FALSE(res.has_header("a"));
  3207. res.set_header("a", "1\rSet-Cookie: a=1");
  3208. EXPECT_EQ(0U, res.headers.size());
  3209. EXPECT_FALSE(res.has_header("a"));
  3210. res.set_header("a\r\nb", "0");
  3211. EXPECT_EQ(0U, res.headers.size());
  3212. EXPECT_FALSE(res.has_header("a"));
  3213. res.set_header("a\rb", "0");
  3214. EXPECT_EQ(0U, res.headers.size());
  3215. EXPECT_FALSE(res.has_header("a"));
  3216. res.set_header("a\nb", "0");
  3217. EXPECT_EQ(0U, res.headers.size());
  3218. EXPECT_FALSE(res.has_header("a"));
  3219. res.set_redirect("1\r\nSet-Cookie: a=1");
  3220. EXPECT_EQ(0U, res.headers.size());
  3221. EXPECT_FALSE(res.has_header("Location"));
  3222. })
  3223. .Get("/slow",
  3224. [&](const Request & /*req*/, Response &res) {
  3225. std::this_thread::sleep_for(std::chrono::seconds(4));
  3226. res.set_content("slow", "text/plain");
  3227. })
  3228. #if 0
  3229. .Post("/slowpost",
  3230. [&](const Request & /*req*/, Response &res) {
  3231. std::this_thread::sleep_for(std::chrono::seconds(2));
  3232. res.set_content("slow", "text/plain");
  3233. })
  3234. #endif
  3235. .Get("/remote_addr",
  3236. [&](const Request &req, Response &res) {
  3237. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3238. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3239. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3240. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3241. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3242. #endif
  3243. res.set_content(req.remote_addr, "text/plain");
  3244. })
  3245. .Get("/local_addr",
  3246. [&](const Request &req, Response &res) {
  3247. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3248. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3249. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3250. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3251. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3252. #endif
  3253. auto local_addr = req.local_addr;
  3254. auto local_port = std::to_string(req.local_port);
  3255. res.set_content(local_addr.append(":").append(local_port),
  3256. "text/plain");
  3257. })
  3258. .Get("/endwith%",
  3259. [&](const Request & /*req*/, Response &res) {
  3260. res.set_content("Hello World!", "text/plain");
  3261. })
  3262. .Get("/a\\+\\+b",
  3263. [&](const Request &req, Response &res) {
  3264. ASSERT_TRUE(req.has_param("a +b"));
  3265. auto val = req.get_param_value("a +b");
  3266. res.set_content(val, "text/plain");
  3267. })
  3268. .Get("/", [&](const Request & /*req*/,
  3269. Response &res) { res.set_redirect("/hi"); })
  3270. .Post("/1",
  3271. [](const Request & /*req*/, Response &res) {
  3272. res.set_redirect("/2", StatusCode::SeeOther_303);
  3273. })
  3274. .Get("/2",
  3275. [](const Request & /*req*/, Response &res) {
  3276. res.set_content("redirected.", "text/plain");
  3277. res.status = StatusCode::OK_200;
  3278. })
  3279. .Post("/person",
  3280. [&](const Request &req, Response &res) {
  3281. if (req.has_param("name") && req.has_param("note")) {
  3282. persons_[req.get_param_value("name")] =
  3283. req.get_param_value("note");
  3284. } else {
  3285. res.status = StatusCode::BadRequest_400;
  3286. }
  3287. })
  3288. .Put("/person",
  3289. [&](const Request &req, Response &res) {
  3290. if (req.has_param("name") && req.has_param("note")) {
  3291. persons_[req.get_param_value("name")] =
  3292. req.get_param_value("note");
  3293. } else {
  3294. res.status = StatusCode::BadRequest_400;
  3295. }
  3296. })
  3297. .Get("/person/(.*)",
  3298. [&](const Request &req, Response &res) {
  3299. string name = req.matches[1];
  3300. if (persons_.find(name) != persons_.end()) {
  3301. auto note = persons_[name];
  3302. res.set_content(note, "text/plain");
  3303. } else {
  3304. res.status = StatusCode::NotFound_404;
  3305. }
  3306. })
  3307. .Delete("/person",
  3308. [&](const Request &req, Response &res) {
  3309. if (req.has_param("name")) {
  3310. string name = req.get_param_value("name");
  3311. if (persons_.find(name) != persons_.end()) {
  3312. persons_.erase(name);
  3313. res.set_content("DELETED", "text/plain");
  3314. } else {
  3315. res.status = StatusCode::NotFound_404;
  3316. }
  3317. } else {
  3318. res.status = StatusCode::BadRequest_400;
  3319. }
  3320. })
  3321. .Post("/x-www-form-urlencoded-json",
  3322. [&](const Request &req, Response &res) {
  3323. auto json = req.get_param_value("json");
  3324. ASSERT_EQ(JSON_DATA, json);
  3325. res.set_content(json, "appliation/json");
  3326. res.status = StatusCode::OK_200;
  3327. })
  3328. .Get("/streamed-chunked",
  3329. [&](const Request & /*req*/, Response &res) {
  3330. res.set_chunked_content_provider(
  3331. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3332. sink.os << "123";
  3333. sink.os << "456";
  3334. sink.os << "789";
  3335. sink.done();
  3336. return true;
  3337. });
  3338. })
  3339. .Get("/streamed-chunked-with-prohibited-trailer",
  3340. [&](const Request & /*req*/, Response &res) {
  3341. auto i = new int(0);
  3342. // Declare both a prohibited trailer (Content-Length) and an
  3343. // allowed one
  3344. res.set_header("Trailer", "Content-Length, X-Allowed");
  3345. res.set_chunked_content_provider(
  3346. "text/plain",
  3347. [i](size_t /*offset*/, DataSink &sink) {
  3348. switch (*i) {
  3349. case 0: sink.os << "123"; break;
  3350. case 1: sink.os << "456"; break;
  3351. case 2: sink.os << "789"; break;
  3352. case 3: {
  3353. sink.done_with_trailer(
  3354. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3355. } break;
  3356. }
  3357. (*i)++;
  3358. return true;
  3359. },
  3360. [i](bool success) {
  3361. EXPECT_TRUE(success);
  3362. delete i;
  3363. });
  3364. })
  3365. .Get("/streamed-chunked2",
  3366. [&](const Request & /*req*/, Response &res) {
  3367. auto i = new int(0);
  3368. res.set_chunked_content_provider(
  3369. "text/plain",
  3370. [i](size_t /*offset*/, DataSink &sink) {
  3371. switch (*i) {
  3372. case 0: sink.os << "123"; break;
  3373. case 1: sink.os << "456"; break;
  3374. case 2: sink.os << "789"; break;
  3375. case 3: sink.done(); break;
  3376. }
  3377. (*i)++;
  3378. return true;
  3379. },
  3380. [i](bool success) {
  3381. EXPECT_TRUE(success);
  3382. delete i;
  3383. });
  3384. })
  3385. .Get("/streamed-chunked-with-trailer",
  3386. [&](const Request & /*req*/, Response &res) {
  3387. auto i = new int(0);
  3388. res.set_header("Trailer", "Dummy1, Dummy2");
  3389. res.set_chunked_content_provider(
  3390. "text/plain",
  3391. [i](size_t /*offset*/, DataSink &sink) {
  3392. switch (*i) {
  3393. case 0: sink.os << "123"; break;
  3394. case 1: sink.os << "456"; break;
  3395. case 2: sink.os << "789"; break;
  3396. case 3: {
  3397. sink.done_with_trailer(
  3398. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3399. } break;
  3400. }
  3401. (*i)++;
  3402. return true;
  3403. },
  3404. [i](bool success) {
  3405. EXPECT_TRUE(success);
  3406. delete i;
  3407. });
  3408. })
  3409. .Get("/streamed",
  3410. [&](const Request & /*req*/, Response &res) {
  3411. res.set_content_provider(
  3412. 6, "text/plain",
  3413. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3414. sink.os << (offset < 3 ? "a" : "b");
  3415. return true;
  3416. });
  3417. })
  3418. .Get("/streamed-without-length",
  3419. [&](const Request & /*req*/, Response &res) {
  3420. auto data = new std::string("abcdefg");
  3421. res.set_content_provider(
  3422. "text/plain",
  3423. [data](size_t offset, DataSink &sink) {
  3424. if (offset < data->size()) {
  3425. sink.os << data->substr(offset);
  3426. }
  3427. sink.done();
  3428. return true;
  3429. },
  3430. [data](bool success) {
  3431. EXPECT_TRUE(success);
  3432. delete data;
  3433. });
  3434. })
  3435. .Get("/streamed-with-range",
  3436. [&](const Request &req, Response &res) {
  3437. auto data = new std::string("abcdefg");
  3438. res.set_content_provider(
  3439. data->size(), "text/plain",
  3440. [data](size_t offset, size_t length, DataSink &sink) {
  3441. size_t DATA_CHUNK_SIZE = 4;
  3442. const auto &d = *data;
  3443. auto out_len =
  3444. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3445. auto ret =
  3446. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3447. EXPECT_TRUE(ret);
  3448. return true;
  3449. },
  3450. [data, &req](bool success) {
  3451. EXPECT_EQ(success, !req.has_param("error"));
  3452. delete data;
  3453. });
  3454. })
  3455. .Get("/streamed-cancel",
  3456. [&](const Request & /*req*/, Response &res) {
  3457. res.set_content_provider(
  3458. size_t(-1), "text/plain",
  3459. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3460. sink.os << "data_chunk";
  3461. return true;
  3462. });
  3463. })
  3464. .Get("/regex-with-delimiter",
  3465. [&](const Request &req, Response & /*res*/) {
  3466. ASSERT_TRUE(req.has_param("key"));
  3467. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3468. })
  3469. .Get("/with-range",
  3470. [&](const Request & /*req*/, Response &res) {
  3471. res.set_content("abcdefg", "text/plain");
  3472. })
  3473. .Get("/test-start-time",
  3474. [&](const Request &req, Response & /*res*/) {
  3475. EXPECT_NE(req.start_time_,
  3476. std::chrono::steady_clock::time_point::min());
  3477. })
  3478. .Get("/with-range-customized-response",
  3479. [&](const Request & /*req*/, Response &res) {
  3480. res.status = StatusCode::BadRequest_400;
  3481. res.set_content(JSON_DATA, "application/json");
  3482. })
  3483. .Post("/chunked",
  3484. [&](const Request &req, Response & /*res*/) {
  3485. EXPECT_EQ(req.body, "dechunked post body");
  3486. })
  3487. .Post("/large-chunked",
  3488. [&](const Request &req, Response & /*res*/) {
  3489. std::string expected(6 * 30 * 1024u, 'a');
  3490. EXPECT_EQ(req.body, expected);
  3491. })
  3492. .Post("/multipart",
  3493. [&](const Request &req, Response & /*res*/) {
  3494. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3495. req.form.get_field_count("text2") +
  3496. req.form.get_field_count("file3") +
  3497. req.form.get_field_count("file4"));
  3498. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3499. req.form.get_file_count("file2"));
  3500. ASSERT_TRUE(!req.form.has_file("???"));
  3501. ASSERT_TRUE(!req.form.has_field("???"));
  3502. ASSERT_TRUE(req.body.empty());
  3503. {
  3504. const auto &text = req.form.get_field("text1");
  3505. EXPECT_EQ("text default", text);
  3506. }
  3507. {
  3508. const auto &text = req.form.get_field("text2");
  3509. EXPECT_EQ("aωb", text);
  3510. }
  3511. {
  3512. const auto &file = req.form.get_file("file1");
  3513. EXPECT_EQ("hello.txt", file.filename);
  3514. EXPECT_EQ("text/plain", file.content_type);
  3515. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3516. }
  3517. {
  3518. const auto &file = req.form.get_file("file2");
  3519. EXPECT_EQ("world.json", file.filename);
  3520. EXPECT_EQ("application/json", file.content_type);
  3521. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3522. }
  3523. {
  3524. const auto &text = req.form.get_field("file3");
  3525. EXPECT_EQ(0u, text.size());
  3526. }
  3527. {
  3528. const auto &text = req.form.get_field("file4");
  3529. EXPECT_EQ(0u, text.size());
  3530. }
  3531. })
  3532. .Post("/multipart/multi_file_values",
  3533. [&](const Request &req, Response & /*res*/) {
  3534. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3535. req.form.get_field_count("multi_text1"));
  3536. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3537. ASSERT_TRUE(!req.form.has_file("???"));
  3538. ASSERT_TRUE(!req.form.has_field("???"));
  3539. ASSERT_TRUE(req.body.empty());
  3540. {
  3541. const auto &text = req.form.get_field("text");
  3542. EXPECT_EQ("default text", text);
  3543. }
  3544. {
  3545. const auto &text1_values = req.form.get_fields("multi_text1");
  3546. EXPECT_EQ(2u, text1_values.size());
  3547. EXPECT_EQ("aaaaa", text1_values[0]);
  3548. EXPECT_EQ("bbbbb", text1_values[1]);
  3549. }
  3550. {
  3551. const auto &file1_values = req.form.get_files("multi_file1");
  3552. EXPECT_EQ(2u, file1_values.size());
  3553. auto file1 = file1_values[0];
  3554. EXPECT_EQ(file1.filename, "hello.txt");
  3555. EXPECT_EQ(file1.content_type, "text/plain");
  3556. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3557. auto file2 = file1_values[1];
  3558. EXPECT_EQ(file2.filename, "world.json");
  3559. EXPECT_EQ(file2.content_type, "application/json");
  3560. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3561. }
  3562. })
  3563. .Post("/empty",
  3564. [&](const Request &req, Response &res) {
  3565. EXPECT_EQ(req.body, "");
  3566. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3567. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3568. res.set_content("empty", "text/plain");
  3569. })
  3570. .Post("/empty-no-content-type",
  3571. [&](const Request &req, Response &res) {
  3572. EXPECT_EQ(req.body, "");
  3573. EXPECT_FALSE(req.has_header("Content-Type"));
  3574. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3575. res.set_content("empty-no-content-type", "text/plain");
  3576. })
  3577. .Post("/path-only",
  3578. [&](const Request &req, Response &res) {
  3579. EXPECT_EQ(req.body, "");
  3580. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3581. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3582. res.set_content("path-only", "text/plain");
  3583. })
  3584. .Post("/path-headers-only",
  3585. [&](const Request &req, Response &res) {
  3586. EXPECT_EQ(req.body, "");
  3587. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3588. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3589. EXPECT_EQ("world", req.get_header_value("hello"));
  3590. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3591. res.set_content("path-headers-only", "text/plain");
  3592. })
  3593. .Post("/post-large",
  3594. [&](const Request &req, Response &res) {
  3595. EXPECT_EQ(req.body, LARGE_DATA);
  3596. res.set_content(req.body, "text/plain");
  3597. })
  3598. .Post("/post-loopback",
  3599. [&](const Request &, Response &res,
  3600. ContentReader const &content_reader) {
  3601. std::string body;
  3602. content_reader([&](const char *data, size_t data_length) {
  3603. body.append(data, data_length);
  3604. return true;
  3605. });
  3606. res.set_content(body, "text/plain");
  3607. })
  3608. .Put("/put-loopback",
  3609. [&](const Request &, Response &res,
  3610. ContentReader const &content_reader) {
  3611. std::string body;
  3612. content_reader([&](const char *data, size_t data_length) {
  3613. body.append(data, data_length);
  3614. return true;
  3615. });
  3616. res.set_content(body, "text/plain");
  3617. })
  3618. .Patch("/patch-loopback",
  3619. [&](const Request &, Response &res,
  3620. ContentReader const &content_reader) {
  3621. std::string body;
  3622. content_reader([&](const char *data, size_t data_length) {
  3623. body.append(data, data_length);
  3624. return true;
  3625. });
  3626. res.set_content(body, "text/plain");
  3627. })
  3628. .Put("/empty-no-content-type",
  3629. [&](const Request &req, Response &res) {
  3630. EXPECT_EQ(req.body, "");
  3631. EXPECT_FALSE(req.has_header("Content-Type"));
  3632. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3633. res.set_content("empty-no-content-type", "text/plain");
  3634. })
  3635. .Put("/put",
  3636. [&](const Request &req, Response &res) {
  3637. EXPECT_EQ(req.body, "PUT");
  3638. res.set_content(req.body, "text/plain");
  3639. })
  3640. .Put("/put-large",
  3641. [&](const Request &req, Response &res) {
  3642. EXPECT_EQ(req.body, LARGE_DATA);
  3643. res.set_content(req.body, "text/plain");
  3644. })
  3645. .Patch("/patch",
  3646. [&](const Request &req, Response &res) {
  3647. EXPECT_EQ(req.body, "PATCH");
  3648. res.set_content(req.body, "text/plain");
  3649. })
  3650. .Delete("/delete",
  3651. [&](const Request & /*req*/, Response &res) {
  3652. res.set_content("DELETE", "text/plain");
  3653. })
  3654. .Delete("/delete-body",
  3655. [&](const Request &req, Response &res) {
  3656. EXPECT_EQ(req.body, "content");
  3657. res.set_content(req.body, "text/plain");
  3658. })
  3659. .Options(R"(\*)",
  3660. [&](const Request & /*req*/, Response &res) {
  3661. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3662. })
  3663. .Get("/request-target",
  3664. [&](const Request &req, Response & /*res*/) {
  3665. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3666. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3667. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3668. })
  3669. .Get("/long-query-value",
  3670. [&](const Request &req, Response & /*res*/) {
  3671. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3672. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3673. })
  3674. .Get("/too-long-query-value",
  3675. [&](const Request &req, Response & /*res*/) {
  3676. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3677. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3678. })
  3679. .Get("/array-param",
  3680. [&](const Request &req, Response & /*res*/) {
  3681. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3682. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3683. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3684. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3685. })
  3686. .Get("/array-param-values",
  3687. [&](const Request &req, Response & /*res*/) {
  3688. auto values = req.get_param_values("array");
  3689. EXPECT_EQ(3u, values.size());
  3690. EXPECT_EQ("value1", values[0]);
  3691. EXPECT_EQ("value2", values[1]);
  3692. EXPECT_EQ("value3", values[2]);
  3693. auto empty = req.get_param_values("nonexistent");
  3694. EXPECT_TRUE(empty.empty());
  3695. })
  3696. .Post("/validate-no-multiple-headers",
  3697. [&](const Request &req, Response & /*res*/) {
  3698. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3699. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3700. })
  3701. .Post("/content_receiver",
  3702. [&](const Request &req, Response &res,
  3703. const ContentReader &content_reader) {
  3704. if (req.is_multipart_form_data()) {
  3705. std::vector<FormData> items;
  3706. content_reader(
  3707. [&](const FormData &file) {
  3708. items.push_back(file);
  3709. return true;
  3710. },
  3711. [&](const char *data, size_t data_length) {
  3712. items.back().content.append(data, data_length);
  3713. return true;
  3714. });
  3715. EXPECT_EQ(5u, items.size());
  3716. {
  3717. const auto &file = get_file_value(items, "text1");
  3718. EXPECT_TRUE(file.filename.empty());
  3719. EXPECT_EQ("text default", file.content);
  3720. }
  3721. {
  3722. const auto &file = get_file_value(items, "text2");
  3723. EXPECT_TRUE(file.filename.empty());
  3724. EXPECT_EQ("aωb", file.content);
  3725. }
  3726. {
  3727. const auto &file = get_file_value(items, "file1");
  3728. EXPECT_EQ("hello.txt", file.filename);
  3729. EXPECT_EQ("text/plain", file.content_type);
  3730. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3731. }
  3732. {
  3733. const auto &file = get_file_value(items, "file2");
  3734. EXPECT_EQ("world.json", file.filename);
  3735. EXPECT_EQ("application/json", file.content_type);
  3736. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3737. }
  3738. {
  3739. const auto &file = get_file_value(items, "file3");
  3740. EXPECT_TRUE(file.filename.empty());
  3741. EXPECT_EQ("application/octet-stream", file.content_type);
  3742. EXPECT_EQ(0u, file.content.size());
  3743. }
  3744. } else {
  3745. std::string body;
  3746. content_reader([&](const char *data, size_t data_length) {
  3747. EXPECT_EQ(7U, data_length);
  3748. body.append(data, data_length);
  3749. return true;
  3750. });
  3751. EXPECT_EQ(body, "content");
  3752. res.set_content(body, "text/plain");
  3753. }
  3754. })
  3755. .Put("/content_receiver",
  3756. [&](const Request & /*req*/, Response &res,
  3757. const ContentReader &content_reader) {
  3758. std::string body;
  3759. content_reader([&](const char *data, size_t data_length) {
  3760. body.append(data, data_length);
  3761. return true;
  3762. });
  3763. EXPECT_EQ(body, "content");
  3764. res.set_content(body, "text/plain");
  3765. })
  3766. .Patch("/content_receiver",
  3767. [&](const Request & /*req*/, Response &res,
  3768. const ContentReader &content_reader) {
  3769. std::string body;
  3770. content_reader([&](const char *data, size_t data_length) {
  3771. body.append(data, data_length);
  3772. return true;
  3773. });
  3774. EXPECT_EQ(body, "content");
  3775. res.set_content(body, "text/plain");
  3776. })
  3777. .Post("/query-string-and-body",
  3778. [&](const Request &req, Response & /*res*/) {
  3779. ASSERT_TRUE(req.has_param("key"));
  3780. EXPECT_EQ(req.get_param_value("key"), "value");
  3781. EXPECT_EQ(req.body, "content");
  3782. })
  3783. .Get("/last-request",
  3784. [&](const Request &req, Response & /*res*/) {
  3785. EXPECT_EQ("close", req.get_header_value("Connection"));
  3786. })
  3787. .Get(R"(/redirect/(\d+))",
  3788. [&](const Request &req, Response &res) {
  3789. auto num = std::stoi(req.matches[1]) + 1;
  3790. std::string url = "/redirect/" + std::to_string(num);
  3791. res.set_redirect(url);
  3792. })
  3793. .Post("/binary",
  3794. [&](const Request &req, Response &res) {
  3795. EXPECT_EQ(4U, req.body.size());
  3796. EXPECT_EQ("application/octet-stream",
  3797. req.get_header_value("Content-Type"));
  3798. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3799. res.set_content(req.body, "application/octet-stream");
  3800. })
  3801. .Put("/binary",
  3802. [&](const Request &req, Response &res) {
  3803. EXPECT_EQ(4U, req.body.size());
  3804. EXPECT_EQ("application/octet-stream",
  3805. req.get_header_value("Content-Type"));
  3806. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3807. res.set_content(req.body, "application/octet-stream");
  3808. })
  3809. .Patch("/binary",
  3810. [&](const Request &req, Response &res) {
  3811. EXPECT_EQ(4U, req.body.size());
  3812. EXPECT_EQ("application/octet-stream",
  3813. req.get_header_value("Content-Type"));
  3814. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3815. res.set_content(req.body, "application/octet-stream");
  3816. })
  3817. .Delete("/binary",
  3818. [&](const Request &req, Response &res) {
  3819. EXPECT_EQ(4U, req.body.size());
  3820. EXPECT_EQ("application/octet-stream",
  3821. req.get_header_value("Content-Type"));
  3822. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3823. res.set_content(req.body, "application/octet-stream");
  3824. })
  3825. .Get("/issue1772",
  3826. [&](const Request & /*req*/, Response &res) {
  3827. res.status = 401;
  3828. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3829. })
  3830. .Delete("/issue609",
  3831. [](const httplib::Request &, httplib::Response &res,
  3832. const httplib::ContentReader &) {
  3833. res.set_content("ok", "text/plain");
  3834. })
  3835. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3836. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3837. .Get("/compress",
  3838. [&](const Request & /*req*/, Response &res) {
  3839. res.set_content(
  3840. "12345678901234567890123456789012345678901234567890123456789"
  3841. "01234567890123456789012345678901234567890",
  3842. "text/plain");
  3843. })
  3844. .Get("/compress-with-charset",
  3845. [&](const Request & /*req*/, Response &res) {
  3846. res.set_content(
  3847. "12345678901234567890123456789012345678901234567890123456789"
  3848. "01234567890123456789012345678901234567890",
  3849. "application/json; charset=utf-8");
  3850. })
  3851. .Get("/nocompress",
  3852. [&](const Request & /*req*/, Response &res) {
  3853. res.set_content(
  3854. "12345678901234567890123456789012345678901234567890123456789"
  3855. "01234567890123456789012345678901234567890",
  3856. "application/octet-stream");
  3857. })
  3858. .Post("/compress-multipart",
  3859. [&](const Request &req, Response & /*res*/) {
  3860. EXPECT_EQ(2u, req.form.fields.size());
  3861. ASSERT_TRUE(!req.form.has_field("???"));
  3862. {
  3863. const auto &text = req.form.get_field("key1");
  3864. EXPECT_EQ("test", text);
  3865. }
  3866. {
  3867. const auto &text = req.form.get_field("key2");
  3868. EXPECT_EQ("--abcdefg123", text);
  3869. }
  3870. })
  3871. #endif
  3872. ;
  3873. persons_["john"] = "programmer";
  3874. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3875. svr_.wait_until_ready();
  3876. }
  3877. virtual void TearDown() {
  3878. svr_.stop();
  3879. if (!request_threads_.empty()) {
  3880. std::this_thread::sleep_for(std::chrono::seconds(1));
  3881. for (auto &t : request_threads_) {
  3882. t.join();
  3883. }
  3884. }
  3885. t_.join();
  3886. }
  3887. map<string, string> persons_;
  3888. #ifdef CPPHTTPLIB_SSL_ENABLED
  3889. SSLClient cli_;
  3890. SSLServer svr_;
  3891. #else
  3892. Client cli_;
  3893. Server svr_;
  3894. #endif
  3895. thread t_;
  3896. std::vector<thread> request_threads_;
  3897. };
  3898. TEST_F(ServerTest, GetMethod200) {
  3899. auto res = cli_.Get("/hi");
  3900. ASSERT_TRUE(res);
  3901. EXPECT_EQ("HTTP/1.1", res->version);
  3902. EXPECT_EQ(StatusCode::OK_200, res->status);
  3903. EXPECT_EQ("OK", res->reason);
  3904. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3905. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3906. EXPECT_EQ("Hello World!", res->body);
  3907. }
  3908. TEST_F(ServerTest, GetEmptyFile) {
  3909. auto res = cli_.Get("/empty_file");
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(StatusCode::OK_200, res->status);
  3912. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3913. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3914. EXPECT_EQ("", res->body);
  3915. }
  3916. TEST_F(ServerTest, GetFileContent) {
  3917. auto res = cli_.Get("/file_content");
  3918. ASSERT_TRUE(res);
  3919. EXPECT_EQ(StatusCode::OK_200, res->status);
  3920. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3921. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3922. EXPECT_EQ("test.html", res->body);
  3923. }
  3924. TEST_F(ServerTest, GetFileContentWithRange) {
  3925. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3928. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3929. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3930. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3931. EXPECT_EQ("est", res->body);
  3932. }
  3933. TEST_F(ServerTest, GetFileContentWithContentType) {
  3934. auto res = cli_.Get("/file_content_with_content_type");
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ(StatusCode::OK_200, res->status);
  3937. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3938. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3939. EXPECT_EQ("file\n", res->body);
  3940. }
  3941. TEST_F(ServerTest, GetInvalidFileContent) {
  3942. auto res = cli_.Get("/invalid_file_content");
  3943. ASSERT_TRUE(res);
  3944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3945. }
  3946. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3947. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3948. ASSERT_TRUE(res);
  3949. EXPECT_EQ("HTTP/1.1", res->version);
  3950. EXPECT_EQ(StatusCode::OK_200, res->status);
  3951. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3952. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3953. EXPECT_EQ("Hello World!", res->body);
  3954. }
  3955. TEST_F(ServerTest, GetMethod302) {
  3956. auto res = cli_.Get("/");
  3957. ASSERT_TRUE(res);
  3958. EXPECT_EQ(StatusCode::Found_302, res->status);
  3959. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3960. }
  3961. TEST_F(ServerTest, GetMethod302Redirect) {
  3962. cli_.set_follow_location(true);
  3963. auto res = cli_.Get("/");
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. EXPECT_EQ("Hello World!", res->body);
  3967. EXPECT_EQ("/hi", res->location);
  3968. }
  3969. TEST_F(ServerTest, GetMethod404) {
  3970. auto res = cli_.Get("/invalid");
  3971. ASSERT_TRUE(res);
  3972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3973. }
  3974. TEST_F(ServerTest, HeadMethod200) {
  3975. auto res = cli_.Head("/hi");
  3976. ASSERT_TRUE(res);
  3977. EXPECT_EQ(StatusCode::OK_200, res->status);
  3978. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3979. EXPECT_TRUE(res->body.empty());
  3980. }
  3981. TEST_F(ServerTest, HeadMethod200Static) {
  3982. auto res = cli_.Head("/mount/dir/index.html");
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3986. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3987. EXPECT_TRUE(res->body.empty());
  3988. }
  3989. TEST_F(ServerTest, HeadMethod404) {
  3990. auto res = cli_.Head("/invalid");
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3993. EXPECT_TRUE(res->body.empty());
  3994. }
  3995. TEST_F(ServerTest, GetMethodPersonJohn) {
  3996. auto res = cli_.Get("/person/john");
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::OK_200, res->status);
  3999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4000. EXPECT_EQ("programmer", res->body);
  4001. }
  4002. TEST_F(ServerTest, PostMethod1) {
  4003. auto res = cli_.Get("/person/john1");
  4004. ASSERT_TRUE(res);
  4005. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4006. res = cli_.Post("/person", "name=john1&note=coder",
  4007. "application/x-www-form-urlencoded");
  4008. ASSERT_TRUE(res);
  4009. ASSERT_EQ(StatusCode::OK_200, res->status);
  4010. res = cli_.Get("/person/john1");
  4011. ASSERT_TRUE(res);
  4012. ASSERT_EQ(StatusCode::OK_200, res->status);
  4013. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4014. ASSERT_EQ("coder", res->body);
  4015. }
  4016. TEST_F(ServerTest, PostMethod2) {
  4017. auto res = cli_.Get("/person/john2");
  4018. ASSERT_TRUE(res);
  4019. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4020. Params params;
  4021. params.emplace("name", "john2");
  4022. params.emplace("note", "coder");
  4023. res = cli_.Post("/person", params);
  4024. ASSERT_TRUE(res);
  4025. ASSERT_EQ(StatusCode::OK_200, res->status);
  4026. res = cli_.Get("/person/john2");
  4027. ASSERT_TRUE(res);
  4028. ASSERT_EQ(StatusCode::OK_200, res->status);
  4029. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4030. ASSERT_EQ("coder", res->body);
  4031. }
  4032. TEST_F(ServerTest, PutMethod3) {
  4033. auto res = cli_.Get("/person/john3");
  4034. ASSERT_TRUE(res);
  4035. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4036. Params params;
  4037. params.emplace("name", "john3");
  4038. params.emplace("note", "coder");
  4039. res = cli_.Put("/person", params);
  4040. ASSERT_TRUE(res);
  4041. ASSERT_EQ(StatusCode::OK_200, res->status);
  4042. res = cli_.Get("/person/john3");
  4043. ASSERT_TRUE(res);
  4044. ASSERT_EQ(StatusCode::OK_200, res->status);
  4045. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4046. ASSERT_EQ("coder", res->body);
  4047. }
  4048. TEST_F(ServerTest, DeleteMethod1) {
  4049. auto res = cli_.Get("/person/john4");
  4050. ASSERT_TRUE(res);
  4051. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4052. Params params;
  4053. params.emplace("name", "john4");
  4054. params.emplace("note", "coder");
  4055. res = cli_.Post("/person", params);
  4056. ASSERT_TRUE(res);
  4057. ASSERT_EQ(StatusCode::OK_200, res->status);
  4058. res = cli_.Get("/person/john4");
  4059. ASSERT_TRUE(res);
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4062. ASSERT_EQ("coder", res->body);
  4063. Params delete_params;
  4064. delete_params.emplace("name", "john4");
  4065. res = cli_.Delete("/person", delete_params);
  4066. ASSERT_TRUE(res);
  4067. ASSERT_EQ(StatusCode::OK_200, res->status);
  4068. ASSERT_EQ("DELETED", res->body);
  4069. res = cli_.Get("/person/john4");
  4070. ASSERT_TRUE(res);
  4071. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4072. }
  4073. TEST_F(ServerTest, DeleteMethod2) {
  4074. auto res = cli_.Get("/person/john5");
  4075. ASSERT_TRUE(res);
  4076. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4077. Params params;
  4078. params.emplace("name", "john5");
  4079. params.emplace("note", "developer");
  4080. res = cli_.Post("/person", params);
  4081. ASSERT_TRUE(res);
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. res = cli_.Get("/person/john5");
  4084. ASSERT_TRUE(res);
  4085. ASSERT_EQ(StatusCode::OK_200, res->status);
  4086. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4087. ASSERT_EQ("developer", res->body);
  4088. Params delete_params;
  4089. delete_params.emplace("name", "john5");
  4090. Headers headers;
  4091. headers.emplace("Custom-Header", "test-value");
  4092. res = cli_.Delete("/person", headers, delete_params);
  4093. ASSERT_TRUE(res);
  4094. ASSERT_EQ(StatusCode::OK_200, res->status);
  4095. ASSERT_EQ("DELETED", res->body);
  4096. res = cli_.Get("/person/john5");
  4097. ASSERT_TRUE(res);
  4098. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4099. }
  4100. TEST_F(ServerTest, DeleteMethod3) {
  4101. auto res = cli_.Get("/person/john6");
  4102. ASSERT_TRUE(res);
  4103. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4104. Params params;
  4105. params.emplace("name", "john6");
  4106. params.emplace("note", "tester");
  4107. res = cli_.Post("/person", params);
  4108. ASSERT_TRUE(res);
  4109. ASSERT_EQ(StatusCode::OK_200, res->status);
  4110. res = cli_.Get("/person/john6");
  4111. ASSERT_TRUE(res);
  4112. ASSERT_EQ(StatusCode::OK_200, res->status);
  4113. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4114. ASSERT_EQ("tester", res->body);
  4115. Params delete_params;
  4116. delete_params.emplace("name", "john6");
  4117. Headers headers;
  4118. headers.emplace("Custom-Header", "test-value");
  4119. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4120. ASSERT_TRUE(res);
  4121. ASSERT_EQ(StatusCode::OK_200, res->status);
  4122. ASSERT_EQ("DELETED", res->body);
  4123. res = cli_.Get("/person/john6");
  4124. ASSERT_TRUE(res);
  4125. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4126. }
  4127. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4128. Params params;
  4129. params.emplace("json", JSON_DATA);
  4130. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4131. ASSERT_TRUE(res);
  4132. ASSERT_EQ(StatusCode::OK_200, res->status);
  4133. ASSERT_EQ(JSON_DATA, res->body);
  4134. }
  4135. TEST_F(ServerTest, PostEmptyContent) {
  4136. auto res = cli_.Post("/empty", "", "text/plain");
  4137. ASSERT_TRUE(res);
  4138. ASSERT_EQ(StatusCode::OK_200, res->status);
  4139. ASSERT_EQ("empty", res->body);
  4140. }
  4141. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4142. auto res = cli_.Post("/empty-no-content-type");
  4143. ASSERT_TRUE(res);
  4144. ASSERT_EQ(StatusCode::OK_200, res->status);
  4145. ASSERT_EQ("empty-no-content-type", res->body);
  4146. }
  4147. TEST_F(ServerTest, PostPathOnly) {
  4148. auto res = cli_.Post("/path-only");
  4149. ASSERT_TRUE(res);
  4150. ASSERT_EQ(StatusCode::OK_200, res->status);
  4151. ASSERT_EQ("path-only", res->body);
  4152. }
  4153. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4154. auto res = cli_.Post("/path-headers-only",
  4155. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4156. ASSERT_TRUE(res);
  4157. ASSERT_EQ(StatusCode::OK_200, res->status);
  4158. ASSERT_EQ("path-headers-only", res->body);
  4159. }
  4160. TEST_F(ServerTest, PostLarge) {
  4161. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4162. ASSERT_TRUE(res);
  4163. ASSERT_EQ(StatusCode::OK_200, res->status);
  4164. EXPECT_EQ(LARGE_DATA, res->body);
  4165. }
  4166. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4167. auto res = cli_.Put("/empty-no-content-type");
  4168. ASSERT_TRUE(res);
  4169. ASSERT_EQ(StatusCode::OK_200, res->status);
  4170. ASSERT_EQ("empty-no-content-type", res->body);
  4171. }
  4172. TEST_F(ServerTest, GetMethodDir) {
  4173. auto res = cli_.Get("/dir/");
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::OK_200, res->status);
  4176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4177. auto body = R"(<html>
  4178. <head>
  4179. </head>
  4180. <body>
  4181. <a href="/dir/test.html">Test</a>
  4182. <a href="/hi">hi</a>
  4183. </body>
  4184. </html>
  4185. )";
  4186. EXPECT_EQ(body, res->body);
  4187. }
  4188. TEST_F(ServerTest, GetMethodDirTest) {
  4189. auto res = cli_.Get("/dir/test.html");
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4193. EXPECT_EQ("test.html", res->body);
  4194. }
  4195. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4196. auto res = cli_.Get("/dir/../dir/test.html");
  4197. ASSERT_TRUE(res);
  4198. EXPECT_EQ(StatusCode::OK_200, res->status);
  4199. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4200. EXPECT_EQ("test.html", res->body);
  4201. }
  4202. TEST_F(ServerTest, GetMethodInvalidPath) {
  4203. auto res = cli_.Get("/dir/../test.html");
  4204. ASSERT_TRUE(res);
  4205. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4206. }
  4207. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4208. auto res = cli_.Get("/../www/dir/test.html");
  4209. ASSERT_TRUE(res);
  4210. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4211. }
  4212. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4213. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4216. }
  4217. TEST_F(ServerTest, GetMethodDirMountTest) {
  4218. auto res = cli_.Get("/mount/dir/test.html");
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::OK_200, res->status);
  4221. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4222. EXPECT_EQ("test.html", res->body);
  4223. }
  4224. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4225. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4226. ASSERT_TRUE(res);
  4227. EXPECT_EQ(StatusCode::OK_200, res->status);
  4228. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4229. EXPECT_EQ("test.html", res->body);
  4230. }
  4231. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4232. auto res = cli_.Get("/mount/dir/../test.html");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4235. }
  4236. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4237. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4240. }
  4241. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4242. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4245. }
  4246. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4247. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4250. }
  4251. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4252. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4253. ASSERT_TRUE(res);
  4254. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4255. }
  4256. TEST_F(ServerTest, PostMethod303) {
  4257. auto res = cli_.Post("/1", "body", "text/plain");
  4258. ASSERT_TRUE(res);
  4259. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4260. EXPECT_EQ("/2", res->get_header_value("Location"));
  4261. }
  4262. TEST_F(ServerTest, PostMethod303Redirect) {
  4263. cli_.set_follow_location(true);
  4264. auto res = cli_.Post("/1", "body", "text/plain");
  4265. ASSERT_TRUE(res);
  4266. EXPECT_EQ(StatusCode::OK_200, res->status);
  4267. EXPECT_EQ("redirected.", res->body);
  4268. EXPECT_EQ("/2", res->location);
  4269. }
  4270. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4271. auto res = cli_.Get("/dir/test.abcde");
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4275. EXPECT_EQ("abcde", res->body);
  4276. }
  4277. TEST_F(ServerTest, StaticFileRange) {
  4278. auto res =
  4279. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4282. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4283. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4284. EXPECT_EQ(true, res->has_header("Content-Range"));
  4285. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4286. EXPECT_EQ(std::string("cd"), res->body);
  4287. }
  4288. TEST_F(ServerTest, StaticFileRanges) {
  4289. auto res = cli_.Get("/dir/test.abcde",
  4290. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4291. ASSERT_TRUE(res);
  4292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4293. EXPECT_TRUE(
  4294. res->get_header_value("Content-Type")
  4295. .find(
  4296. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4297. 0);
  4298. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4299. }
  4300. TEST_F(ServerTest, StaticFileRangeHead) {
  4301. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4304. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4305. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4306. EXPECT_EQ(true, res->has_header("Content-Range"));
  4307. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4308. }
  4309. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4310. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4311. ASSERT_TRUE(res);
  4312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4314. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4315. EXPECT_EQ(true, res->has_header("Content-Range"));
  4316. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4317. res->get_header_value("Content-Range"));
  4318. EXPECT_EQ("LAST\n", res->body);
  4319. }
  4320. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4321. auto res =
  4322. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4326. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4327. EXPECT_EQ(true, res->has_header("Content-Range"));
  4328. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4329. }
  4330. TEST_F(ServerTest, StaticFileBigFile) {
  4331. auto res = cli_.Get("/dir/1MB.txt");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4335. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4336. }
  4337. TEST_F(ServerTest, InvalidBaseDirMount) {
  4338. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4339. }
  4340. TEST_F(ServerTest, Binary) {
  4341. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4342. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4343. "application/octet-stream");
  4344. ASSERT_TRUE(res);
  4345. ASSERT_EQ(StatusCode::OK_200, res->status);
  4346. ASSERT_EQ(4U, res->body.size());
  4347. res = cli_.Put("/binary", binary.data(), binary.size(),
  4348. "application/octet-stream");
  4349. ASSERT_TRUE(res);
  4350. ASSERT_EQ(StatusCode::OK_200, res->status);
  4351. ASSERT_EQ(4U, res->body.size());
  4352. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4353. "application/octet-stream");
  4354. ASSERT_TRUE(res);
  4355. ASSERT_EQ(StatusCode::OK_200, res->status);
  4356. ASSERT_EQ(4U, res->body.size());
  4357. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4358. "application/octet-stream");
  4359. ASSERT_TRUE(res);
  4360. ASSERT_EQ(StatusCode::OK_200, res->status);
  4361. ASSERT_EQ(4U, res->body.size());
  4362. }
  4363. TEST_F(ServerTest, BinaryString) {
  4364. auto binary = std::string("\x00\x01\x02\x03", 4);
  4365. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4366. ASSERT_TRUE(res);
  4367. ASSERT_EQ(StatusCode::OK_200, res->status);
  4368. ASSERT_EQ(4U, res->body.size());
  4369. res = cli_.Put("/binary", binary, "application/octet-stream");
  4370. ASSERT_TRUE(res);
  4371. ASSERT_EQ(StatusCode::OK_200, res->status);
  4372. ASSERT_EQ(4U, res->body.size());
  4373. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4374. ASSERT_TRUE(res);
  4375. ASSERT_EQ(StatusCode::OK_200, res->status);
  4376. ASSERT_EQ(4U, res->body.size());
  4377. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4378. ASSERT_TRUE(res);
  4379. ASSERT_EQ(StatusCode::OK_200, res->status);
  4380. ASSERT_EQ(4U, res->body.size());
  4381. }
  4382. TEST_F(ServerTest, EmptyRequest) {
  4383. auto res = cli_.Get("");
  4384. ASSERT_TRUE(!res);
  4385. EXPECT_EQ(Error::Connection, res.error());
  4386. }
  4387. TEST_F(ServerTest, LongRequest) {
  4388. std::string request;
  4389. for (size_t i = 0; i < 545; i++) {
  4390. request += "/TooLongRequest";
  4391. }
  4392. request += "OK";
  4393. auto res = cli_.Get(request.c_str());
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4396. }
  4397. TEST_F(ServerTest, TooLongRequest) {
  4398. std::string request;
  4399. for (size_t i = 0; i < 546; i++) {
  4400. request += "/TooLongRequest";
  4401. }
  4402. request += "_NG";
  4403. auto start = std::chrono::high_resolution_clock::now();
  4404. cli_.set_keep_alive(true);
  4405. auto res = cli_.Get(request.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, AlmostTooLongRequest) {
  4417. // test for #2046 - URI length check shouldn't include other content on req
  4418. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4419. // leading /, space, HTTP/1.1)
  4420. std::string request =
  4421. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4422. auto res = cli_.Get(request.c_str());
  4423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4425. }
  4426. TEST_F(ServerTest, LongHeader) {
  4427. Request req;
  4428. req.method = "GET";
  4429. req.path = "/hi";
  4430. std::string host_and_port;
  4431. host_and_port += HOST;
  4432. host_and_port += ":";
  4433. host_and_port += std::to_string(PORT);
  4434. req.headers.emplace("Host", host_and_port.c_str());
  4435. req.headers.emplace("Accept", "*/*");
  4436. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4437. req.headers.emplace(
  4438. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4464. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4465. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4466. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4467. "@@@@@@@@@@@@@@@@");
  4468. auto res = std::make_shared<Response>();
  4469. auto error = Error::Success;
  4470. auto ret = cli_.send(req, *res, error);
  4471. ASSERT_TRUE(ret);
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. }
  4474. TEST_F(ServerTest, LongQueryValue) {
  4475. auto start = std::chrono::high_resolution_clock::now();
  4476. cli_.set_keep_alive(true);
  4477. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4478. auto end = std::chrono::high_resolution_clock::now();
  4479. auto elapsed =
  4480. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4481. .count();
  4482. ASSERT_TRUE(res);
  4483. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4484. EXPECT_LE(elapsed, 1000);
  4485. EXPECT_EQ("close", res->get_header_value("Connection"));
  4486. EXPECT_FALSE(cli_.is_socket_open());
  4487. }
  4488. TEST_F(ServerTest, TooLongQueryValue) {
  4489. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4490. ASSERT_FALSE(res);
  4491. EXPECT_EQ(Error::Read, res.error());
  4492. }
  4493. TEST_F(ServerTest, TooLongHeader) {
  4494. Request req;
  4495. req.method = "GET";
  4496. req.path = "/hi";
  4497. std::string host_and_port;
  4498. host_and_port += HOST;
  4499. host_and_port += ":";
  4500. host_and_port += std::to_string(PORT);
  4501. req.headers.emplace("Host", host_and_port.c_str());
  4502. req.headers.emplace("Accept", "*/*");
  4503. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4504. req.headers.emplace(
  4505. "Header-Name",
  4506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4527. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4528. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4529. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4530. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4531. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4532. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4533. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4534. "@@@@@@@@@@@@@@@@@");
  4535. auto res = std::make_shared<Response>();
  4536. auto error = Error::Success;
  4537. auto ret = cli_.send(req, *res, error);
  4538. ASSERT_TRUE(ret);
  4539. EXPECT_EQ(StatusCode::OK_200, res->status);
  4540. }
  4541. TEST_F(ServerTest, HeaderCountAtLimit) {
  4542. // Test with headers just under the 100 limit
  4543. httplib::Headers headers;
  4544. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4545. // This should keep us just under the 100 header limit
  4546. for (int i = 0; i < 95; i++) {
  4547. std::string name = "X-Test-Header-" + std::to_string(i);
  4548. std::string value = "value" + std::to_string(i);
  4549. headers.emplace(name, value);
  4550. }
  4551. // This should work fine as we're under the limit
  4552. auto res = cli_.Get("/hi", headers);
  4553. EXPECT_TRUE(res);
  4554. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4555. }
  4556. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4557. // Test with many headers to exceed the 100 limit
  4558. httplib::Headers headers;
  4559. // Add 150 headers to definitely exceed the 100 limit
  4560. for (int i = 0; i < 150; i++) {
  4561. std::string name = "X-Test-Header-" + std::to_string(i);
  4562. std::string value = "value" + std::to_string(i);
  4563. headers.emplace(name, value);
  4564. }
  4565. // This should fail due to exceeding header count limit
  4566. cli_.set_keep_alive(true);
  4567. auto res = cli_.Get("/hi", headers);
  4568. // The server should respond with 400 Bad Request
  4569. ASSERT_TRUE(res);
  4570. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4571. EXPECT_EQ("close", res->get_header_value("Connection"));
  4572. EXPECT_FALSE(cli_.is_socket_open());
  4573. }
  4574. TEST_F(ServerTest, PercentEncoding) {
  4575. auto res = cli_.Get("/e%6edwith%");
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. }
  4579. TEST_F(ServerTest, PercentEncodingUnicode) {
  4580. auto res = cli_.Get("/e%u006edwith%");
  4581. ASSERT_TRUE(res);
  4582. EXPECT_EQ(StatusCode::OK_200, res->status);
  4583. }
  4584. TEST_F(ServerTest, InvalidPercentEncoding) {
  4585. auto res = cli_.Get("/%endwith%");
  4586. ASSERT_TRUE(res);
  4587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4588. }
  4589. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4590. auto res = cli_.Get("/%uendwith%");
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4593. }
  4594. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4595. auto res = cli_.Get("/hello?aaa=bbb%");
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4598. }
  4599. TEST_F(ServerTest, PlusSignEncoding) {
  4600. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4601. ASSERT_TRUE(res);
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. EXPECT_EQ("a +b", res->body);
  4604. }
  4605. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4606. // This test simulates a potential DoS attack using many headers
  4607. // to verify our security fix prevents memory exhaustion
  4608. httplib::Headers attack_headers;
  4609. // Attempt to add many headers like an attacker would (200 headers to far
  4610. // exceed limit)
  4611. for (int i = 0; i < 200; i++) {
  4612. std::string name = "X-Attack-Header-" + std::to_string(i);
  4613. std::string value = "attack_payload_" + std::to_string(i);
  4614. attack_headers.emplace(name, value);
  4615. }
  4616. // Try to POST with excessive headers
  4617. cli_.set_keep_alive(true);
  4618. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4619. // Should either fail or return 400 Bad Request due to security limit
  4620. if (res) {
  4621. // If we get a response, it should be 400 Bad Request
  4622. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4623. EXPECT_EQ("close", res->get_header_value("Connection"));
  4624. }
  4625. EXPECT_FALSE(cli_.is_socket_open());
  4626. }
  4627. TEST_F(ServerTest, MultipartFormData) {
  4628. UploadFormDataItems items = {
  4629. {"text1", "text default", "", ""},
  4630. {"text2", "aωb", "", ""},
  4631. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4632. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4633. {"file3", "", "", "application/octet-stream"},
  4634. {"file4", "", "", " application/json tmp-string "}};
  4635. auto res = cli_.Post("/multipart", items);
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4640. UploadFormDataItems items = {
  4641. {"text", "default text", "", ""},
  4642. {"multi_text1", "aaaaa", "", ""},
  4643. {"multi_text1", "bbbbb", "", ""},
  4644. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4645. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4646. "application/json"},
  4647. };
  4648. auto res = cli_.Post("/multipart/multi_file_values", items);
  4649. ASSERT_TRUE(res);
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. }
  4652. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4653. auto res = cli_.Get("/hi");
  4654. ASSERT_TRUE(res);
  4655. EXPECT_EQ(StatusCode::OK_200, res->status);
  4656. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4657. EXPECT_EQ("Hello World!", res->body);
  4658. }
  4659. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4660. Request req;
  4661. req.method = "POST";
  4662. req.path = "/chunked";
  4663. std::string host_and_port;
  4664. host_and_port += HOST;
  4665. host_and_port += ":";
  4666. host_and_port += std::to_string(PORT);
  4667. req.headers.emplace("Host", host_and_port.c_str());
  4668. req.headers.emplace("Accept", "*/*");
  4669. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4670. req.headers.emplace("Content-Type", "text/plain");
  4671. req.headers.emplace("Content-Length", "0");
  4672. req.headers.emplace(
  4673. "Transfer-Encoding",
  4674. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4675. // Client does not chunk, so make a chunked body manually.
  4676. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4677. auto res = std::make_shared<Response>();
  4678. auto error = Error::Success;
  4679. auto ret = cli_.send(req, *res, error);
  4680. ASSERT_TRUE(ret);
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. }
  4683. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4684. // rather than treat them as valid lengths.
  4685. template <typename ClientT>
  4686. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4687. Request req;
  4688. req.method = "POST";
  4689. req.path = "/chunked";
  4690. std::string host_and_port;
  4691. host_and_port += HOST;
  4692. host_and_port += ":";
  4693. host_and_port += std::to_string(PORT);
  4694. req.headers.emplace("Host", host_and_port.c_str());
  4695. req.headers.emplace("Content-Length", "0");
  4696. req.headers.emplace("Transfer-Encoding", "chunked");
  4697. req.body = body;
  4698. auto res = std::make_shared<Response>();
  4699. auto error = Error::Success;
  4700. ASSERT_TRUE(cli.send(req, *res, error));
  4701. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4702. }
  4703. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4704. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4705. }
  4706. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4707. expect_chunked_body_rejected(
  4708. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4709. }
  4710. TEST_F(ServerTest, GetStreamed2) {
  4711. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4712. ASSERT_TRUE(res);
  4713. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4714. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4715. EXPECT_EQ(true, res->has_header("Content-Range"));
  4716. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4717. EXPECT_EQ(std::string("ab"), res->body);
  4718. }
  4719. TEST_F(ServerTest, GetStreamed) {
  4720. auto res = cli_.Get("/streamed");
  4721. ASSERT_TRUE(res);
  4722. EXPECT_EQ(StatusCode::OK_200, res->status);
  4723. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4724. EXPECT_EQ(std::string("aaabbb"), res->body);
  4725. }
  4726. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4727. auto res = cli_.Get("/streamed-without-length",
  4728. Headers{make_range_header({{0, -1}})});
  4729. ASSERT_TRUE(res);
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ(false, res->has_header("Content-Length"));
  4732. EXPECT_EQ(false, res->has_header("Content-Range"));
  4733. EXPECT_EQ(std::string("abcdefg"), res->body);
  4734. }
  4735. TEST_F(ServerTest, GetStreamedWithRange1) {
  4736. auto res =
  4737. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4738. ASSERT_TRUE(res);
  4739. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4740. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4741. EXPECT_EQ(true, res->has_header("Content-Range"));
  4742. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4743. EXPECT_EQ(std::string("def"), res->body);
  4744. }
  4745. TEST_F(ServerTest, GetStreamedWithRange2) {
  4746. auto res =
  4747. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4748. ASSERT_TRUE(res);
  4749. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4750. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4751. EXPECT_EQ(true, res->has_header("Content-Range"));
  4752. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4753. EXPECT_EQ(std::string("bcdefg"), res->body);
  4754. }
  4755. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4756. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4757. ASSERT_TRUE(res);
  4758. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4759. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4760. EXPECT_EQ(true, res->has_header("Content-Range"));
  4761. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4762. EXPECT_EQ(std::string("efg"), res->body);
  4763. }
  4764. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4765. auto res =
  4766. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4767. ASSERT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4769. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4770. EXPECT_EQ(false, res->has_header("Content-Range"));
  4771. EXPECT_EQ(0U, res->body.size());
  4772. }
  4773. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4774. auto res =
  4775. cli_.Get("/streamed-with-range",
  4776. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4777. "92233720368547758079223372036854775807"}});
  4778. ASSERT_TRUE(res);
  4779. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4780. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4781. EXPECT_EQ(false, res->has_header("Content-Range"));
  4782. EXPECT_EQ(0U, res->body.size());
  4783. }
  4784. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4785. auto res = cli_.Get(
  4786. "/with-range",
  4787. Headers{{"Range",
  4788. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4789. {"Accept-Encoding", ""}});
  4790. ASSERT_TRUE(res);
  4791. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4792. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4793. EXPECT_EQ(true, res->has_header("Content-Range"));
  4794. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4795. EXPECT_EQ(std::string("abcdefg"), res->body);
  4796. }
  4797. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4798. auto res = cli_.Get("/with-range", Headers{
  4799. {"Range", "bytes=0-"},
  4800. {"Accept-Encoding", ""},
  4801. });
  4802. ASSERT_TRUE(res);
  4803. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4804. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4805. EXPECT_EQ(true, res->has_header("Content-Range"));
  4806. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4807. EXPECT_EQ(std::string("abcdefg"), res->body);
  4808. }
  4809. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4810. auto res = cli_.Get("/streamed-with-range",
  4811. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4812. ASSERT_TRUE(res);
  4813. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4814. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4815. EXPECT_EQ(false, res->has_header("Content-Range"));
  4816. EXPECT_EQ(267U, res->body.size());
  4817. // Check that both range contents are present
  4818. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4819. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4820. // Check that Content-Range headers are present for both ranges
  4821. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4822. std::string::npos);
  4823. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4824. std::string::npos);
  4825. }
  4826. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4827. Ranges ranges;
  4828. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4829. ranges.emplace_back(0, -1);
  4830. }
  4831. auto res = cli_.Get("/streamed-with-range?error",
  4832. Headers{{make_range_header(ranges)}});
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4835. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4836. EXPECT_EQ(false, res->has_header("Content-Range"));
  4837. EXPECT_EQ(0U, res->body.size());
  4838. }
  4839. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4840. auto res = cli_.Get("/streamed-with-range",
  4841. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4842. ASSERT_TRUE(res);
  4843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4844. EXPECT_EQ(5U, res->body.size());
  4845. // Check that overlapping ranges are coalesced into a single range
  4846. EXPECT_EQ("bcdef", res->body);
  4847. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4848. // Should be single range, not multipart
  4849. EXPECT_TRUE(res->has_header("Content-Range"));
  4850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4851. }
  4852. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4853. auto res = cli_.Get("/streamed-with-range",
  4854. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4857. EXPECT_EQ(268U, res->body.size());
  4858. // Check that both range contents are present
  4859. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4860. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4861. // Check that Content-Range headers are present for both ranges
  4862. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4863. std::string::npos);
  4864. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4865. std::string::npos);
  4866. }
  4867. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4868. auto res = cli_.Get("/streamed-with-range",
  4869. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4870. ASSERT_TRUE(res);
  4871. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4872. EXPECT_EQ(269U, res->body.size());
  4873. // Check that both duplicate range contents are present
  4874. size_t first_abc = res->body.find("abc\r\n");
  4875. EXPECT_TRUE(first_abc != std::string::npos);
  4876. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4877. EXPECT_TRUE(second_abc != std::string::npos);
  4878. // Check that Content-Range headers are present for both ranges
  4879. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4880. EXPECT_TRUE(first_range != std::string::npos);
  4881. size_t second_range =
  4882. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4883. EXPECT_TRUE(second_range != std::string::npos);
  4884. }
  4885. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4886. auto res =
  4887. cli_.Get("/streamed-with-range?error",
  4888. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4889. ASSERT_TRUE(res);
  4890. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4891. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4892. EXPECT_EQ(false, res->has_header("Content-Range"));
  4893. EXPECT_EQ(0U, res->body.size());
  4894. }
  4895. TEST_F(ServerTest, GetStreamedEndless) {
  4896. uint64_t offset = 0;
  4897. auto res = cli_.Get("/streamed-cancel",
  4898. [&](const char * /*data*/, uint64_t data_length) {
  4899. if (offset < 100) {
  4900. offset += data_length;
  4901. return true;
  4902. }
  4903. return false;
  4904. });
  4905. ASSERT_TRUE(!res);
  4906. EXPECT_EQ(Error::Canceled, res.error());
  4907. }
  4908. TEST_F(ServerTest, ClientStop) {
  4909. std::atomic_size_t count{4};
  4910. std::vector<std::thread> threads;
  4911. for (auto i = count.load(); i != 0; --i) {
  4912. threads.emplace_back([&]() {
  4913. auto res = cli_.Get("/streamed-cancel",
  4914. [&](const char *, uint64_t) { return true; });
  4915. --count;
  4916. ASSERT_TRUE(!res);
  4917. EXPECT_TRUE(res.error() == Error::Canceled ||
  4918. res.error() == Error::Read || res.error() == Error::Write);
  4919. });
  4920. }
  4921. std::this_thread::sleep_for(std::chrono::seconds(2));
  4922. while (count != 0) {
  4923. cli_.stop();
  4924. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4925. }
  4926. for (auto &t : threads) {
  4927. t.join();
  4928. }
  4929. }
  4930. TEST_F(ServerTest, GetWithRange1) {
  4931. auto res = cli_.Get("/with-range", Headers{
  4932. make_range_header({{3, 5}}),
  4933. {"Accept-Encoding", ""},
  4934. });
  4935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4936. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4937. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4938. EXPECT_EQ(true, res->has_header("Content-Range"));
  4939. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4940. EXPECT_EQ(std::string("def"), res->body);
  4941. }
  4942. TEST_F(ServerTest, GetWithRange2) {
  4943. auto res = cli_.Get("/with-range", Headers{
  4944. make_range_header({{1, -1}}),
  4945. {"Accept-Encoding", ""},
  4946. });
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4949. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4950. EXPECT_EQ(true, res->has_header("Content-Range"));
  4951. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4952. EXPECT_EQ(std::string("bcdefg"), res->body);
  4953. }
  4954. TEST_F(ServerTest, GetWithRange3) {
  4955. auto res = cli_.Get("/with-range", Headers{
  4956. make_range_header({{0, 0}}),
  4957. {"Accept-Encoding", ""},
  4958. });
  4959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4961. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4962. EXPECT_EQ(true, res->has_header("Content-Range"));
  4963. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4964. EXPECT_EQ(std::string("a"), res->body);
  4965. }
  4966. TEST_F(ServerTest, GetWithRange4) {
  4967. auto res = cli_.Get("/with-range", Headers{
  4968. make_range_header({{-1, 2}}),
  4969. {"Accept-Encoding", ""},
  4970. });
  4971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4972. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4973. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4974. EXPECT_EQ(true, res->has_header("Content-Range"));
  4975. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4976. EXPECT_EQ(std::string("fg"), res->body);
  4977. }
  4978. TEST_F(ServerTest, GetWithRange5) {
  4979. auto res = cli_.Get("/with-range", Headers{
  4980. make_range_header({{0, 5}}),
  4981. {"Accept-Encoding", ""},
  4982. });
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4985. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4986. EXPECT_EQ(true, res->has_header("Content-Range"));
  4987. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4988. EXPECT_EQ(std::string("abcdef"), res->body);
  4989. }
  4990. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4991. auto res =
  4992. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  4993. ASSERT_TRUE(res);
  4994. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4995. }
  4996. TEST_F(ServerTest, GetWithRangeMultipart) {
  4997. auto res =
  4998. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4999. ASSERT_TRUE(res);
  5000. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5001. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5002. EXPECT_EQ(false, res->has_header("Content-Range"));
  5003. EXPECT_EQ(267U, res->body.size());
  5004. }
  5005. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5006. auto res = cli_.Get("/with-range",
  5007. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5008. ASSERT_TRUE(res);
  5009. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5010. }
  5011. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5012. auto res = cli_.Get("/with-range-customized-response",
  5013. Headers{{make_range_header({{1, 2}})}});
  5014. ASSERT_TRUE(res);
  5015. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5016. EXPECT_EQ(true, res->has_header("Content-Length"));
  5017. EXPECT_EQ(false, res->has_header("Content-Range"));
  5018. EXPECT_EQ(JSON_DATA, res->body);
  5019. }
  5020. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5021. auto res = cli_.Get("/with-range-customized-response",
  5022. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5025. EXPECT_EQ(true, res->has_header("Content-Length"));
  5026. EXPECT_EQ(false, res->has_header("Content-Range"));
  5027. EXPECT_EQ(JSON_DATA, res->body);
  5028. }
  5029. TEST_F(ServerTest, Issue1772) {
  5030. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5031. ASSERT_TRUE(res);
  5032. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5033. }
  5034. TEST_F(ServerTest, Issue609) {
  5035. auto res = cli_.Delete("/issue609");
  5036. ASSERT_TRUE(res);
  5037. EXPECT_EQ(StatusCode::OK_200, res->status);
  5038. EXPECT_EQ(std::string("ok"), res->body);
  5039. }
  5040. TEST_F(ServerTest, GetStreamedChunked) {
  5041. auto res = cli_.Get("/streamed-chunked");
  5042. ASSERT_TRUE(res);
  5043. EXPECT_EQ(StatusCode::OK_200, res->status);
  5044. EXPECT_EQ(std::string("123456789"), res->body);
  5045. }
  5046. TEST_F(ServerTest, GetStreamedChunked2) {
  5047. auto res = cli_.Get("/streamed-chunked2");
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ(std::string("123456789"), res->body);
  5051. }
  5052. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5053. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5054. ASSERT_TRUE(res);
  5055. EXPECT_EQ(StatusCode::OK_200, res->status);
  5056. EXPECT_EQ(std::string("123456789"), res->body);
  5057. EXPECT_TRUE(res->has_header("Trailer"));
  5058. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5059. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5060. // Trailers are now stored separately from headers (security fix)
  5061. EXPECT_EQ(2U, res->trailers.size());
  5062. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5063. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5064. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5065. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5066. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5067. // Verify trailers are NOT in headers (security verification)
  5068. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5069. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5070. }
  5071. TEST_F(ServerTest, LargeChunkedPost) {
  5072. Request req;
  5073. req.method = "POST";
  5074. req.path = "/large-chunked";
  5075. std::string host_and_port;
  5076. host_and_port += HOST;
  5077. host_and_port += ":";
  5078. host_and_port += std::to_string(PORT);
  5079. req.headers.emplace("Host", host_and_port.c_str());
  5080. req.headers.emplace("Accept", "*/*");
  5081. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5082. req.headers.emplace("Content-Type", "text/plain");
  5083. req.headers.emplace("Content-Length", "0");
  5084. req.headers.emplace("Transfer-Encoding", "chunked");
  5085. std::string long_string(30 * 1024u, 'a');
  5086. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5087. // Attempt to make a large enough post to exceed OS buffers, to test that
  5088. // the server handles short reads if the full chunk data isn't available.
  5089. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5090. auto res = std::make_shared<Response>();
  5091. auto error = Error::Success;
  5092. auto ret = cli_.send(req, *res, error);
  5093. ASSERT_TRUE(ret);
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. }
  5096. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5097. auto res = cli_.Get("/remote_addr");
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5101. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5102. }
  5103. TEST_F(ServerTest, GetMethodLocalAddr) {
  5104. auto res = cli_.Get("/local_addr");
  5105. ASSERT_TRUE(res);
  5106. EXPECT_EQ(StatusCode::OK_200, res->status);
  5107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5108. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5109. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5110. }
  5111. TEST_F(ServerTest, HTTPResponseSplitting) {
  5112. auto res = cli_.Get("/http_response_splitting");
  5113. ASSERT_TRUE(res);
  5114. EXPECT_EQ(StatusCode::OK_200, res->status);
  5115. }
  5116. TEST_F(ServerTest, SlowRequest) {
  5117. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5118. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5119. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5120. }
  5121. #if 0
  5122. TEST_F(ServerTest, SlowPost) {
  5123. char buffer[64 * 1024];
  5124. memset(buffer, 0x42, sizeof(buffer));
  5125. auto res = cli_.Post(
  5126. "/slowpost", 64 * 1024 * 1024,
  5127. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5128. auto ret = sink.write(buffer, sizeof(buffer));
  5129. EXPECT_TRUE(ret);
  5130. return true;
  5131. },
  5132. "text/plain");
  5133. ASSERT_TRUE(res);
  5134. EXPECT_EQ(StatusCode::OK_200, res->status);
  5135. }
  5136. TEST_F(ServerTest, SlowPostFail) {
  5137. char buffer[64 * 1024];
  5138. memset(buffer, 0x42, sizeof(buffer));
  5139. cli_.set_write_timeout(std::chrono::seconds(0));
  5140. auto res = cli_.Post(
  5141. "/slowpost", 64 * 1024 * 1024,
  5142. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5143. sink.write(buffer, sizeof(buffer));
  5144. return true;
  5145. },
  5146. "text/plain");
  5147. ASSERT_TRUE(!res);
  5148. EXPECT_EQ(Error::Write, res.error());
  5149. }
  5150. #endif
  5151. TEST_F(ServerTest, Put) {
  5152. auto res = cli_.Put("/put", "PUT", "text/plain");
  5153. ASSERT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. EXPECT_EQ("PUT", res->body);
  5156. }
  5157. TEST_F(ServerTest, PutWithContentProvider) {
  5158. auto res = cli_.Put(
  5159. "/put", 3,
  5160. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5161. sink.os << "PUT";
  5162. return true;
  5163. },
  5164. "text/plain");
  5165. ASSERT_TRUE(res);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. EXPECT_EQ("PUT", res->body);
  5168. }
  5169. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5170. auto res = cli_.Post(
  5171. "/post", 42,
  5172. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5173. return false;
  5174. },
  5175. "text/plain");
  5176. ASSERT_TRUE(!res);
  5177. EXPECT_EQ(Error::Canceled, res.error());
  5178. }
  5179. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5180. auto res = cli_.Put(
  5181. "/put",
  5182. [](size_t /*offset*/, DataSink &sink) {
  5183. sink.os << "PUT";
  5184. sink.done();
  5185. return true;
  5186. },
  5187. "text/plain");
  5188. ASSERT_TRUE(res);
  5189. EXPECT_EQ(StatusCode::OK_200, res->status);
  5190. EXPECT_EQ("PUT", res->body);
  5191. }
  5192. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5193. auto res = cli_.Post(
  5194. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5195. "text/plain");
  5196. ASSERT_TRUE(!res);
  5197. EXPECT_EQ(Error::Canceled, res.error());
  5198. }
  5199. TEST_F(ServerTest, PostLoopBack) {
  5200. std::string body;
  5201. auto res = cli_.Post(
  5202. "/post-loopback", 9,
  5203. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5204. EXPECT_EQ(9u, length);
  5205. sink.write("123", 3);
  5206. sink.write("456", 3);
  5207. sink.write("789", 3);
  5208. return true;
  5209. },
  5210. "text/plain",
  5211. [&body](const char *data, size_t data_length) {
  5212. body.append(data, data_length);
  5213. return true;
  5214. });
  5215. ASSERT_TRUE(res);
  5216. EXPECT_EQ(StatusCode::OK_200, res->status);
  5217. EXPECT_EQ("123456789", body);
  5218. }
  5219. TEST_F(ServerTest, PutLoopBack) {
  5220. std::string body;
  5221. auto res = cli_.Put(
  5222. "/put-loopback", 9,
  5223. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5224. EXPECT_EQ(9u, length);
  5225. sink.write("123", 3);
  5226. sink.write("456", 3);
  5227. sink.write("789", 3);
  5228. return true;
  5229. },
  5230. "text/plain",
  5231. [&body](const char *data, size_t data_length) {
  5232. body.append(data, data_length);
  5233. return true;
  5234. });
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(StatusCode::OK_200, res->status);
  5237. EXPECT_EQ("123456789", body);
  5238. }
  5239. TEST_F(ServerTest, PatchLoopBack) {
  5240. std::string body;
  5241. auto res = cli_.Patch(
  5242. "/patch-loopback", 9,
  5243. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5244. EXPECT_EQ(9u, length);
  5245. sink.write("123", 3);
  5246. sink.write("456", 3);
  5247. sink.write("789", 3);
  5248. return true;
  5249. },
  5250. "text/plain",
  5251. [&body](const char *data, size_t data_length) {
  5252. body.append(data, data_length);
  5253. return true;
  5254. });
  5255. ASSERT_TRUE(res);
  5256. EXPECT_EQ(StatusCode::OK_200, res->status);
  5257. EXPECT_EQ("123456789", body);
  5258. }
  5259. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5260. std::string body;
  5261. auto res = cli_.Post(
  5262. "/post-loopback",
  5263. [](size_t /*offset*/, DataSink &sink) {
  5264. sink.write("123", 3);
  5265. sink.write("456", 3);
  5266. sink.write("789", 3);
  5267. sink.done();
  5268. return true;
  5269. },
  5270. "text/plain",
  5271. [&body](const char *data, size_t data_length) {
  5272. body.append(data, data_length);
  5273. return true;
  5274. });
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("123456789", body);
  5278. }
  5279. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5280. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5281. cli_.set_compress(true);
  5282. auto res = cli_.Put(
  5283. "/put", 3,
  5284. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5285. sink.os << "PUT";
  5286. return true;
  5287. },
  5288. "text/plain");
  5289. ASSERT_TRUE(res);
  5290. EXPECT_EQ(StatusCode::OK_200, res->status);
  5291. EXPECT_EQ("PUT", res->body);
  5292. }
  5293. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5294. cli_.set_compress(true);
  5295. auto res = cli_.Post(
  5296. "/post", 42,
  5297. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5298. return false;
  5299. },
  5300. "text/plain");
  5301. ASSERT_TRUE(!res);
  5302. EXPECT_EQ(Error::Canceled, res.error());
  5303. }
  5304. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5305. cli_.set_compress(true);
  5306. auto res = cli_.Put(
  5307. "/put",
  5308. [](size_t /*offset*/, DataSink &sink) {
  5309. sink.os << "PUT";
  5310. sink.done();
  5311. return true;
  5312. },
  5313. "text/plain");
  5314. ASSERT_TRUE(res);
  5315. EXPECT_EQ(StatusCode::OK_200, res->status);
  5316. EXPECT_EQ("PUT", res->body);
  5317. }
  5318. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5319. cli_.set_compress(true);
  5320. auto res = cli_.Post(
  5321. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5322. "text/plain");
  5323. ASSERT_TRUE(!res);
  5324. EXPECT_EQ(Error::Canceled, res.error());
  5325. }
  5326. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5327. cli_.set_compress(true);
  5328. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5329. ASSERT_TRUE(res);
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. EXPECT_EQ(LARGE_DATA, res->body);
  5332. }
  5333. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5334. #ifdef CPPHTTPLIB_SSL_ENABLED
  5335. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5336. Client cli(s.c_str());
  5337. cli.enable_server_certificate_verification(false);
  5338. #else
  5339. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5340. Client cli(s.c_str());
  5341. #endif
  5342. cli.set_compress(true);
  5343. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5344. ASSERT_TRUE(res);
  5345. EXPECT_EQ(StatusCode::OK_200, res->status);
  5346. EXPECT_EQ(LARGE_DATA, res->body);
  5347. // The compressed size should be less than a 10th of the original. May vary
  5348. // depending on the zlib library.
  5349. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5350. static_cast<uint64_t>(10 * 1024 * 1024));
  5351. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5352. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5353. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5354. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5355. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5356. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5357. #endif
  5358. }
  5359. TEST_F(ServerTest, PutContentWithDeflate) {
  5360. cli_.set_compress(false);
  5361. Headers headers;
  5362. headers.emplace("Content-Encoding", "deflate");
  5363. // PUT in deflate format:
  5364. auto res = cli_.Put("/put", headers,
  5365. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5366. ASSERT_TRUE(res);
  5367. EXPECT_EQ(StatusCode::OK_200, res->status);
  5368. EXPECT_EQ("PUT", res->body);
  5369. }
  5370. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5371. Headers headers;
  5372. headers.emplace("Accept-Encoding", "gzip, deflate");
  5373. auto res = cli_.Get("/streamed-chunked", headers);
  5374. ASSERT_TRUE(res);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. EXPECT_EQ(std::string("123456789"), res->body);
  5377. }
  5378. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5379. Headers headers;
  5380. headers.emplace("Accept-Encoding", "gzip, deflate");
  5381. auto res = cli_.Get("/streamed-chunked2", headers);
  5382. ASSERT_TRUE(res);
  5383. EXPECT_EQ(StatusCode::OK_200, res->status);
  5384. EXPECT_EQ(std::string("123456789"), res->body);
  5385. }
  5386. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5387. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5388. ASSERT_TRUE(res);
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. }
  5391. TEST(GzipDecompressor, ChunkedDecompression) {
  5392. std::string data;
  5393. for (size_t i = 0; i < 32 * 1024; ++i) {
  5394. data.push_back(static_cast<char>('a' + i % 26));
  5395. }
  5396. std::string compressed_data;
  5397. {
  5398. httplib::detail::gzip_compressor compressor;
  5399. bool result = compressor.compress(
  5400. data.data(), data.size(),
  5401. /*last=*/true,
  5402. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5403. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5404. compressed_data_size);
  5405. return true;
  5406. });
  5407. ASSERT_TRUE(result);
  5408. }
  5409. std::string decompressed_data;
  5410. {
  5411. httplib::detail::gzip_decompressor decompressor;
  5412. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5413. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5414. size_t chunk_size = 130;
  5415. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5416. chunk_begin += chunk_size) {
  5417. size_t current_chunk_size =
  5418. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5419. bool result = decompressor.decompress(
  5420. compressed_data.data() + chunk_begin, current_chunk_size,
  5421. [&](const char *decompressed_data_chunk,
  5422. size_t decompressed_data_chunk_size) {
  5423. decompressed_data.insert(decompressed_data.size(),
  5424. decompressed_data_chunk,
  5425. decompressed_data_chunk_size);
  5426. return true;
  5427. });
  5428. ASSERT_TRUE(result);
  5429. }
  5430. }
  5431. ASSERT_EQ(data, decompressed_data);
  5432. }
  5433. TEST(GzipDecompressor, DeflateDecompression) {
  5434. std::string original_text = "Raw deflate without gzip";
  5435. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5436. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5437. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5438. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5439. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5440. std::string decompressed_data;
  5441. {
  5442. httplib::detail::gzip_decompressor decompressor;
  5443. bool result = decompressor.decompress(
  5444. compressed_data.data(), compressed_data.size(),
  5445. [&](const char *decompressed_data_chunk,
  5446. size_t decompressed_data_chunk_size) {
  5447. decompressed_data.insert(decompressed_data.size(),
  5448. decompressed_data_chunk,
  5449. decompressed_data_chunk_size);
  5450. return true;
  5451. });
  5452. ASSERT_TRUE(result);
  5453. }
  5454. ASSERT_EQ(original_text, decompressed_data);
  5455. }
  5456. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5457. std::string original_text = "Raw deflate without gzip";
  5458. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5459. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5460. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5461. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5462. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5463. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5464. std::string decompressed_data;
  5465. {
  5466. httplib::detail::gzip_decompressor decompressor;
  5467. bool result = decompressor.decompress(
  5468. compressed_data.data(), compressed_data.size(),
  5469. [&](const char *decompressed_data_chunk,
  5470. size_t decompressed_data_chunk_size) {
  5471. decompressed_data.insert(decompressed_data.size(),
  5472. decompressed_data_chunk,
  5473. decompressed_data_chunk_size);
  5474. return true;
  5475. });
  5476. ASSERT_TRUE(result);
  5477. }
  5478. ASSERT_EQ(original_text, decompressed_data);
  5479. }
  5480. #endif
  5481. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5482. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5483. Headers headers;
  5484. headers.emplace("Accept-Encoding", "br");
  5485. auto res = cli_.Get("/streamed-chunked", headers);
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ(std::string("123456789"), res->body);
  5489. }
  5490. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5491. Headers headers;
  5492. headers.emplace("Accept-Encoding", "br");
  5493. auto res = cli_.Get("/streamed-chunked2", headers);
  5494. ASSERT_TRUE(res);
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. EXPECT_EQ(std::string("123456789"), res->body);
  5497. }
  5498. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5499. cli_.set_compress(true);
  5500. auto res = cli_.Put(
  5501. "/put", 3,
  5502. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5503. sink.os << "PUT";
  5504. return true;
  5505. },
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. EXPECT_EQ("PUT", res->body);
  5510. }
  5511. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5512. cli_.set_compress(true);
  5513. auto res = cli_.Put(
  5514. "/put",
  5515. [](size_t /*offset*/, DataSink &sink) {
  5516. sink.os << "PUT";
  5517. sink.done();
  5518. return true;
  5519. },
  5520. "text/plain");
  5521. ASSERT_TRUE(res);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. EXPECT_EQ("PUT", res->body);
  5524. }
  5525. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5526. cli_.set_compress(true);
  5527. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5528. ASSERT_TRUE(res);
  5529. EXPECT_EQ(StatusCode::OK_200, res->status);
  5530. EXPECT_EQ(LARGE_DATA, res->body);
  5531. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5532. }
  5533. #endif
  5534. TEST_F(ServerTest, Patch) {
  5535. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5536. ASSERT_TRUE(res);
  5537. EXPECT_EQ(StatusCode::OK_200, res->status);
  5538. EXPECT_EQ("PATCH", res->body);
  5539. }
  5540. TEST_F(ServerTest, Delete) {
  5541. auto res = cli_.Delete("/delete");
  5542. ASSERT_TRUE(res);
  5543. EXPECT_EQ(StatusCode::OK_200, res->status);
  5544. EXPECT_EQ("DELETE", res->body);
  5545. }
  5546. TEST_F(ServerTest, DeleteContentReceiver) {
  5547. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5548. ASSERT_TRUE(res);
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ("content", res->body);
  5551. }
  5552. TEST_F(ServerTest, Options) {
  5553. auto res = cli_.Options("*");
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5557. EXPECT_TRUE(res->body.empty());
  5558. }
  5559. TEST_F(ServerTest, URL) {
  5560. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5561. ASSERT_TRUE(res);
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. }
  5564. TEST_F(ServerTest, ArrayParam) {
  5565. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5566. ASSERT_TRUE(res);
  5567. EXPECT_EQ(StatusCode::OK_200, res->status);
  5568. }
  5569. TEST_F(ServerTest, ArrayParamValues) {
  5570. auto res =
  5571. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5572. ASSERT_TRUE(res);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, NoMultipleHeaders) {
  5576. Headers headers = {{"Content-Length", "5"}};
  5577. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5578. "text/plain");
  5579. ASSERT_TRUE(res);
  5580. EXPECT_EQ(StatusCode::OK_200, res->status);
  5581. }
  5582. TEST_F(ServerTest, PostContentReceiver) {
  5583. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5584. ASSERT_TRUE(res);
  5585. ASSERT_EQ(StatusCode::OK_200, res->status);
  5586. ASSERT_EQ("content", res->body);
  5587. }
  5588. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5589. UploadFormDataItems items = {
  5590. {"text1", "text default", "", ""},
  5591. {"text2", "aωb", "", ""},
  5592. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5593. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5594. {"file3", "", "", "application/octet-stream"},
  5595. };
  5596. auto res = cli_.Post("/content_receiver", items);
  5597. ASSERT_TRUE(res);
  5598. EXPECT_EQ(StatusCode::OK_200, res->status);
  5599. }
  5600. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5601. UploadFormDataItems items = {
  5602. {"text1", "text default", "", ""},
  5603. {"text2", "aωb", "", ""},
  5604. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5605. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5606. {"file3", "", "", "application/octet-stream"},
  5607. };
  5608. auto boundary = std::string("+++++");
  5609. std::string body;
  5610. for (const auto &item : items) {
  5611. body += "--" + boundary + "\r\n";
  5612. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5613. if (!item.filename.empty()) {
  5614. body += "; filename=\"" + item.filename + "\"";
  5615. }
  5616. body += "\r\n";
  5617. if (!item.content_type.empty()) {
  5618. body += "Content-Type: " + item.content_type + "\r\n";
  5619. }
  5620. body += "\r\n";
  5621. body += item.content + "\r\n";
  5622. }
  5623. body += "--" + boundary + "--\r\n";
  5624. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5625. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5626. ASSERT_TRUE(res);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. TEST(MultipartFormDataTest, FieldEscaping) {
  5630. Server svr;
  5631. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5632. const ContentReader &content_reader) {
  5633. ASSERT_TRUE(req.is_multipart_form_data());
  5634. std::vector<FormData> received;
  5635. content_reader(
  5636. [&](const FormData &file) {
  5637. received.push_back(file);
  5638. return true;
  5639. },
  5640. [&](const char *data, size_t data_length) {
  5641. received.back().content.append(data, data_length);
  5642. return true;
  5643. });
  5644. // '"', CR and LF in names and filenames are escaped following the
  5645. // WHATWG HTML standard, so each part still parses as a single part
  5646. // with no injected headers. Content types get CR/LF escaped too,
  5647. // while '"' (legal there, e.g. quoted charset) is preserved.
  5648. ASSERT_EQ(4U, received.size());
  5649. EXPECT_EQ("na%22me", received[0].name);
  5650. EXPECT_EQ("quoted name", received[0].content);
  5651. EXPECT_EQ("file", received[1].name);
  5652. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5653. received[1].filename);
  5654. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5655. EXPECT_EQ("injected", received[1].content);
  5656. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5657. EXPECT_EQ("my%22file.txt", received[2].filename);
  5658. EXPECT_EQ("cr lf name", received[2].content);
  5659. EXPECT_EQ("typed", received[3].name);
  5660. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5661. received[3].content_type);
  5662. EXPECT_EQ("typed content", received[3].content);
  5663. });
  5664. auto port = svr.bind_to_any_port("localhost");
  5665. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5666. auto se = detail::scope_exit([&] {
  5667. svr.stop();
  5668. t.join();
  5669. ASSERT_FALSE(svr.is_running());
  5670. });
  5671. svr.wait_until_ready();
  5672. Client cli("localhost", port);
  5673. UploadFormDataItems items = {
  5674. {"na\"me", "quoted name", "", ""},
  5675. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5676. "application/octet-stream"},
  5677. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5678. {"typed", "typed content", "",
  5679. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5680. };
  5681. auto res = cli.Post("/post", items);
  5682. ASSERT_TRUE(res);
  5683. EXPECT_EQ(StatusCode::OK_200, res->status);
  5684. }
  5685. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5686. const UploadFormDataItems items = {
  5687. {"name1", "Content 1", "", ""},
  5688. {"name2", "Content 2", "file2.txt", "text/plain"},
  5689. };
  5690. Server svr;
  5691. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5692. const ContentReader &content_reader) {
  5693. ASSERT_TRUE(req.is_multipart_form_data());
  5694. std::vector<FormData> received;
  5695. content_reader(
  5696. [&](const FormData &file) {
  5697. received.push_back(file);
  5698. return true;
  5699. },
  5700. [&](const char *data, size_t data_length) {
  5701. received.back().content.append(data, data_length);
  5702. return true;
  5703. });
  5704. ASSERT_EQ(2U, received.size());
  5705. EXPECT_EQ("name1", received[0].name);
  5706. EXPECT_EQ("Content 1", received[0].content);
  5707. EXPECT_EQ("name2", received[1].name);
  5708. EXPECT_EQ("Content 2", received[1].content);
  5709. EXPECT_EQ("file2.txt", received[1].filename);
  5710. EXPECT_EQ("text/plain", received[1].content_type);
  5711. });
  5712. auto port = svr.bind_to_any_port("localhost");
  5713. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5714. auto se = detail::scope_exit([&] {
  5715. svr.stop();
  5716. t.join();
  5717. ASSERT_FALSE(svr.is_running());
  5718. });
  5719. svr.wait_until_ready();
  5720. Client cli("localhost", port);
  5721. // Whole-body serialization with a generated boundary
  5722. {
  5723. MultipartFormDataWriter writer;
  5724. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5725. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5726. writer.content_type());
  5727. auto body = writer.serialize(items);
  5728. EXPECT_EQ(body.size(), writer.content_length(items));
  5729. auto res = cli.Post("/post", body, writer.content_type());
  5730. ASSERT_TRUE(res);
  5731. EXPECT_EQ(StatusCode::OK_200, res->status);
  5732. }
  5733. // Per-part framing with a custom boundary via a content provider
  5734. {
  5735. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5736. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5737. MultipartFormDataWriter writer("custom-boundary_123");
  5738. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5739. std::string body;
  5740. for (const auto &item : items) {
  5741. body += writer.item_begin(item);
  5742. body += item.content;
  5743. body += MultipartFormDataWriter::item_end();
  5744. }
  5745. body += writer.finish();
  5746. EXPECT_EQ(body.size(), writer.content_length(items));
  5747. auto res = cli.Post(
  5748. "/post", body.size(),
  5749. [&](size_t offset, size_t length, DataSink &sink) {
  5750. sink.write(body.data() + offset, length);
  5751. return true;
  5752. },
  5753. writer.content_type());
  5754. ASSERT_TRUE(res);
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. }
  5757. }
  5758. TEST_F(ServerTest, PostContentReceiverGzip) {
  5759. cli_.set_compress(true);
  5760. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5761. ASSERT_TRUE(res);
  5762. ASSERT_EQ(StatusCode::OK_200, res->status);
  5763. ASSERT_EQ("content", res->body);
  5764. }
  5765. TEST_F(ServerTest, PutContentReceiver) {
  5766. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5767. ASSERT_TRUE(res);
  5768. ASSERT_EQ(StatusCode::OK_200, res->status);
  5769. ASSERT_EQ("content", res->body);
  5770. }
  5771. TEST_F(ServerTest, PatchContentReceiver) {
  5772. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5773. ASSERT_TRUE(res);
  5774. ASSERT_EQ(StatusCode::OK_200, res->status);
  5775. ASSERT_EQ("content", res->body);
  5776. }
  5777. template <typename ClientType>
  5778. void TestWithHeadersAndContentReceiver(
  5779. ClientType &cli,
  5780. std::function<Result(ClientType &, const std::string &, const Headers &,
  5781. const std::string &, const std::string &,
  5782. ContentReceiver, DownloadProgress)>
  5783. request_func) {
  5784. Headers headers;
  5785. headers.emplace("X-Custom-Header", "test-value");
  5786. std::string received_body;
  5787. auto res = request_func(
  5788. cli, "/content_receiver", headers, "content", "application/json",
  5789. [&](const char *data, size_t data_length) {
  5790. received_body.append(data, data_length);
  5791. return true;
  5792. },
  5793. nullptr);
  5794. ASSERT_TRUE(res);
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. EXPECT_EQ("content", received_body);
  5797. }
  5798. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5799. #ifdef CPPHTTPLIB_SSL_ENABLED
  5800. using ClientT = SSLClient;
  5801. #else
  5802. using ClientT = Client;
  5803. #endif
  5804. TestWithHeadersAndContentReceiver<ClientT>(
  5805. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5806. const std::string &body, const std::string &content_type,
  5807. ContentReceiver receiver, DownloadProgress progress) {
  5808. return cli.Post(path, headers, body, content_type, receiver, progress);
  5809. });
  5810. }
  5811. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5812. #ifdef CPPHTTPLIB_SSL_ENABLED
  5813. using ClientT = SSLClient;
  5814. #else
  5815. using ClientT = Client;
  5816. #endif
  5817. TestWithHeadersAndContentReceiver<ClientT>(
  5818. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5819. const std::string &body, const std::string &content_type,
  5820. ContentReceiver receiver, DownloadProgress progress) {
  5821. return cli.Put(path, headers, body, content_type, receiver, progress);
  5822. });
  5823. }
  5824. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5825. #ifdef CPPHTTPLIB_SSL_ENABLED
  5826. using ClientT = SSLClient;
  5827. #else
  5828. using ClientT = Client;
  5829. #endif
  5830. TestWithHeadersAndContentReceiver<ClientT>(
  5831. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5832. const std::string &body, const std::string &content_type,
  5833. ContentReceiver receiver, DownloadProgress progress) {
  5834. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5835. });
  5836. }
  5837. template <typename ClientType>
  5838. void TestWithHeadersAndContentReceiverWithProgress(
  5839. ClientType &cli,
  5840. std::function<Result(ClientType &, const std::string &, const Headers &,
  5841. const std::string &, const std::string &,
  5842. ContentReceiver, DownloadProgress)>
  5843. request_func) {
  5844. Headers headers;
  5845. headers.emplace("X-Test-Header", "progress-test");
  5846. std::string received_body;
  5847. auto progress_called = false;
  5848. auto res = request_func(
  5849. cli, "/content_receiver", headers, "content", "text/plain",
  5850. [&](const char *data, size_t data_length) {
  5851. received_body.append(data, data_length);
  5852. return true;
  5853. },
  5854. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5855. progress_called = true;
  5856. return true;
  5857. });
  5858. ASSERT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("content", received_body);
  5861. EXPECT_TRUE(progress_called);
  5862. }
  5863. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5864. #ifdef CPPHTTPLIB_SSL_ENABLED
  5865. using ClientT = SSLClient;
  5866. #else
  5867. using ClientT = Client;
  5868. #endif
  5869. TestWithHeadersAndContentReceiverWithProgress<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, DownloadProgress progress) {
  5873. return cli.Post(path, headers, body, content_type, receiver, progress);
  5874. });
  5875. }
  5876. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5877. #ifdef CPPHTTPLIB_SSL_ENABLED
  5878. using ClientT = SSLClient;
  5879. #else
  5880. using ClientT = Client;
  5881. #endif
  5882. TestWithHeadersAndContentReceiverWithProgress<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, DownloadProgress progress) {
  5886. return cli.Put(path, headers, body, content_type, receiver, progress);
  5887. });
  5888. }
  5889. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5890. #ifdef CPPHTTPLIB_SSL_ENABLED
  5891. using ClientT = SSLClient;
  5892. #else
  5893. using ClientT = Client;
  5894. #endif
  5895. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5896. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5897. const std::string &body, const std::string &content_type,
  5898. ContentReceiver receiver, DownloadProgress progress) {
  5899. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5900. });
  5901. }
  5902. template <typename ClientType>
  5903. void TestWithHeadersAndContentReceiverError(
  5904. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5905. const Headers &, const std::string &,
  5906. const std::string &, ContentReceiver)>
  5907. request_func) {
  5908. Headers headers;
  5909. headers.emplace("X-Error-Test", "true");
  5910. std::string received_body;
  5911. auto receiver_failed = false;
  5912. auto res =
  5913. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5914. [&](const char *data, size_t data_length) {
  5915. received_body.append(data, data_length);
  5916. receiver_failed = true;
  5917. return false;
  5918. });
  5919. ASSERT_FALSE(res);
  5920. EXPECT_TRUE(receiver_failed);
  5921. }
  5922. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5923. #ifdef CPPHTTPLIB_SSL_ENABLED
  5924. using ClientT = SSLClient;
  5925. #else
  5926. using ClientT = Client;
  5927. #endif
  5928. TestWithHeadersAndContentReceiverError<ClientT>(
  5929. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5930. const std::string &body, const std::string &content_type,
  5931. ContentReceiver receiver) {
  5932. return cli.Post(path, headers, body, content_type, receiver);
  5933. });
  5934. }
  5935. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5936. #ifdef CPPHTTPLIB_SSL_ENABLED
  5937. using ClientT = SSLClient;
  5938. #else
  5939. using ClientT = Client;
  5940. #endif
  5941. TestWithHeadersAndContentReceiverError<ClientT>(
  5942. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5943. const std::string &body, const std::string &content_type,
  5944. ContentReceiver receiver) {
  5945. return cli.Put(path, headers, body, content_type, receiver);
  5946. });
  5947. }
  5948. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5949. #ifdef CPPHTTPLIB_SSL_ENABLED
  5950. using ClientT = SSLClient;
  5951. #else
  5952. using ClientT = Client;
  5953. #endif
  5954. TestWithHeadersAndContentReceiverError<ClientT>(
  5955. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5956. const std::string &body, const std::string &content_type,
  5957. ContentReceiver receiver) {
  5958. return cli.Patch(path, headers, body, content_type, receiver);
  5959. });
  5960. }
  5961. TEST_F(ServerTest, PostQueryStringAndBody) {
  5962. auto res =
  5963. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5964. ASSERT_TRUE(res);
  5965. ASSERT_EQ(StatusCode::OK_200, res->status);
  5966. }
  5967. TEST_F(ServerTest, HTTP2Magic) {
  5968. Request req;
  5969. req.method = "PRI";
  5970. req.path = "*";
  5971. req.body = "SM";
  5972. auto res = std::make_shared<Response>();
  5973. auto error = Error::Success;
  5974. auto ret = cli_.send(req, *res, error);
  5975. ASSERT_TRUE(ret);
  5976. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5977. }
  5978. TEST_F(ServerTest, KeepAlive) {
  5979. auto res = cli_.Get("/hi");
  5980. ASSERT_TRUE(res);
  5981. EXPECT_EQ(StatusCode::OK_200, res->status);
  5982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5983. EXPECT_EQ("Hello World!", res->body);
  5984. res = cli_.Get("/hi");
  5985. ASSERT_TRUE(res);
  5986. EXPECT_EQ(StatusCode::OK_200, res->status);
  5987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5988. EXPECT_EQ("Hello World!", res->body);
  5989. res = cli_.Get("/hi");
  5990. ASSERT_TRUE(res);
  5991. EXPECT_EQ(StatusCode::OK_200, res->status);
  5992. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5993. EXPECT_EQ("Hello World!", res->body);
  5994. res = cli_.Get("/not-exist");
  5995. ASSERT_TRUE(res);
  5996. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5997. res = cli_.Post("/empty", "", "text/plain");
  5998. ASSERT_TRUE(res);
  5999. EXPECT_EQ(StatusCode::OK_200, res->status);
  6000. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6001. EXPECT_EQ("empty", res->body);
  6002. EXPECT_EQ("close", res->get_header_value("Connection"));
  6003. res = cli_.Post(
  6004. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6005. "text/plain");
  6006. ASSERT_TRUE(res);
  6007. EXPECT_EQ(StatusCode::OK_200, res->status);
  6008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6009. EXPECT_EQ("empty", res->body);
  6010. cli_.set_keep_alive(false);
  6011. res = cli_.Get("/last-request");
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. EXPECT_EQ("close", res->get_header_value("Connection"));
  6015. }
  6016. TEST_F(ServerTest, TooManyRedirect) {
  6017. cli_.set_follow_location(true);
  6018. auto res = cli_.Get("/redirect/0");
  6019. ASSERT_TRUE(!res);
  6020. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6021. }
  6022. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6023. Request req;
  6024. req.method = "FOOBAR";
  6025. req.path = "/hi";
  6026. cli_.set_keep_alive(true);
  6027. auto res = cli_.send(req);
  6028. ASSERT_TRUE(res);
  6029. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6030. EXPECT_EQ("close", res->get_header_value("Connection"));
  6031. EXPECT_FALSE(cli_.is_socket_open());
  6032. }
  6033. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6035. TEST_F(ServerTest, Gzip) {
  6036. Headers headers;
  6037. headers.emplace("Accept-Encoding", "gzip, deflate");
  6038. auto res = cli_.Get("/compress", headers);
  6039. ASSERT_TRUE(res);
  6040. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6042. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6043. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6044. "7890123456789012345678901234567890",
  6045. res->body);
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. }
  6048. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6049. Headers headers;
  6050. headers.emplace("Accept-Encoding", "gzip, deflate");
  6051. auto res = cli_.Get("/compress-with-charset", headers);
  6052. ASSERT_TRUE(res);
  6053. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6054. EXPECT_EQ("application/json; charset=utf-8",
  6055. res->get_header_value("Content-Type"));
  6056. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6057. "7890123456789012345678901234567890",
  6058. res->body);
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. }
  6061. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6062. Headers headers;
  6063. headers.emplace("Accept-Encoding", "");
  6064. auto res = cli_.Get("/compress", headers);
  6065. ASSERT_TRUE(res);
  6066. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6067. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6068. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6069. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6070. "7890123456789012345678901234567890",
  6071. res->body);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. }
  6074. TEST_F(ServerTest, GzipWithContentReceiver) {
  6075. Headers headers;
  6076. headers.emplace("Accept-Encoding", "gzip, deflate");
  6077. std::string body;
  6078. auto res = cli_.Get("/compress", headers,
  6079. [&](const char *data, uint64_t data_length) {
  6080. EXPECT_EQ(100U, data_length);
  6081. body.append(data, data_length);
  6082. return true;
  6083. });
  6084. ASSERT_TRUE(res);
  6085. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6087. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6088. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6089. "7890123456789012345678901234567890",
  6090. body);
  6091. EXPECT_EQ(StatusCode::OK_200, res->status);
  6092. }
  6093. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6094. Headers headers;
  6095. headers.emplace("Accept-Encoding", "gzip, deflate");
  6096. cli_.set_decompress(false);
  6097. auto res = cli_.Get("/compress", headers);
  6098. ASSERT_TRUE(res);
  6099. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6101. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6102. EXPECT_EQ(33U, res->body.size());
  6103. EXPECT_EQ(StatusCode::OK_200, res->status);
  6104. }
  6105. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6106. Headers headers;
  6107. headers.emplace("Accept-Encoding", "");
  6108. std::string body;
  6109. auto res = cli_.Get("/compress", headers,
  6110. [&](const char *data, uint64_t data_length) {
  6111. EXPECT_EQ(100U, data_length);
  6112. body.append(data, data_length);
  6113. return true;
  6114. });
  6115. ASSERT_TRUE(res);
  6116. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6118. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6120. "7890123456789012345678901234567890",
  6121. body);
  6122. EXPECT_EQ(StatusCode::OK_200, res->status);
  6123. }
  6124. TEST_F(ServerTest, NoGzip) {
  6125. Headers headers;
  6126. headers.emplace("Accept-Encoding", "gzip, deflate");
  6127. auto res = cli_.Get("/nocompress", headers);
  6128. ASSERT_TRUE(res);
  6129. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6130. EXPECT_EQ("application/octet-stream", 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, NoGzipWithContentReceiver) {
  6138. Headers headers;
  6139. headers.emplace("Accept-Encoding", "gzip, deflate");
  6140. std::string body;
  6141. auto res = cli_.Get("/nocompress", 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(false, res->has_header("Content-Encoding"));
  6149. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6150. EXPECT_EQ("100", 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, MultipartFormDataGzip) {
  6157. UploadFormDataItems items = {
  6158. {"key1", "test", "", ""},
  6159. {"key2", "--abcdefg123", "", ""},
  6160. };
  6161. cli_.set_compress(true);
  6162. auto res = cli_.Post("/compress-multipart", items);
  6163. ASSERT_TRUE(res);
  6164. EXPECT_EQ(StatusCode::OK_200, res->status);
  6165. }
  6166. #endif
  6167. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6168. TEST_F(ServerTest, Brotli) {
  6169. Headers headers;
  6170. headers.emplace("Accept-Encoding", "br");
  6171. auto res = cli_.Get("/compress", headers);
  6172. ASSERT_TRUE(res);
  6173. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6175. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6176. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6177. "7890123456789012345678901234567890",
  6178. res->body);
  6179. EXPECT_EQ(StatusCode::OK_200, res->status);
  6180. }
  6181. #endif
  6182. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6183. TEST_F(ServerTest, Zstd) {
  6184. Headers headers;
  6185. headers.emplace("Accept-Encoding", "zstd");
  6186. auto res = cli_.Get("/compress", headers);
  6187. ASSERT_TRUE(res);
  6188. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6190. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6191. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6192. "7890123456789012345678901234567890",
  6193. res->body);
  6194. EXPECT_EQ(StatusCode::OK_200, res->status);
  6195. }
  6196. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6197. Headers headers;
  6198. headers.emplace("Accept-Encoding", "");
  6199. auto res = cli_.Get("/compress", headers);
  6200. ASSERT_TRUE(res);
  6201. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6203. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6204. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6205. "7890123456789012345678901234567890",
  6206. res->body);
  6207. EXPECT_EQ(StatusCode::OK_200, res->status);
  6208. }
  6209. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6210. Headers headers;
  6211. headers.emplace("Accept-Encoding", "zstd");
  6212. std::string body;
  6213. auto res = cli_.Get("/compress", headers,
  6214. [&](const char *data, uint64_t data_length) {
  6215. EXPECT_EQ(100U, data_length);
  6216. body.append(data, data_length);
  6217. return true;
  6218. });
  6219. ASSERT_TRUE(res);
  6220. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6222. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6223. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6224. "7890123456789012345678901234567890",
  6225. body);
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6229. Headers headers;
  6230. headers.emplace("Accept-Encoding", "zstd");
  6231. cli_.set_decompress(false);
  6232. auto res = cli_.Get("/compress", headers);
  6233. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6234. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6235. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6236. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6237. ASSERT_TRUE(res);
  6238. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6240. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6241. EXPECT_EQ(StatusCode::OK_200, res->status);
  6242. ASSERT_EQ(26U, res->body.size());
  6243. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6244. 0);
  6245. }
  6246. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6247. Headers headers;
  6248. headers.emplace("Accept-Encoding", "");
  6249. std::string body;
  6250. auto res = cli_.Get("/compress", headers,
  6251. [&](const char *data, uint64_t data_length) {
  6252. EXPECT_EQ(100U, data_length);
  6253. body.append(data, data_length);
  6254. return true;
  6255. });
  6256. ASSERT_TRUE(res);
  6257. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6258. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6259. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6260. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6261. "7890123456789012345678901234567890",
  6262. body);
  6263. EXPECT_EQ(StatusCode::OK_200, res->status);
  6264. }
  6265. TEST_F(ServerTest, NoZstd) {
  6266. Headers headers;
  6267. headers.emplace("Accept-Encoding", "zstd");
  6268. auto res = cli_.Get("/nocompress", headers);
  6269. ASSERT_TRUE(res);
  6270. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6271. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6272. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6273. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6274. "7890123456789012345678901234567890",
  6275. res->body);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. }
  6278. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6279. Headers headers;
  6280. headers.emplace("Accept-Encoding", "zstd");
  6281. std::string body;
  6282. auto res = cli_.Get("/nocompress", headers,
  6283. [&](const char *data, uint64_t data_length) {
  6284. EXPECT_EQ(100U, data_length);
  6285. body.append(data, data_length);
  6286. return true;
  6287. });
  6288. ASSERT_TRUE(res);
  6289. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6290. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6291. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6292. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6293. "7890123456789012345678901234567890",
  6294. body);
  6295. EXPECT_EQ(StatusCode::OK_200, res->status);
  6296. }
  6297. // TODO: How to enable zstd ??
  6298. TEST_F(ServerTest, MultipartFormDataZstd) {
  6299. UploadFormDataItems items = {
  6300. {"key1", "test", "", ""},
  6301. {"key2", "--abcdefg123", "", ""},
  6302. };
  6303. Headers headers;
  6304. headers.emplace("Accept-Encoding", "zstd");
  6305. cli_.set_compress(true);
  6306. auto res = cli_.Post("/compress-multipart", headers, items);
  6307. ASSERT_TRUE(res);
  6308. EXPECT_EQ(StatusCode::OK_200, res->status);
  6309. }
  6310. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6311. Headers headers;
  6312. headers.emplace("Accept-Encoding", "zstd");
  6313. cli_.set_compress(true);
  6314. auto res = cli_.Put(
  6315. "/put", headers, 3,
  6316. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6317. sink.os << "PUT";
  6318. return true;
  6319. },
  6320. "text/plain");
  6321. ASSERT_TRUE(res);
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. EXPECT_EQ("PUT", res->body);
  6324. }
  6325. // Pre-compression logging tests
  6326. TEST_F(ServerTest, PreCompressionLogging) {
  6327. // Test data for compression (matches the actual /compress endpoint content)
  6328. const std::string test_content =
  6329. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6330. "3456789012345678901234567890";
  6331. // Variables to capture logging data
  6332. std::string pre_compression_body;
  6333. std::string pre_compression_content_type;
  6334. std::string pre_compression_content_encoding;
  6335. std::string post_compression_body;
  6336. std::string post_compression_content_type;
  6337. std::string post_compression_content_encoding;
  6338. // Set up pre-compression logger
  6339. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6340. const Response &res) {
  6341. pre_compression_body = res.body;
  6342. pre_compression_content_type = res.get_header_value("Content-Type");
  6343. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6344. });
  6345. // Set up post-compression logger
  6346. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6347. post_compression_body = res.body;
  6348. post_compression_content_type = res.get_header_value("Content-Type");
  6349. post_compression_content_encoding =
  6350. res.get_header_value("Content-Encoding");
  6351. });
  6352. // Test with gzip compression
  6353. Headers headers;
  6354. headers.emplace("Accept-Encoding", "gzip");
  6355. auto res = cli_.Get("/compress", headers);
  6356. // Verify response was compressed
  6357. ASSERT_TRUE(res);
  6358. EXPECT_EQ(StatusCode::OK_200, res->status);
  6359. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6360. // Verify pre-compression logger captured uncompressed content
  6361. EXPECT_EQ(test_content, pre_compression_body);
  6362. EXPECT_EQ("text/plain", pre_compression_content_type);
  6363. EXPECT_TRUE(pre_compression_content_encoding
  6364. .empty()); // No encoding header before compression
  6365. // Verify post-compression logger captured compressed content
  6366. EXPECT_NE(test_content,
  6367. post_compression_body); // Should be different after compression
  6368. EXPECT_EQ("text/plain", post_compression_content_type);
  6369. EXPECT_EQ("gzip", post_compression_content_encoding);
  6370. // Verify compressed content is smaller
  6371. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6372. }
  6373. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6374. const std::string test_content =
  6375. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6376. "3456789012345678901234567890";
  6377. std::string pre_compression_body;
  6378. std::string post_compression_body;
  6379. svr_.set_pre_compression_logger(
  6380. [&](const Request & /*req*/, const Response &res) {
  6381. pre_compression_body = res.body;
  6382. });
  6383. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6384. post_compression_body = res.body;
  6385. });
  6386. Headers headers;
  6387. headers.emplace("Accept-Encoding", "br");
  6388. auto res = cli_.Get("/compress", headers);
  6389. ASSERT_TRUE(res);
  6390. EXPECT_EQ(StatusCode::OK_200, res->status);
  6391. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6392. // Verify pre-compression content is uncompressed
  6393. EXPECT_EQ(test_content, pre_compression_body);
  6394. // Verify post-compression content is compressed
  6395. EXPECT_NE(test_content, post_compression_body);
  6396. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6397. }
  6398. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6399. const std::string test_content =
  6400. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6401. "3456789012345678901234567890";
  6402. std::string pre_compression_body;
  6403. std::string post_compression_body;
  6404. svr_.set_pre_compression_logger(
  6405. [&](const Request & /*req*/, const Response &res) {
  6406. pre_compression_body = res.body;
  6407. });
  6408. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6409. post_compression_body = res.body;
  6410. });
  6411. // Request without compression (use /nocompress endpoint)
  6412. Headers headers;
  6413. auto res = cli_.Get("/nocompress", headers);
  6414. ASSERT_TRUE(res);
  6415. EXPECT_EQ(StatusCode::OK_200, res->status);
  6416. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6417. // Pre-compression logger should not be called when no compression is applied
  6418. EXPECT_TRUE(
  6419. pre_compression_body.empty()); // Pre-compression logger not called
  6420. EXPECT_EQ(
  6421. test_content,
  6422. post_compression_body); // Post-compression logger captures final content
  6423. }
  6424. TEST_F(ServerTest, LoggerSeesContentLength) {
  6425. size_t logged_content_length = 0;
  6426. std::string logged_content_length_header;
  6427. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6428. logged_content_length = res.content_length_;
  6429. logged_content_length_header = res.get_header_value("Content-Length");
  6430. });
  6431. auto res = cli_.Get("/nocompress");
  6432. ASSERT_TRUE(res);
  6433. EXPECT_EQ(StatusCode::OK_200, res->status);
  6434. EXPECT_EQ(res->body.size(), logged_content_length);
  6435. EXPECT_EQ(std::to_string(logged_content_length),
  6436. logged_content_length_header);
  6437. }
  6438. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6439. const std::string test_content =
  6440. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6441. "3456789012345678901234567890";
  6442. std::string pre_compression_body;
  6443. bool pre_logger_called = false;
  6444. // Set only pre-compression logger
  6445. svr_.set_pre_compression_logger(
  6446. [&](const Request & /*req*/, const Response &res) {
  6447. pre_compression_body = res.body;
  6448. pre_logger_called = true;
  6449. });
  6450. Headers headers;
  6451. headers.emplace("Accept-Encoding", "gzip");
  6452. auto res = cli_.Get("/compress", headers);
  6453. ASSERT_TRUE(res);
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6456. // Verify pre-compression logger was called
  6457. EXPECT_TRUE(pre_logger_called);
  6458. EXPECT_EQ(test_content, pre_compression_body);
  6459. }
  6460. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6461. {
  6462. // Test with Expect: 100-continue header - success case
  6463. // Server returns 100 Continue, client sends body, server returns 200 OK
  6464. Request req;
  6465. req.method = "POST";
  6466. req.path = "/post-large";
  6467. req.set_header("Expect", "100-continue");
  6468. req.body = LARGE_DATA;
  6469. Response res;
  6470. auto error = Error::Success;
  6471. cli_.set_keep_alive(true);
  6472. auto ret = cli_.send(req, res, error);
  6473. EXPECT_TRUE(ret);
  6474. EXPECT_EQ(StatusCode::OK_200, res.status);
  6475. EXPECT_EQ(LARGE_DATA, res.body);
  6476. }
  6477. {
  6478. // Test with Expect: 100-continue header - error case
  6479. // Client should not send the body when server returns an error
  6480. Request req;
  6481. req.method = "POST";
  6482. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6483. req.set_header("Expect", "100-continue");
  6484. req.body = LARGE_DATA;
  6485. Response res;
  6486. auto error = Error::Success;
  6487. auto start = std::chrono::high_resolution_clock::now();
  6488. cli_.set_keep_alive(true);
  6489. auto ret = cli_.send(req, res, error);
  6490. auto end = std::chrono::high_resolution_clock::now();
  6491. auto elapsed =
  6492. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6493. .count();
  6494. // With Expect: 100-continue, request completes successfully but with error
  6495. EXPECT_TRUE(ret);
  6496. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6497. EXPECT_EQ("close", res.get_header_value("Connection"));
  6498. EXPECT_FALSE(cli_.is_socket_open());
  6499. EXPECT_LE(elapsed, 2000);
  6500. }
  6501. {
  6502. // Send an extra GET request to ensure error recovery without hanging
  6503. Request req;
  6504. req.method = "GET";
  6505. req.path = "/hi";
  6506. auto start = std::chrono::high_resolution_clock::now();
  6507. auto res = cli_.send(req);
  6508. auto end = std::chrono::high_resolution_clock::now();
  6509. auto elapsed =
  6510. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6511. .count();
  6512. ASSERT_TRUE(res);
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. EXPECT_EQ("Hello World!", res->body);
  6515. EXPECT_LE(elapsed, 500);
  6516. }
  6517. }
  6518. TEST(ZstdDecompressor, ChunkedDecompression) {
  6519. std::string data;
  6520. for (size_t i = 0; i < 32 * 1024; ++i) {
  6521. data.push_back(static_cast<char>('a' + i % 26));
  6522. }
  6523. std::string compressed_data;
  6524. {
  6525. httplib::detail::zstd_compressor compressor;
  6526. bool result = compressor.compress(
  6527. data.data(), data.size(),
  6528. /*last=*/true,
  6529. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6530. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6531. compressed_data_size);
  6532. return true;
  6533. });
  6534. ASSERT_TRUE(result);
  6535. }
  6536. std::string decompressed_data;
  6537. {
  6538. httplib::detail::zstd_decompressor decompressor;
  6539. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6540. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6541. size_t chunk_size = 130;
  6542. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6543. chunk_begin += chunk_size) {
  6544. size_t current_chunk_size =
  6545. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6546. bool result = decompressor.decompress(
  6547. compressed_data.data() + chunk_begin, current_chunk_size,
  6548. [&](const char *decompressed_data_chunk,
  6549. size_t decompressed_data_chunk_size) {
  6550. decompressed_data.insert(decompressed_data.size(),
  6551. decompressed_data_chunk,
  6552. decompressed_data_chunk_size);
  6553. return true;
  6554. });
  6555. ASSERT_TRUE(result);
  6556. }
  6557. }
  6558. ASSERT_EQ(data, decompressed_data);
  6559. }
  6560. TEST(ZstdDecompressor, Decompress) {
  6561. std::string original_text = "Compressed with ZSTD";
  6562. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6563. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6564. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6565. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6566. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6567. std::string decompressed_data;
  6568. {
  6569. httplib::detail::zstd_decompressor decompressor;
  6570. bool result = decompressor.decompress(
  6571. compressed_data.data(), compressed_data.size(),
  6572. [&](const char *decompressed_data_chunk,
  6573. size_t decompressed_data_chunk_size) {
  6574. decompressed_data.insert(decompressed_data.size(),
  6575. decompressed_data_chunk,
  6576. decompressed_data_chunk_size);
  6577. return true;
  6578. });
  6579. ASSERT_TRUE(result);
  6580. }
  6581. ASSERT_EQ(original_text, decompressed_data);
  6582. }
  6583. #endif
  6584. // Sends a raw request to a server listening at HOST:PORT.
  6585. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6586. std::string *resp = nullptr) {
  6587. auto error = Error::Success;
  6588. auto client_sock = detail::create_client_socket(
  6589. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6590. /*connection_timeout_sec=*/5, 0,
  6591. /*read_timeout_sec=*/5, 0,
  6592. /*write_timeout_sec=*/5, 0, std::string(), error);
  6593. if (client_sock == INVALID_SOCKET) { return false; }
  6594. auto ret = detail::process_client_socket(
  6595. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6596. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6597. if (req.size() !=
  6598. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6599. return false;
  6600. }
  6601. char buf[512];
  6602. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6603. while (line_reader.getline()) {
  6604. if (resp) { *resp += line_reader.ptr(); }
  6605. }
  6606. return true;
  6607. });
  6608. detail::close_socket(client_sock);
  6609. return ret;
  6610. }
  6611. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6612. Server svr;
  6613. std::string header_value;
  6614. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6615. header_value = req.get_header_value("foo");
  6616. res.set_content("ok", "text/plain");
  6617. });
  6618. thread t = thread([&] { svr.listen(HOST, PORT); });
  6619. auto se = detail::scope_exit([&] {
  6620. svr.stop();
  6621. t.join();
  6622. ASSERT_FALSE(svr.is_running());
  6623. });
  6624. svr.wait_until_ready();
  6625. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6626. // like characters are not treated the same - use vertical tab and escape.
  6627. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6628. "foo: \t \v bar \x1B\t \r\n"
  6629. "Connection: close\r\n"
  6630. "\r\n";
  6631. std::string res;
  6632. ASSERT_TRUE(send_request(5, req, &res));
  6633. EXPECT_EQ(header_value, "");
  6634. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6635. }
  6636. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6637. Server svr;
  6638. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6639. auto i = new int(0);
  6640. res.set_header("Trailer", "X-Safe, X-Reflected");
  6641. res.set_chunked_content_provider(
  6642. "text/plain",
  6643. [i](size_t /*offset*/, DataSink &sink) {
  6644. if (*i == 0) {
  6645. sink.os << "body";
  6646. } else {
  6647. Headers trailer;
  6648. // A valid trailer that must survive.
  6649. trailer.emplace("X-Safe", "safe");
  6650. // Attacker-controlled value carrying CR/LF (response splitting).
  6651. trailer.emplace("X-Reflected",
  6652. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6653. // Attacker-controlled name carrying CR/LF.
  6654. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6655. sink.done_with_trailer(trailer);
  6656. }
  6657. (*i)++;
  6658. return true;
  6659. },
  6660. [i](bool /*success*/) { delete i; });
  6661. });
  6662. thread t = thread([&] { svr.listen(HOST, PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. t.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6670. "Host: " + HOST +
  6671. "\r\n"
  6672. "Connection: close\r\n"
  6673. "\r\n";
  6674. std::string res;
  6675. ASSERT_TRUE(send_request(5, req, &res));
  6676. // The injected fields must not appear anywhere in the raw response.
  6677. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6678. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6679. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6680. // Invalid trailers are dropped entirely, matching set_header().
  6681. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6682. // The valid trailer still passes through.
  6683. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6684. }
  6685. // Sends a raw request and verifies that there isn't a crash or exception.
  6686. static void test_raw_request(const std::string &req,
  6687. std::string *out = nullptr) {
  6688. Server svr;
  6689. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6690. res.set_content("ok", "text/plain");
  6691. });
  6692. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6693. res.set_content("ok", "text/plain");
  6694. });
  6695. svr.Get("/header_field_value_check",
  6696. [&](const Request & /*req*/, Response &res) {
  6697. res.set_content("ok", "text/plain");
  6698. });
  6699. // Server read timeout must be longer than the client read timeout for the
  6700. // bug to reproduce, probably to force the server to process a request
  6701. // without a trailing blank line.
  6702. const time_t client_read_timeout_sec = 1;
  6703. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6704. bool listen_thread_ok = false;
  6705. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6706. auto se = detail::scope_exit([&] {
  6707. svr.stop();
  6708. t.join();
  6709. ASSERT_FALSE(svr.is_running());
  6710. EXPECT_TRUE(listen_thread_ok);
  6711. });
  6712. svr.wait_until_ready();
  6713. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6714. }
  6715. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6716. // A certain header line causes an exception if the header property is parsed
  6717. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6718. test_raw_request(
  6719. "GET /hi HTTP/1.1\r\n"
  6720. " : "
  6721. " "
  6722. " ");
  6723. }
  6724. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6725. // A certain header line causes an exception if the header property *name* is
  6726. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6727. // greedy matcher and requires backtracking when there are a lot of ":"
  6728. // characters.
  6729. // This occurs with libc++ but not libstdc++.
  6730. test_raw_request(
  6731. "GET /hi HTTP/1.1\r\n"
  6732. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6733. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6734. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6735. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6736. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6737. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6738. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6739. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6740. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6741. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6742. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6743. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6744. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6745. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6746. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6747. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6748. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6749. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6750. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6751. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6752. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6753. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6754. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6755. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6756. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6757. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6758. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6759. "&&&%%%");
  6760. }
  6761. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6762. // Make sure this doesn't crash the server.
  6763. // In a previous version of the header line regex, the "\r" rendered the line
  6764. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6765. // a new position where the leading white space ended and the field value
  6766. // began.
  6767. // The crash occurs with libc++ but not libstdc++.
  6768. test_raw_request("GET /hi HTTP/1.1\r\n"
  6769. "a:" +
  6770. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6771. "\r\n"
  6772. "\r\n");
  6773. }
  6774. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6775. std::string out;
  6776. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6777. "Content-Type: text/plain\r\n"
  6778. "Transfer-Encoding: chunked\r\n"
  6779. "\r\n"
  6780. "nothex\r\n",
  6781. &out);
  6782. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6783. }
  6784. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6785. std::string out;
  6786. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6787. "Content-Type: text/plain\r\n"
  6788. "Transfer-Encoding: chunked\r\n"
  6789. "\r\n"
  6790. "3\r\n"
  6791. "xyz\r\n"
  6792. "NaN\r\n",
  6793. &out);
  6794. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6795. }
  6796. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6797. std::string out;
  6798. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6799. "Content-Type: text/plain\r\n"
  6800. "Transfer-Encoding: chunked\r\n"
  6801. "\r\n"
  6802. // Length is too large for 64 bits.
  6803. "1ffffffffffffffff\r\n"
  6804. "xyz\r\n",
  6805. &out);
  6806. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6807. }
  6808. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6809. test_raw_request("GET /hi HTTP/1.1\r\n"
  6810. "Content-Type: text/plain\r\n\r");
  6811. }
  6812. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6813. std::string out;
  6814. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6815. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6816. }
  6817. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6818. Server svr;
  6819. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6820. EXPECT_TRUE(!req.remote_addr.empty());
  6821. });
  6822. thread t = thread([&] { svr.listen(HOST, PORT); });
  6823. auto se = detail::scope_exit([&] {
  6824. svr.stop();
  6825. t.join();
  6826. ASSERT_FALSE(svr.is_running());
  6827. });
  6828. svr.wait_until_ready();
  6829. // Send an invalid request line to trigger Bad Request
  6830. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6831. std::string out;
  6832. ASSERT_TRUE(send_request(5, bad_req, &out));
  6833. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6834. }
  6835. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6836. std::string out;
  6837. std::string request(
  6838. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6839. test_raw_request(request, &out);
  6840. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6841. }
  6842. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6843. std::string out;
  6844. std::string request(
  6845. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6846. test_raw_request(request, &out);
  6847. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6848. }
  6849. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6850. std::string out;
  6851. std::string request(
  6852. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6853. test_raw_request(request, &out);
  6854. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6855. }
  6856. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6857. std::string out;
  6858. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6859. "Test: \r\n\r\n",
  6860. &out);
  6861. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6862. }
  6863. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6864. Server svr;
  6865. std::string x_custom;
  6866. std::string cookie;
  6867. std::string xff;
  6868. std::string x_unicode;
  6869. std::string x_iis;
  6870. svr.Get("/check", [&](const Request &req, Response &res) {
  6871. x_custom = req.get_header_value("X-Custom");
  6872. cookie = req.get_header_value("Cookie");
  6873. xff = req.get_header_value("X-Forwarded-For");
  6874. x_unicode = req.get_header_value("X-Unicode");
  6875. x_iis = req.get_header_value("X-IIS");
  6876. res.set_content("ok", "text/plain");
  6877. });
  6878. thread t = thread([&] { svr.listen(HOST, PORT); });
  6879. auto se = detail::scope_exit([&] {
  6880. svr.stop();
  6881. t.join();
  6882. ASSERT_FALSE(svr.is_running());
  6883. });
  6884. svr.wait_until_ready();
  6885. const std::string req = "GET /check HTTP/1.1\r\n"
  6886. "Host: localhost\r\n"
  6887. "X-Custom: a%0D%0AInjected: b\r\n"
  6888. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6889. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6890. "X-Unicode: %E3%81%82\r\n"
  6891. "X-IIS: %u00E9\r\n"
  6892. "Connection: close\r\n"
  6893. "\r\n";
  6894. std::string res;
  6895. ASSERT_TRUE(send_request(5, req, &res));
  6896. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6897. // Every value must be returned verbatim (wire form), with no decoding.
  6898. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6899. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6900. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6901. EXPECT_EQ("%E3%81%82", x_unicode);
  6902. EXPECT_EQ("%u00E9", x_iis);
  6903. }
  6904. // Applications that previously relied on automatic percent-decoding can
  6905. // reproduce the old behavior by explicitly calling decode_path_component()
  6906. // or, for RFC 3986 conformance, decode_uri_component().
  6907. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6908. Server svr;
  6909. std::string decoded;
  6910. svr.Get("/check", [&](const Request &req, Response &res) {
  6911. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6912. res.set_content("ok", "text/plain");
  6913. });
  6914. thread t = thread([&] { svr.listen(HOST, PORT); });
  6915. auto se = detail::scope_exit([&] {
  6916. svr.stop();
  6917. t.join();
  6918. ASSERT_FALSE(svr.is_running());
  6919. });
  6920. svr.wait_until_ready();
  6921. const std::string req = "GET /check HTTP/1.1\r\n"
  6922. "Host: localhost\r\n"
  6923. "X-Custom: hello%20world\r\n"
  6924. "Connection: close\r\n"
  6925. "\r\n";
  6926. std::string res;
  6927. ASSERT_TRUE(send_request(5, req, &res));
  6928. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6929. EXPECT_EQ("hello world", decoded);
  6930. }
  6931. // Regression test for #2033. Browsers send Referer values that include
  6932. // percent-encoded characters such as %0A inside the URL. Decoding the
  6933. // header value would either trip the post-decode CR/LF/NUL guard (the
  6934. // original bug, returning 400) or, after that guard was relaxed, silently
  6935. // store a literal LF — both unacceptable. The wire form must round-trip.
  6936. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6937. Server svr;
  6938. std::string referer;
  6939. svr.Get("/check", [&](const Request &req, Response &res) {
  6940. referer = req.get_header_value("Referer");
  6941. res.set_content("ok", "text/plain");
  6942. });
  6943. thread t = thread([&] { svr.listen(HOST, PORT); });
  6944. auto se = detail::scope_exit([&] {
  6945. svr.stop();
  6946. t.join();
  6947. ASSERT_FALSE(svr.is_running());
  6948. });
  6949. svr.wait_until_ready();
  6950. const std::string req = "GET /check HTTP/1.1\r\n"
  6951. "Host: localhost\r\n"
  6952. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6953. "Connection: close\r\n"
  6954. "\r\n";
  6955. std::string res;
  6956. ASSERT_TRUE(send_request(5, req, &res));
  6957. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6958. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6959. }
  6960. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6961. Server svr;
  6962. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6963. res.set_header("Cache-Control", "no-cache");
  6964. res.set_chunked_content_provider(
  6965. "text/event-stream", [](size_t offset, DataSink &sink) {
  6966. std::string s = "data:";
  6967. s += std::to_string(offset);
  6968. s += "\n\n";
  6969. auto ret = sink.write(s.data(), s.size());
  6970. EXPECT_TRUE(ret);
  6971. std::this_thread::sleep_for(std::chrono::seconds(1));
  6972. return true;
  6973. });
  6974. });
  6975. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6976. svr.wait_until_ready();
  6977. Client client(HOST, PORT);
  6978. const Headers headers = {{"Accept", "text/event-stream"}};
  6979. auto get_thread = std::thread([&client, &headers]() {
  6980. auto res = client.Get(
  6981. "/events", headers,
  6982. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6983. });
  6984. auto se = detail::scope_exit([&] {
  6985. svr.stop();
  6986. get_thread.join();
  6987. listen_thread.join();
  6988. ASSERT_FALSE(svr.is_running());
  6989. });
  6990. // Give GET time to get a few messages.
  6991. std::this_thread::sleep_for(std::chrono::seconds(2));
  6992. }
  6993. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6994. httplib::Server svr;
  6995. svr.Post("/hi",
  6996. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6997. res.status = StatusCode::OK_200;
  6998. });
  6999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7000. svr.wait_until_ready();
  7001. Client cli(HOST, PORT);
  7002. auto res = cli.Post("/hi", "data", "text/plain");
  7003. ASSERT_TRUE(res);
  7004. EXPECT_EQ(StatusCode::OK_200, res->status);
  7005. svr.stop();
  7006. thread.join();
  7007. ASSERT_FALSE(svr.is_running());
  7008. res = cli.Post("/hi", "data", "text/plain");
  7009. ASSERT_FALSE(res);
  7010. }
  7011. TEST(ServerStopTest, ListenFailure) {
  7012. Server svr;
  7013. auto t = thread([&]() {
  7014. auto ret = svr.listen("????", PORT);
  7015. EXPECT_FALSE(ret);
  7016. });
  7017. svr.wait_until_ready();
  7018. svr.stop();
  7019. t.join();
  7020. }
  7021. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7022. TEST(ServerStopTest, Decommision) {
  7023. Server svr;
  7024. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7025. for (int i = 0; i < 4; i++) {
  7026. auto is_even = !(i % 2);
  7027. std::thread t{[&] {
  7028. try {
  7029. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7030. if (is_even) {
  7031. throw std::runtime_error("Some thing that happens to go wrong.");
  7032. }
  7033. svr.listen(HOST, PORT);
  7034. } catch (...) { svr.decommission(); }
  7035. }};
  7036. svr.wait_until_ready();
  7037. // Server is up
  7038. {
  7039. Client cli(HOST, PORT);
  7040. auto res = cli.Get("/hi");
  7041. if (is_even) {
  7042. EXPECT_FALSE(res);
  7043. } else {
  7044. EXPECT_TRUE(res);
  7045. EXPECT_EQ("hi...", res->body);
  7046. }
  7047. }
  7048. svr.stop();
  7049. t.join();
  7050. // Server is down...
  7051. {
  7052. Client cli(HOST, PORT);
  7053. auto res = cli.Get("/hi");
  7054. EXPECT_FALSE(res);
  7055. }
  7056. }
  7057. }
  7058. #endif
  7059. // Helper function for string body upload progress tests
  7060. template <typename SetupHandler, typename ClientCall>
  7061. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7062. ClientCall &&client_call,
  7063. const string &body) {
  7064. Server svr;
  7065. setup_handler(svr);
  7066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7067. auto se = detail::scope_exit([&] {
  7068. svr.stop();
  7069. t.join();
  7070. });
  7071. svr.wait_until_ready();
  7072. Client cli(HOST, PORT);
  7073. vector<uint64_t> progress_values;
  7074. bool progress_called = false;
  7075. auto res =
  7076. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7077. progress_values.push_back(current);
  7078. progress_called = true;
  7079. return true;
  7080. });
  7081. ASSERT_TRUE(res);
  7082. EXPECT_EQ(200, res->status);
  7083. EXPECT_TRUE(progress_called);
  7084. }
  7085. TEST(UploadProgressTest, PostStringBodyBasic) {
  7086. TestStringBodyUploadProgress(
  7087. [](Server &svr) {
  7088. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7089. res.set_content("received", "text/plain");
  7090. });
  7091. },
  7092. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7093. return cli.Post("/test", body, "text/plain", progress_callback);
  7094. },
  7095. "test data for upload progress");
  7096. }
  7097. TEST(UploadProgressTest, PutStringBodyBasic) {
  7098. TestStringBodyUploadProgress(
  7099. [](Server &svr) {
  7100. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7101. res.set_content("put received", "text/plain");
  7102. });
  7103. },
  7104. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7105. return cli.Put("/test", body, "text/plain", progress_callback);
  7106. },
  7107. "put test data for upload progress");
  7108. }
  7109. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7110. TestStringBodyUploadProgress(
  7111. [](Server &svr) {
  7112. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7113. res.set_content("patch received", "text/plain");
  7114. });
  7115. },
  7116. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7117. return cli.Patch("/test", body, "text/plain", progress_callback);
  7118. },
  7119. "patch test data for upload progress");
  7120. }
  7121. // Helper function for content provider upload progress tests
  7122. template <typename SetupHandler, typename ClientCall>
  7123. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7124. ClientCall &&client_call) {
  7125. Server svr;
  7126. setup_handler(svr);
  7127. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7128. auto se = detail::scope_exit([&] {
  7129. svr.stop();
  7130. t.join();
  7131. });
  7132. svr.wait_until_ready();
  7133. Client cli(HOST, PORT);
  7134. vector<uint64_t> progress_values;
  7135. auto res =
  7136. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7137. progress_values.push_back(current);
  7138. return true;
  7139. });
  7140. ASSERT_TRUE(res);
  7141. EXPECT_EQ(200, res->status);
  7142. EXPECT_FALSE(progress_values.empty());
  7143. }
  7144. TEST(UploadProgressTest, PostContentProviderProgress) {
  7145. TestContentProviderUploadProgress(
  7146. [](Server &svr) {
  7147. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7148. res.set_content("provider received", "text/plain");
  7149. });
  7150. },
  7151. [](Client &cli, UploadProgress progress_callback) {
  7152. return cli.Post(
  7153. "/test", 10,
  7154. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7155. sink.os << "test data";
  7156. return true;
  7157. },
  7158. "text/plain", progress_callback);
  7159. });
  7160. }
  7161. // Helper function for multipart upload progress tests
  7162. template <typename SetupHandler, typename ClientCall>
  7163. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7164. ClientCall &&client_call,
  7165. const string &endpoint) {
  7166. Server svr;
  7167. setup_handler(svr);
  7168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7169. auto se = detail::scope_exit([&] {
  7170. svr.stop();
  7171. t.join();
  7172. });
  7173. svr.wait_until_ready();
  7174. Client cli(HOST, PORT);
  7175. vector<uint64_t> progress_values;
  7176. UploadFormDataItems items = {
  7177. {"field1", "value1", "", ""},
  7178. {"field2", "longer value for progress tracking test", "", ""},
  7179. {"file1", "file content data for upload progress", "test.txt",
  7180. "text/plain"}};
  7181. auto res = client_call(cli, endpoint, items,
  7182. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7183. progress_values.push_back(current);
  7184. return true;
  7185. });
  7186. ASSERT_TRUE(res);
  7187. EXPECT_EQ(200, res->status);
  7188. EXPECT_FALSE(progress_values.empty());
  7189. }
  7190. TEST(UploadProgressTest, PostMultipartProgress) {
  7191. TestMultipartUploadProgress(
  7192. [](Server &svr) {
  7193. svr.Post("/multipart", [](const Request &req, Response &res) {
  7194. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7195. res.set_content("multipart received", "text/plain");
  7196. });
  7197. },
  7198. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7199. UploadProgress progress_callback) {
  7200. return cli.Post(endpoint, items, progress_callback);
  7201. },
  7202. "/multipart");
  7203. }
  7204. // Helper function for basic download progress tests
  7205. template <typename SetupHandler, typename ClientCall>
  7206. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7207. ClientCall &&client_call, const string &endpoint,
  7208. size_t expected_content_size) {
  7209. Server svr;
  7210. setup_handler(svr);
  7211. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7212. auto se = detail::scope_exit([&] {
  7213. svr.stop();
  7214. t.join();
  7215. });
  7216. svr.wait_until_ready();
  7217. Client cli(HOST, PORT);
  7218. vector<uint64_t> progress_values;
  7219. auto res = client_call(cli, endpoint,
  7220. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7221. progress_values.push_back(current);
  7222. return true;
  7223. });
  7224. ASSERT_TRUE(res);
  7225. EXPECT_EQ(200, res->status);
  7226. EXPECT_FALSE(progress_values.empty());
  7227. EXPECT_EQ(expected_content_size, res->body.size());
  7228. }
  7229. TEST(DownloadProgressTest, GetBasic) {
  7230. TestBasicDownloadProgress(
  7231. [](Server &svr) {
  7232. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7233. string content(1000, 'D');
  7234. res.set_content(content, "text/plain");
  7235. });
  7236. },
  7237. [](Client &cli, const string &endpoint,
  7238. DownloadProgress progress_callback) {
  7239. return cli.Get(endpoint, progress_callback);
  7240. },
  7241. "/download", 1000u);
  7242. }
  7243. // Helper function for content receiver download progress tests
  7244. template <typename SetupHandler, typename ClientCall>
  7245. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7246. ClientCall &&client_call,
  7247. const string &endpoint,
  7248. size_t expected_content_size) {
  7249. Server svr;
  7250. setup_handler(svr);
  7251. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7252. auto se = detail::scope_exit([&] {
  7253. svr.stop();
  7254. t.join();
  7255. });
  7256. svr.wait_until_ready();
  7257. Client cli(HOST, PORT);
  7258. vector<uint64_t> progress_values;
  7259. string received_body;
  7260. auto res = client_call(
  7261. cli, endpoint,
  7262. [&](const char *data, size_t data_length) -> bool {
  7263. received_body.append(data, data_length);
  7264. return true;
  7265. },
  7266. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7267. progress_values.push_back(current);
  7268. return true;
  7269. });
  7270. ASSERT_TRUE(res);
  7271. EXPECT_EQ(200, res->status);
  7272. EXPECT_FALSE(progress_values.empty());
  7273. EXPECT_EQ(expected_content_size, received_body.size());
  7274. EXPECT_TRUE(res->body.empty());
  7275. }
  7276. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7277. TestContentReceiverDownloadProgress(
  7278. [](Server &svr) {
  7279. svr.Get("/download-receiver",
  7280. [](const Request & /*req*/, Response &res) {
  7281. string content(2000, 'R');
  7282. res.set_content(content, "text/plain");
  7283. });
  7284. },
  7285. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7286. DownloadProgress progress_callback) {
  7287. return cli.Get(endpoint, content_receiver, progress_callback);
  7288. },
  7289. "/download-receiver", 2000u);
  7290. }
  7291. TEST(StreamingTest, NoContentLengthStreaming) {
  7292. Server svr;
  7293. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7294. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7295. if (offset < 6) {
  7296. sink.os << (offset < 3 ? "a" : "b");
  7297. } else {
  7298. sink.done();
  7299. }
  7300. return true;
  7301. });
  7302. });
  7303. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7304. auto listen_se = detail::scope_exit([&] {
  7305. svr.stop();
  7306. listen_thread.join();
  7307. ASSERT_FALSE(svr.is_running());
  7308. });
  7309. svr.wait_until_ready();
  7310. Client client(HOST, PORT);
  7311. auto get_thread = std::thread([&client]() {
  7312. std::string s;
  7313. auto res =
  7314. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7315. s += std::string(data, len);
  7316. return true;
  7317. });
  7318. ASSERT_TRUE(res);
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. EXPECT_EQ("aaabbb", s);
  7321. });
  7322. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7323. // Give GET time to get a few messages.
  7324. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7325. }
  7326. TEST(MountTest, Unmount) {
  7327. Server svr;
  7328. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7329. auto se = detail::scope_exit([&] {
  7330. svr.stop();
  7331. listen_thread.join();
  7332. ASSERT_FALSE(svr.is_running());
  7333. });
  7334. svr.wait_until_ready();
  7335. Client cli("localhost", PORT);
  7336. svr.set_mount_point("/mount2", "./www2");
  7337. auto res = cli.Get("/");
  7338. ASSERT_TRUE(res);
  7339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7340. res = cli.Get("/mount2/dir/test.html");
  7341. ASSERT_TRUE(res);
  7342. EXPECT_EQ(StatusCode::OK_200, res->status);
  7343. svr.set_mount_point("/", "./www");
  7344. res = cli.Get("/dir/");
  7345. ASSERT_TRUE(res);
  7346. EXPECT_EQ(StatusCode::OK_200, res->status);
  7347. svr.remove_mount_point("/");
  7348. res = cli.Get("/dir/");
  7349. ASSERT_TRUE(res);
  7350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7351. svr.remove_mount_point("/mount2");
  7352. res = cli.Get("/mount2/dir/test.html");
  7353. ASSERT_TRUE(res);
  7354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7355. }
  7356. TEST(MountTest, Redicect) {
  7357. Server svr;
  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.set_mount_point("/", "./www");
  7365. svr.wait_until_ready();
  7366. Client cli("localhost", PORT);
  7367. auto res = cli.Get("/dir/");
  7368. ASSERT_TRUE(res);
  7369. EXPECT_EQ(StatusCode::OK_200, res->status);
  7370. res = cli.Get("/dir");
  7371. ASSERT_TRUE(res);
  7372. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7373. res = cli.Get("/file");
  7374. ASSERT_TRUE(res);
  7375. EXPECT_EQ(StatusCode::OK_200, res->status);
  7376. res = cli.Get("/file/");
  7377. ASSERT_TRUE(res);
  7378. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7379. cli.set_follow_location(true);
  7380. res = cli.Get("/dir");
  7381. ASSERT_TRUE(res);
  7382. EXPECT_EQ(StatusCode::OK_200, res->status);
  7383. }
  7384. TEST(MountTest, MultibytesPathName) {
  7385. Server svr;
  7386. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7387. auto se = detail::scope_exit([&] {
  7388. svr.stop();
  7389. listen_thread.join();
  7390. ASSERT_FALSE(svr.is_running());
  7391. });
  7392. svr.set_mount_point("/", "./www");
  7393. svr.wait_until_ready();
  7394. Client cli("localhost", PORT);
  7395. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7396. ASSERT_TRUE(res);
  7397. EXPECT_EQ(StatusCode::OK_200, res->status);
  7398. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7399. }
  7400. #ifdef _WIN32
  7401. // Issue #2435: mmap::open() must succeed even when another handle holds
  7402. // the file open for writing (e.g. an active log file).
  7403. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7404. const char *path = "mmap_concurrent_writer_test.txt";
  7405. const char *content = "hello";
  7406. {
  7407. std::ofstream f(path, std::ios::binary);
  7408. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7409. }
  7410. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7411. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7412. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7413. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7414. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7415. detail::mmap m(path);
  7416. ASSERT_TRUE(m.is_open());
  7417. EXPECT_EQ(strlen(content), m.size());
  7418. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7419. }
  7420. #endif
  7421. TEST(KeepAliveTest, ReadTimeout) {
  7422. Server svr;
  7423. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7424. std::this_thread::sleep_for(std::chrono::seconds(2));
  7425. res.set_content("a", "text/plain");
  7426. });
  7427. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7428. res.set_content("b", "text/plain");
  7429. });
  7430. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7431. auto se = detail::scope_exit([&] {
  7432. svr.stop();
  7433. listen_thread.join();
  7434. ASSERT_FALSE(svr.is_running());
  7435. });
  7436. svr.wait_until_ready();
  7437. Client cli("localhost", PORT);
  7438. cli.set_keep_alive(true);
  7439. cli.set_read_timeout(std::chrono::seconds(1));
  7440. auto resa = cli.Get("/a");
  7441. ASSERT_FALSE(resa);
  7442. EXPECT_EQ(Error::Read, resa.error());
  7443. auto resb = cli.Get("/b");
  7444. ASSERT_TRUE(resb);
  7445. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7446. EXPECT_EQ("b", resb->body);
  7447. }
  7448. TEST(KeepAliveTest, MaxCount) {
  7449. size_t keep_alive_max_count = 3;
  7450. Server svr;
  7451. svr.set_keep_alive_max_count(keep_alive_max_count);
  7452. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7453. res.set_content("Hello World!", "text/plain");
  7454. });
  7455. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7456. auto se = detail::scope_exit([&] {
  7457. svr.stop();
  7458. listen_thread.join();
  7459. ASSERT_FALSE(svr.is_running());
  7460. });
  7461. svr.wait_until_ready();
  7462. Client cli(HOST, PORT);
  7463. cli.set_keep_alive(true);
  7464. for (size_t i = 0; i < 5; i++) {
  7465. auto result = cli.Get("/hi");
  7466. ASSERT_TRUE(result);
  7467. EXPECT_EQ(StatusCode::OK_200, result->status);
  7468. if (i == keep_alive_max_count - 1) {
  7469. EXPECT_EQ("close", result->get_header_value("Connection"));
  7470. } else {
  7471. EXPECT_FALSE(result->has_header("Connection"));
  7472. }
  7473. }
  7474. }
  7475. TEST(KeepAliveTest, Issue1041) {
  7476. Server svr;
  7477. svr.set_keep_alive_timeout(3);
  7478. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7479. res.set_content("Hello World!", "text/plain");
  7480. });
  7481. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7482. auto se = detail::scope_exit([&] {
  7483. svr.stop();
  7484. listen_thread.join();
  7485. ASSERT_FALSE(svr.is_running());
  7486. });
  7487. svr.wait_until_ready();
  7488. Client cli(HOST, PORT);
  7489. cli.set_keep_alive(true);
  7490. auto result = cli.Get("/hi");
  7491. ASSERT_TRUE(result);
  7492. EXPECT_EQ(StatusCode::OK_200, result->status);
  7493. std::this_thread::sleep_for(std::chrono::seconds(5));
  7494. result = cli.Get("/hi");
  7495. ASSERT_TRUE(result);
  7496. EXPECT_EQ(StatusCode::OK_200, result->status);
  7497. }
  7498. TEST(KeepAliveTest, Issue1959) {
  7499. Server svr;
  7500. svr.set_keep_alive_timeout(5);
  7501. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7502. res.set_content("a", "text/plain");
  7503. });
  7504. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7505. auto se = detail::scope_exit([&] {
  7506. if (!svr.is_running()) return;
  7507. svr.stop();
  7508. listen_thread.join();
  7509. ASSERT_FALSE(svr.is_running());
  7510. });
  7511. svr.wait_until_ready();
  7512. Client cli("localhost", PORT);
  7513. cli.set_keep_alive(true);
  7514. using namespace std::chrono;
  7515. auto start = steady_clock::now();
  7516. cli.Get("/a");
  7517. svr.stop();
  7518. listen_thread.join();
  7519. auto end = steady_clock::now();
  7520. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7521. EXPECT_LT(elapsed, 5000);
  7522. }
  7523. #ifdef CPPHTTPLIB_SSL_ENABLED
  7524. TEST(KeepAliveTest, SSLClientReconnection) {
  7525. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7526. ASSERT_TRUE(svr.is_valid());
  7527. svr.set_keep_alive_timeout(1);
  7528. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7529. res.set_content("Hello World!", "text/plain");
  7530. });
  7531. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7532. auto se = detail::scope_exit([&] {
  7533. svr.stop();
  7534. listen_thread.join();
  7535. ASSERT_FALSE(svr.is_running());
  7536. });
  7537. svr.wait_until_ready();
  7538. SSLClient cli(HOST, PORT);
  7539. cli.enable_server_certificate_verification(false);
  7540. cli.set_keep_alive(true);
  7541. auto result = cli.Get("/hi");
  7542. ASSERT_TRUE(result);
  7543. EXPECT_EQ(StatusCode::OK_200, result->status);
  7544. result = cli.Get("/hi");
  7545. ASSERT_TRUE(result);
  7546. EXPECT_EQ(StatusCode::OK_200, result->status);
  7547. std::this_thread::sleep_for(std::chrono::seconds(2));
  7548. // Recoonect
  7549. result = cli.Get("/hi");
  7550. ASSERT_TRUE(result);
  7551. EXPECT_EQ(StatusCode::OK_200, result->status);
  7552. result = cli.Get("/hi");
  7553. ASSERT_TRUE(result);
  7554. EXPECT_EQ(StatusCode::OK_200, result->status);
  7555. }
  7556. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7558. ASSERT_TRUE(svr.is_valid());
  7559. svr.set_keep_alive_timeout(1);
  7560. std::string content = "reconnect";
  7561. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7562. res.set_content("Hello World!", "text/plain");
  7563. });
  7564. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7565. auto se = detail::scope_exit([&] {
  7566. svr.stop();
  7567. listen_thread.join();
  7568. ASSERT_FALSE(svr.is_running());
  7569. });
  7570. svr.wait_until_ready();
  7571. SSLClient cli(HOST, PORT);
  7572. cli.enable_server_certificate_verification(false);
  7573. cli.set_keep_alive(true);
  7574. auto result = cli.Post(
  7575. "/hi", content.size(),
  7576. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7577. sink.write(content.c_str(), content.size());
  7578. return true;
  7579. },
  7580. "text/plain");
  7581. ASSERT_TRUE(result);
  7582. EXPECT_EQ(200, result->status);
  7583. std::this_thread::sleep_for(std::chrono::seconds(2));
  7584. // Recoonect
  7585. result = cli.Post(
  7586. "/hi", content.size(),
  7587. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7588. sink.write(content.c_str(), content.size());
  7589. return true;
  7590. },
  7591. "text/plain");
  7592. ASSERT_TRUE(result);
  7593. EXPECT_EQ(200, result->status);
  7594. result = cli.Post(
  7595. "/hi", content.size(),
  7596. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7597. sink.write(content.c_str(), content.size());
  7598. return true;
  7599. },
  7600. "text/plain");
  7601. ASSERT_TRUE(result);
  7602. EXPECT_EQ(200, result->status);
  7603. }
  7604. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7605. using namespace httplib::tls;
  7606. {
  7607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7608. ASSERT_TRUE(svr.is_valid());
  7609. svr.Get("/sni", [&](const Request &req, Response &res) {
  7610. std::string expected = req.sni();
  7611. EXPECT_EQ(expected, req.get_param_value("expected"));
  7612. res.set_content("ok", "text/plain");
  7613. });
  7614. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7615. auto se = detail::scope_exit([&] {
  7616. svr.stop();
  7617. listen_thread.join();
  7618. ASSERT_FALSE(svr.is_running());
  7619. });
  7620. svr.wait_until_ready();
  7621. {
  7622. SSLClient cli("localhost", PORT);
  7623. cli.enable_server_certificate_verification(false);
  7624. auto res = cli.Get("/sni?expected=localhost");
  7625. ASSERT_TRUE(res);
  7626. }
  7627. {
  7628. SSLClient cli("::1", PORT);
  7629. cli.enable_server_certificate_verification(false);
  7630. auto res = cli.Get("/sni?expected=");
  7631. // NOTE: This may fail if the server is listening on IPv4 only
  7632. // (e.g., when localhost resolves to 127.0.0.1 only)
  7633. if (res) {
  7634. EXPECT_EQ(StatusCode::OK_200, res->status);
  7635. } else {
  7636. EXPECT_EQ(Error::Connection, res.error());
  7637. }
  7638. }
  7639. }
  7640. }
  7641. #endif
  7642. TEST(ClientProblemDetectionTest, ContentProvider) {
  7643. Server svr;
  7644. size_t content_length = 1024 * 1024;
  7645. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7646. res.set_content_provider(
  7647. content_length, "text/plain",
  7648. [&](size_t offset, size_t length, DataSink &sink) {
  7649. auto out_len = std::min(length, static_cast<size_t>(1024));
  7650. std::string out(out_len, '@');
  7651. sink.write(out.data(), out_len);
  7652. return offset < 4096;
  7653. },
  7654. [](bool success) { ASSERT_FALSE(success); });
  7655. });
  7656. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7657. res.set_content_provider(
  7658. 0, "text/plain",
  7659. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7660. EXPECT_TRUE(false);
  7661. return true;
  7662. },
  7663. [](bool success) { ASSERT_FALSE(success); });
  7664. });
  7665. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7666. auto se = detail::scope_exit([&] {
  7667. svr.stop();
  7668. listen_thread.join();
  7669. ASSERT_FALSE(svr.is_running());
  7670. });
  7671. svr.wait_until_ready();
  7672. Client cli("localhost", PORT);
  7673. {
  7674. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7675. size_t /*data_length*/) { return false; });
  7676. ASSERT_FALSE(res);
  7677. }
  7678. {
  7679. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7680. size_t /*data_length*/) { return false; });
  7681. ASSERT_TRUE(res);
  7682. }
  7683. }
  7684. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7685. Server svr;
  7686. svr.set_error_handler([](Request const &, Response &res) -> void {
  7687. res.set_chunked_content_provider(
  7688. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7689. sink.os << "hello";
  7690. sink.os << "world";
  7691. sink.done();
  7692. return true;
  7693. });
  7694. });
  7695. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7696. auto se = detail::scope_exit([&] {
  7697. svr.stop();
  7698. listen_thread.join();
  7699. ASSERT_FALSE(svr.is_running());
  7700. });
  7701. svr.wait_until_ready();
  7702. Client cli("localhost", PORT);
  7703. auto res = cli.Get("/");
  7704. ASSERT_TRUE(res);
  7705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7706. EXPECT_EQ("helloworld", res->body);
  7707. }
  7708. TEST(LongPollingTest, ClientCloseDetection) {
  7709. Server svr;
  7710. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7711. res.set_chunked_content_provider(
  7712. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7713. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7714. sink.os << "hello";
  7715. auto count = 10;
  7716. while (count > 0 && sink.is_writable()) {
  7717. this_thread::sleep_for(chrono::milliseconds(10));
  7718. count--;
  7719. }
  7720. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7721. return true;
  7722. });
  7723. });
  7724. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7725. auto se = detail::scope_exit([&] {
  7726. svr.stop();
  7727. listen_thread.join();
  7728. ASSERT_FALSE(svr.is_running());
  7729. });
  7730. svr.wait_until_ready();
  7731. Client cli("localhost", PORT);
  7732. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7733. EXPECT_EQ("hello", string(data, data_length));
  7734. return false; // close the socket immediately.
  7735. });
  7736. ASSERT_FALSE(res);
  7737. }
  7738. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7739. Server svr;
  7740. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7741. res.set_chunked_content_provider(
  7742. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7743. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7744. sink.os << "hello";
  7745. EXPECT_TRUE(sink.os.good());
  7746. // Wait for the client to close the connection
  7747. auto count = 10;
  7748. while (count > 0 && sink.is_writable()) {
  7749. this_thread::sleep_for(chrono::milliseconds(10));
  7750. count--;
  7751. }
  7752. // After client disconnect, write repeatedly until the socket
  7753. // write actually fails (small writes may be absorbed by the
  7754. // kernel buffer)
  7755. std::string chunk(1024, 'x');
  7756. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7757. sink.os << chunk;
  7758. }
  7759. EXPECT_TRUE(sink.os.fail());
  7760. return true;
  7761. });
  7762. });
  7763. auto port = svr.bind_to_any_port("localhost");
  7764. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7765. auto se = detail::scope_exit([&] {
  7766. svr.stop();
  7767. listen_thread.join();
  7768. ASSERT_FALSE(svr.is_running());
  7769. });
  7770. svr.wait_until_ready();
  7771. Client cli("localhost", port);
  7772. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7773. EXPECT_EQ("hello", string(data, data_length));
  7774. return false; // close the socket immediately.
  7775. });
  7776. ASSERT_FALSE(res);
  7777. }
  7778. TEST(GetWithParametersTest, GetWithParameters) {
  7779. Server svr;
  7780. svr.Get("/", [&](const Request &req, Response &) {
  7781. EXPECT_EQ("world", req.get_param_value("hello"));
  7782. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7783. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7784. });
  7785. svr.Get("/params", [&](const Request &req, Response &) {
  7786. EXPECT_EQ("world", req.get_param_value("hello"));
  7787. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7788. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7789. });
  7790. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7791. EXPECT_EQ("resource-id", req.matches[1]);
  7792. EXPECT_EQ("foo", req.get_param_value("param1"));
  7793. EXPECT_EQ("bar", req.get_param_value("param2"));
  7794. });
  7795. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7796. EXPECT_EQ("user-id", req.path_params.at("id"));
  7797. EXPECT_EQ("foo", req.get_param_value("param1"));
  7798. EXPECT_EQ("bar", req.get_param_value("param2"));
  7799. });
  7800. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7801. auto se = detail::scope_exit([&] {
  7802. svr.stop();
  7803. listen_thread.join();
  7804. ASSERT_FALSE(svr.is_running());
  7805. });
  7806. svr.wait_until_ready();
  7807. {
  7808. Client cli(HOST, PORT);
  7809. Params params;
  7810. params.emplace("hello", "world");
  7811. params.emplace("hello2", "world2");
  7812. params.emplace("hello3", "world3");
  7813. auto res = cli.Get("/", params, Headers{});
  7814. ASSERT_TRUE(res);
  7815. EXPECT_EQ(StatusCode::OK_200, res->status);
  7816. }
  7817. {
  7818. Client cli(HOST, PORT);
  7819. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7820. ASSERT_TRUE(res);
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. }
  7823. {
  7824. Client cli(HOST, PORT);
  7825. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7826. ASSERT_TRUE(res);
  7827. EXPECT_EQ(StatusCode::OK_200, res->status);
  7828. }
  7829. {
  7830. Client cli(HOST, PORT);
  7831. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7832. ASSERT_TRUE(res);
  7833. EXPECT_EQ(StatusCode::OK_200, res->status);
  7834. }
  7835. }
  7836. TEST(GetWithParametersTest, GetWithParameters2) {
  7837. Server svr;
  7838. svr.Get("/", [&](const Request &req, Response &res) {
  7839. auto text = req.get_param_value("hello");
  7840. res.set_content(text, "text/plain");
  7841. });
  7842. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7843. auto se = detail::scope_exit([&] {
  7844. svr.stop();
  7845. listen_thread.join();
  7846. ASSERT_FALSE(svr.is_running());
  7847. });
  7848. svr.wait_until_ready();
  7849. Client cli("localhost", PORT);
  7850. Params params;
  7851. params.emplace("hello", "world");
  7852. std::string body;
  7853. auto res = cli.Get("/", params, Headers{},
  7854. [&](const char *data, size_t data_length) {
  7855. body.append(data, data_length);
  7856. return true;
  7857. });
  7858. ASSERT_TRUE(res);
  7859. EXPECT_EQ(StatusCode::OK_200, res->status);
  7860. EXPECT_EQ("world", body);
  7861. }
  7862. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7863. Server svr;
  7864. svr.Get("/search", [&](const Request &req, Response &res) {
  7865. auto q = req.get_param_value("q");
  7866. res.set_content(q, "text/plain");
  7867. });
  7868. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7869. auto se = detail::scope_exit([&] {
  7870. svr.stop();
  7871. listen_thread.join();
  7872. ASSERT_FALSE(svr.is_running());
  7873. });
  7874. svr.wait_until_ready();
  7875. Client cli("localhost", PORT);
  7876. // Verify that Get(path, params) works without requiring Headers argument
  7877. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7878. ASSERT_TRUE(res);
  7879. EXPECT_EQ(StatusCode::OK_200, res->status);
  7880. EXPECT_EQ("cpp-httplib", res->body);
  7881. }
  7882. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7883. auto host = "httpbingo.org";
  7884. auto path = std::string{"/range/32"};
  7885. #ifdef CPPHTTPLIB_SSL_ENABLED
  7886. SSLClient cli(host);
  7887. #else
  7888. Client cli(host);
  7889. #endif
  7890. cli.set_default_headers({make_range_header({{1, 10}})});
  7891. cli.set_connection_timeout(5);
  7892. {
  7893. auto res = cli.Get(path);
  7894. ASSERT_TRUE(res);
  7895. EXPECT_EQ("bcdefghijk", res->body);
  7896. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7897. }
  7898. {
  7899. auto res = cli.Get(path);
  7900. ASSERT_TRUE(res);
  7901. EXPECT_EQ("bcdefghijk", res->body);
  7902. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7903. }
  7904. }
  7905. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7906. Server svr;
  7907. svr.set_default_headers({{"Hello", "World"}});
  7908. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7909. res.set_content("ok", "text/plain");
  7910. });
  7911. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7912. auto se = detail::scope_exit([&] {
  7913. svr.stop();
  7914. listen_thread.join();
  7915. ASSERT_FALSE(svr.is_running());
  7916. });
  7917. svr.wait_until_ready();
  7918. Client cli("localhost", PORT);
  7919. auto res = cli.Get("/");
  7920. ASSERT_TRUE(res);
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. EXPECT_EQ("ok", res->body);
  7923. EXPECT_EQ("World", res->get_header_value("Hello"));
  7924. }
  7925. #ifdef CPPHTTPLIB_SSL_ENABLED
  7926. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7928. ASSERT_TRUE(svr.is_valid());
  7929. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7930. std::this_thread::sleep_for(std::chrono::seconds(2));
  7931. res.set_content("a", "text/plain");
  7932. });
  7933. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7934. res.set_content("b", "text/plain");
  7935. });
  7936. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7937. auto se = detail::scope_exit([&] {
  7938. svr.stop();
  7939. listen_thread.join();
  7940. ASSERT_FALSE(svr.is_running());
  7941. });
  7942. svr.wait_until_ready();
  7943. SSLClient cli("localhost", PORT);
  7944. cli.enable_server_certificate_verification(false);
  7945. cli.set_keep_alive(true);
  7946. cli.set_read_timeout(std::chrono::seconds(1));
  7947. auto resa = cli.Get("/a");
  7948. ASSERT_TRUE(!resa);
  7949. EXPECT_EQ(Error::Read, resa.error());
  7950. auto resb = cli.Get("/b");
  7951. ASSERT_TRUE(resb);
  7952. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7953. EXPECT_EQ("b", resb->body);
  7954. }
  7955. #endif
  7956. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7957. protected:
  7958. ServerTestWithAI_PASSIVE()
  7959. : cli_(HOST, PORT)
  7960. #ifdef CPPHTTPLIB_SSL_ENABLED
  7961. ,
  7962. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7963. #endif
  7964. {
  7965. #ifdef CPPHTTPLIB_SSL_ENABLED
  7966. cli_.enable_server_certificate_verification(false);
  7967. #endif
  7968. }
  7969. virtual void SetUp() {
  7970. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7971. res.set_content("Hello World!", "text/plain");
  7972. });
  7973. t_ = thread(
  7974. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7975. svr_.wait_until_ready();
  7976. }
  7977. virtual void TearDown() {
  7978. svr_.stop();
  7979. t_.join();
  7980. }
  7981. #ifdef CPPHTTPLIB_SSL_ENABLED
  7982. SSLClient cli_;
  7983. SSLServer svr_;
  7984. #else
  7985. Client cli_;
  7986. Server svr_;
  7987. #endif
  7988. thread t_;
  7989. };
  7990. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7991. auto res = cli_.Get("/hi");
  7992. ASSERT_TRUE(res);
  7993. EXPECT_EQ(StatusCode::OK_200, res->status);
  7994. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7995. EXPECT_EQ("Hello World!", res->body);
  7996. }
  7997. class ServerUpDownTest : public ::testing::Test {
  7998. protected:
  7999. ServerUpDownTest() : cli_(HOST, PORT) {}
  8000. virtual void SetUp() {
  8001. t_ = thread([&]() {
  8002. svr_.bind_to_any_port(HOST);
  8003. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8004. ASSERT_TRUE(svr_.listen_after_bind());
  8005. });
  8006. svr_.wait_until_ready();
  8007. }
  8008. virtual void TearDown() {
  8009. svr_.stop();
  8010. t_.join();
  8011. }
  8012. Client cli_;
  8013. Server svr_;
  8014. thread t_;
  8015. };
  8016. TEST_F(ServerUpDownTest, QuickStartStop) {
  8017. // Should not crash, especially when run with
  8018. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8019. }
  8020. class PayloadMaxLengthTest : public ::testing::Test {
  8021. protected:
  8022. PayloadMaxLengthTest()
  8023. : cli_(HOST, PORT)
  8024. #ifdef CPPHTTPLIB_SSL_ENABLED
  8025. ,
  8026. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8027. #endif
  8028. {
  8029. #ifdef CPPHTTPLIB_SSL_ENABLED
  8030. cli_.enable_server_certificate_verification(false);
  8031. #endif
  8032. }
  8033. virtual void SetUp() {
  8034. svr_.set_payload_max_length(8);
  8035. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8036. res.set_content("test", "text/plain");
  8037. });
  8038. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8039. svr_.wait_until_ready();
  8040. }
  8041. virtual void TearDown() {
  8042. svr_.stop();
  8043. t_.join();
  8044. }
  8045. #ifdef CPPHTTPLIB_SSL_ENABLED
  8046. SSLClient cli_;
  8047. SSLServer svr_;
  8048. #else
  8049. Client cli_;
  8050. Server svr_;
  8051. #endif
  8052. thread t_;
  8053. };
  8054. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8055. auto res = cli_.Post("/test", "123456789", "text/plain");
  8056. ASSERT_TRUE(res);
  8057. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8058. res = cli_.Post("/test", "12345678", "text/plain");
  8059. ASSERT_TRUE(res);
  8060. EXPECT_EQ(StatusCode::OK_200, res->status);
  8061. }
  8062. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8063. // Test chunked encoding with payload exceeding the 8-byte limit
  8064. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8065. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8066. ASSERT_TRUE(res);
  8067. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8068. }
  8069. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8070. // Test chunked encoding with payload within the 8-byte limit
  8071. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8072. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8073. ASSERT_TRUE(res);
  8074. EXPECT_EQ(StatusCode::OK_200, res->status);
  8075. }
  8076. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8077. // Test using send_request to send chunked data exceeding payload limit
  8078. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8079. "Host: " +
  8080. std::string(HOST) + ":" + std::to_string(PORT) +
  8081. "\r\n"
  8082. "Transfer-Encoding: chunked\r\n"
  8083. "Connection: close\r\n"
  8084. "\r\n"
  8085. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8086. "0123456789\r\n"
  8087. "0\r\n" // End chunk
  8088. "\r\n";
  8089. std::string response;
  8090. bool result = send_request(1, chunked_request, &response);
  8091. if (!result) {
  8092. // If send_request fails, it might be because the server closed the
  8093. // connection due to payload limit enforcement, which is acceptable
  8094. SUCCEED()
  8095. << "Server rejected oversized chunked request (connection closed)";
  8096. } else {
  8097. // If we got a response, check if it's an error response or connection was
  8098. // closed early Short response length indicates connection was closed due to
  8099. // payload limit
  8100. if (response.length() <= 10) {
  8101. SUCCEED() << "Server closed connection for oversized chunked request";
  8102. } else {
  8103. // Check for error status codes
  8104. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8105. response.find("Payload Too Large") != std::string::npos ||
  8106. response.find("400") != std::string::npos);
  8107. }
  8108. }
  8109. }
  8110. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8111. // Test request without Content-Length header exceeding payload limit
  8112. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8113. "Host: " +
  8114. std::string(HOST) + ":" +
  8115. std::to_string(PORT) +
  8116. "\r\n"
  8117. "Connection: close\r\n"
  8118. "\r\n";
  8119. // Add payload exceeding the 8-byte limit
  8120. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8121. request_without_content_length += large_payload;
  8122. std::string response;
  8123. bool result = send_request(1, request_without_content_length, &response);
  8124. if (!result) {
  8125. // If send_request fails, server likely closed connection due to payload
  8126. // limit
  8127. SUCCEED() << "Server rejected oversized request without Content-Length "
  8128. "(connection closed)";
  8129. } else {
  8130. // Check if server responded with error or closed connection early
  8131. if (response.length() <= 10) {
  8132. SUCCEED() << "Server closed connection for oversized request without "
  8133. "Content-Length";
  8134. } else {
  8135. // Check for error status codes
  8136. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8137. response.find("Payload Too Large") != std::string::npos ||
  8138. response.find("400") != std::string::npos);
  8139. }
  8140. }
  8141. }
  8142. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8143. // Test request without Content-Length header within payload limit
  8144. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8145. "Host: " +
  8146. std::string(HOST) + ":" +
  8147. std::to_string(PORT) +
  8148. "\r\n"
  8149. "Connection: close\r\n"
  8150. "\r\n";
  8151. // Add payload within the 8-byte limit
  8152. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8153. request_without_content_length += small_payload;
  8154. std::string response;
  8155. bool result = send_request(1, request_without_content_length, &response);
  8156. // For requests without Content-Length, the server may have different behavior
  8157. // The key is that it should not reject due to payload limit for small
  8158. // payloads
  8159. if (result) {
  8160. // Check for any HTTP response (success or error, but not connection closed)
  8161. if (response.length() > 10) {
  8162. SUCCEED()
  8163. << "Server processed request without Content-Length within limit";
  8164. } else {
  8165. // Short response might indicate connection closed, which is acceptable
  8166. SUCCEED() << "Server closed connection for request without "
  8167. "Content-Length (acceptable behavior)";
  8168. }
  8169. } else {
  8170. // Connection failure might be due to protocol requirements
  8171. SUCCEED() << "Connection issue with request without Content-Length "
  8172. "(environment-specific)";
  8173. }
  8174. }
  8175. class LargePayloadMaxLengthTest : public ::testing::Test {
  8176. protected:
  8177. LargePayloadMaxLengthTest()
  8178. : cli_(HOST, PORT)
  8179. #ifdef CPPHTTPLIB_SSL_ENABLED
  8180. ,
  8181. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8182. #endif
  8183. {
  8184. #ifdef CPPHTTPLIB_SSL_ENABLED
  8185. cli_.enable_server_certificate_verification(false);
  8186. #endif
  8187. }
  8188. virtual void SetUp() {
  8189. // Set 10MB payload limit
  8190. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8191. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8192. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8193. res.set_content("Large payload test", "text/plain");
  8194. });
  8195. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8196. svr_.wait_until_ready();
  8197. }
  8198. virtual void TearDown() {
  8199. svr_.stop();
  8200. t_.join();
  8201. }
  8202. #ifdef CPPHTTPLIB_SSL_ENABLED
  8203. SSLClient cli_;
  8204. SSLServer svr_;
  8205. #else
  8206. Client cli_;
  8207. Server svr_;
  8208. #endif
  8209. thread t_;
  8210. };
  8211. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8212. // Test chunked encoding with payload within 10MB limit
  8213. std::string medium_payload(5 * 1024 * 1024,
  8214. 'A'); // 5MB payload, within 10MB limit
  8215. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8216. ASSERT_TRUE(res);
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. }
  8219. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8220. // Test chunked encoding with payload exceeding 10MB limit
  8221. std::string large_payload(12 * 1024 * 1024,
  8222. 'B'); // 12MB payload, exceeds 10MB limit
  8223. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8224. // Server may either return 413 or close the connection
  8225. if (res) {
  8226. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8227. } else {
  8228. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8229. }
  8230. }
  8231. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8232. // Test request without Content-Length header within 10MB limit
  8233. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8234. "Host: " +
  8235. std::string(HOST) + ":" +
  8236. std::to_string(PORT) +
  8237. "\r\n"
  8238. "Connection: close\r\n"
  8239. "\r\n";
  8240. // Add 1MB payload (within 10MB limit)
  8241. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8242. request_without_content_length += medium_payload;
  8243. std::string response;
  8244. bool result = send_request(5, request_without_content_length, &response);
  8245. if (result) {
  8246. // Should get a proper HTTP response for payloads within limit
  8247. if (response.length() > 10) {
  8248. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8249. "10MB limit";
  8250. } else {
  8251. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8252. "Content-Length)";
  8253. }
  8254. } else {
  8255. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8256. }
  8257. }
  8258. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8259. // Test request without Content-Length header exceeding 10MB limit
  8260. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8261. "Host: " +
  8262. std::string(HOST) + ":" +
  8263. std::to_string(PORT) +
  8264. "\r\n"
  8265. "Connection: close\r\n"
  8266. "\r\n";
  8267. // Add 12MB payload (exceeds 10MB limit)
  8268. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8269. request_without_content_length += large_payload;
  8270. std::string response;
  8271. bool result = send_request(10, request_without_content_length, &response);
  8272. if (!result) {
  8273. // Server should close connection due to payload limit
  8274. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8275. "(connection closed)";
  8276. } else {
  8277. // Check for error response
  8278. if (response.length() <= 10) {
  8279. SUCCEED()
  8280. << "Server closed connection for 12MB request exceeding 10MB limit";
  8281. } else {
  8282. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8283. response.find("Payload Too Large") != std::string::npos ||
  8284. response.find("400") != std::string::npos);
  8285. }
  8286. }
  8287. }
  8288. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8289. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8290. // path.
  8291. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8292. Server svr;
  8293. const size_t LIMIT = 64 * 1024; // 64KB
  8294. svr.set_payload_max_length(LIMIT);
  8295. size_t total = 0;
  8296. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8297. const ContentReader &content_reader) {
  8298. content_reader([&](const char * /*data*/, size_t len) {
  8299. total += len;
  8300. return true;
  8301. });
  8302. res.status = 200;
  8303. res.set_content("stream_ok", "text/plain");
  8304. });
  8305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8306. auto se = detail::scope_exit([&] {
  8307. svr.stop();
  8308. thread.join();
  8309. ASSERT_FALSE(svr.is_running());
  8310. });
  8311. svr.wait_until_ready();
  8312. // Prepare 256KB raw data and gzip-compress it
  8313. std::string raw(256 * 1024, 'A');
  8314. std::string gz;
  8315. {
  8316. z_stream zs{};
  8317. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8318. Z_DEFAULT_STRATEGY);
  8319. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8320. zs.avail_in = static_cast<uInt>(raw.size());
  8321. char outbuf[4096];
  8322. int ret;
  8323. do {
  8324. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8325. zs.avail_out = sizeof(outbuf);
  8326. ret = deflate(&zs, Z_FINISH);
  8327. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8328. } while (ret != Z_STREAM_END);
  8329. deflateEnd(&zs);
  8330. }
  8331. Client cli(HOST, PORT);
  8332. cli.set_connection_timeout(std::chrono::seconds(5));
  8333. Headers headers = {{"Content-Encoding", "gzip"}};
  8334. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8335. "application/octet-stream");
  8336. ASSERT_TRUE(res);
  8337. // Server must reject oversized decompressed payloads with 413.
  8338. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8339. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8340. EXPECT_LE(total, LIMIT);
  8341. }
  8342. #endif
  8343. // Regression test for DoS vulnerability: a malicious server sending a response
  8344. // without Content-Length header must not cause unbounded memory consumption on
  8345. // the client side. The client should stop reading after a reasonable limit,
  8346. // similar to the server-side set_payload_max_length protection.
  8347. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8348. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8349. #ifndef _WIN32
  8350. signal(SIGPIPE, SIG_IGN);
  8351. #endif
  8352. auto server_thread = std::thread([] {
  8353. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8354. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8355. default_socket_options(srv);
  8356. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8357. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8358. sockaddr_in addr{};
  8359. addr.sin_family = AF_INET;
  8360. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8361. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8362. int opt = 1;
  8363. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8364. #ifdef _WIN32
  8365. reinterpret_cast<const char *>(&opt),
  8366. #else
  8367. &opt,
  8368. #endif
  8369. sizeof(opt));
  8370. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8371. ::listen(srv, 1);
  8372. sockaddr_in cli_addr{};
  8373. socklen_t cli_len = sizeof(cli_addr);
  8374. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8375. if (cli != INVALID_SOCKET) {
  8376. char buf[4096];
  8377. ::recv(cli, buf, sizeof(buf), 0);
  8378. // Malicious response: no Content-Length, no chunked encoding
  8379. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8380. "Connection: close\r\n"
  8381. "\r\n";
  8382. ::send(cli,
  8383. #ifdef _WIN32
  8384. static_cast<const char *>(response_header.c_str()),
  8385. static_cast<int>(response_header.size()),
  8386. #else
  8387. response_header.c_str(), response_header.size(),
  8388. #endif
  8389. 0);
  8390. // Send 10MB of data
  8391. std::string chunk(64 * 1024, 'A');
  8392. size_t total_sent = 0;
  8393. while (total_sent < MALICIOUS_DATA_SIZE) {
  8394. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8395. auto sent = ::send(cli,
  8396. #ifdef _WIN32
  8397. static_cast<const char *>(chunk.c_str()),
  8398. static_cast<int>(to_send),
  8399. #else
  8400. chunk.c_str(), to_send,
  8401. #endif
  8402. 0);
  8403. if (sent <= 0) break;
  8404. total_sent += static_cast<size_t>(sent);
  8405. }
  8406. detail::close_socket(cli);
  8407. }
  8408. detail::close_socket(srv);
  8409. });
  8410. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8411. size_t total_read = 0;
  8412. {
  8413. Client cli("127.0.0.1", PORT + 2);
  8414. cli.set_read_timeout(5, 0);
  8415. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8416. auto stream = cli.open_stream("GET", "/malicious");
  8417. ASSERT_TRUE(stream.is_valid());
  8418. char buffer[64 * 1024];
  8419. ssize_t n;
  8420. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8421. total_read += static_cast<size_t>(n);
  8422. }
  8423. } // StreamHandle and Client destroyed here, closing the socket
  8424. server_thread.join();
  8425. // With set_payload_max_length, the client must stop reading before consuming
  8426. // all 10MB. The read loop should be cut off at or near the configured limit.
  8427. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8428. << "Client read " << total_read << " bytes, exceeding the configured "
  8429. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8430. }
  8431. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8432. // the entire response body without truncation.
  8433. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8434. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8435. #ifndef _WIN32
  8436. signal(SIGPIPE, SIG_IGN);
  8437. #endif
  8438. auto server_thread = std::thread([] {
  8439. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8440. default_socket_options(srv);
  8441. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8442. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8443. sockaddr_in addr{};
  8444. addr.sin_family = AF_INET;
  8445. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8446. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8447. int opt = 1;
  8448. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8449. #ifdef _WIN32
  8450. reinterpret_cast<const char *>(&opt),
  8451. #else
  8452. &opt,
  8453. #endif
  8454. sizeof(opt));
  8455. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8456. ::listen(srv, 1);
  8457. sockaddr_in cli_addr{};
  8458. socklen_t cli_len = sizeof(cli_addr);
  8459. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8460. if (cli != INVALID_SOCKET) {
  8461. char buf[4096];
  8462. ::recv(cli, buf, sizeof(buf), 0);
  8463. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8464. "Connection: close\r\n"
  8465. "\r\n";
  8466. ::send(cli,
  8467. #ifdef _WIN32
  8468. static_cast<const char *>(response_header.c_str()),
  8469. static_cast<int>(response_header.size()),
  8470. #else
  8471. response_header.c_str(), response_header.size(),
  8472. #endif
  8473. 0);
  8474. std::string chunk(64 * 1024, 'A');
  8475. size_t total_sent = 0;
  8476. while (total_sent < DATA_SIZE) {
  8477. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8478. auto sent = ::send(cli,
  8479. #ifdef _WIN32
  8480. static_cast<const char *>(chunk.c_str()),
  8481. static_cast<int>(to_send),
  8482. #else
  8483. chunk.c_str(), to_send,
  8484. #endif
  8485. 0);
  8486. if (sent <= 0) break;
  8487. total_sent += static_cast<size_t>(sent);
  8488. }
  8489. #ifdef _WIN32
  8490. ::shutdown(cli, SD_SEND);
  8491. #else
  8492. ::shutdown(cli, SHUT_WR);
  8493. #endif
  8494. // Drain until the client closes its end, ensuring all data is delivered
  8495. char drain[1024];
  8496. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8497. detail::close_socket(cli);
  8498. }
  8499. detail::close_socket(srv);
  8500. });
  8501. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8502. size_t total_read = 0;
  8503. {
  8504. Client cli("127.0.0.1", PORT + 2);
  8505. cli.set_read_timeout(5, 0);
  8506. cli.set_payload_max_length(0); // 0 means no limit
  8507. auto stream = cli.open_stream("GET", "/data");
  8508. ASSERT_TRUE(stream.is_valid());
  8509. char buffer[64 * 1024];
  8510. ssize_t n;
  8511. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8512. total_read += static_cast<size_t>(n);
  8513. }
  8514. }
  8515. server_thread.join();
  8516. EXPECT_EQ(total_read, DATA_SIZE)
  8517. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8518. << " bytes without truncation, but only read " << total_read << " bytes.";
  8519. }
  8520. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8521. // enormous Content-Length must not cause the client to pre-allocate a huge
  8522. // response body buffer. The reservation is capped at payload_max_length_, and
  8523. // the read itself fails when the body exceeds the limit.
  8524. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8525. #ifndef _WIN32
  8526. signal(SIGPIPE, SIG_IGN);
  8527. #endif
  8528. auto server_thread = std::thread([] {
  8529. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8530. default_socket_options(srv);
  8531. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8532. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8533. sockaddr_in addr{};
  8534. addr.sin_family = AF_INET;
  8535. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8536. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8537. int opt = 1;
  8538. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8539. #ifdef _WIN32
  8540. reinterpret_cast<const char *>(&opt),
  8541. #else
  8542. &opt,
  8543. #endif
  8544. sizeof(opt));
  8545. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8546. ::listen(srv, 1);
  8547. sockaddr_in cli_addr{};
  8548. socklen_t cli_len = sizeof(cli_addr);
  8549. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8550. if (cli != INVALID_SOCKET) {
  8551. char buf[4096];
  8552. ::recv(cli, buf, sizeof(buf), 0);
  8553. // Malicious response: claim a 20GB body but send only a tiny payload.
  8554. std::string response = "HTTP/1.1 200 OK\r\n"
  8555. "Content-Length: 20000000000\r\n"
  8556. "\r\n"
  8557. "abc";
  8558. ::send(cli,
  8559. #ifdef _WIN32
  8560. static_cast<const char *>(response.c_str()),
  8561. static_cast<int>(response.size()),
  8562. #else
  8563. response.c_str(), response.size(),
  8564. #endif
  8565. 0);
  8566. detail::close_socket(cli);
  8567. }
  8568. detail::close_socket(srv);
  8569. });
  8570. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8571. {
  8572. Client cli("127.0.0.1", PORT + 2);
  8573. cli.set_read_timeout(5, 0);
  8574. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8575. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8576. // (server claims more bytes than payload_max_length permits), but it must
  8577. // not exhaust memory before getting there.
  8578. auto res = cli.Get("/malicious");
  8579. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8580. }
  8581. server_thread.join();
  8582. }
  8583. // Verify that content_receiver bypasses the default payload_max_length,
  8584. // allowing streaming downloads larger than 100MB without requiring an explicit
  8585. // set_payload_max_length call.
  8586. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8587. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8588. #ifndef _WIN32
  8589. signal(SIGPIPE, SIG_IGN);
  8590. #endif
  8591. auto server_thread = std::thread([] {
  8592. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8593. default_socket_options(srv);
  8594. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8595. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8596. sockaddr_in addr{};
  8597. addr.sin_family = AF_INET;
  8598. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8599. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8600. int opt = 1;
  8601. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8602. #ifdef _WIN32
  8603. reinterpret_cast<const char *>(&opt),
  8604. #else
  8605. &opt,
  8606. #endif
  8607. sizeof(opt));
  8608. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8609. ::listen(srv, 1);
  8610. sockaddr_in cli_addr{};
  8611. socklen_t cli_len = sizeof(cli_addr);
  8612. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8613. if (cli != INVALID_SOCKET) {
  8614. char buf[4096];
  8615. ::recv(cli, buf, sizeof(buf), 0);
  8616. // Response with Content-Length larger than default 100MB limit
  8617. auto content_length = std::to_string(DATA_SIZE);
  8618. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8619. "Content-Length: " +
  8620. content_length +
  8621. "\r\n"
  8622. "Connection: close\r\n"
  8623. "\r\n";
  8624. ::send(cli,
  8625. #ifdef _WIN32
  8626. static_cast<const char *>(response_header.c_str()),
  8627. static_cast<int>(response_header.size()),
  8628. #else
  8629. response_header.c_str(), response_header.size(),
  8630. #endif
  8631. 0);
  8632. std::string chunk(64 * 1024, 'A');
  8633. size_t total_sent = 0;
  8634. while (total_sent < DATA_SIZE) {
  8635. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8636. auto sent = ::send(cli,
  8637. #ifdef _WIN32
  8638. static_cast<const char *>(chunk.c_str()),
  8639. static_cast<int>(to_send),
  8640. #else
  8641. chunk.c_str(), to_send,
  8642. #endif
  8643. 0);
  8644. if (sent <= 0) break;
  8645. total_sent += static_cast<size_t>(sent);
  8646. }
  8647. detail::close_socket(cli);
  8648. }
  8649. detail::close_socket(srv);
  8650. });
  8651. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8652. size_t total_received = 0;
  8653. {
  8654. Client cli("127.0.0.1", PORT + 2);
  8655. cli.set_read_timeout(10, 0);
  8656. // Do NOT call set_payload_max_length — use the default 100MB limit
  8657. auto res =
  8658. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8659. total_received += data_length;
  8660. return true;
  8661. });
  8662. ASSERT_TRUE(res);
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. }
  8665. server_thread.join();
  8666. EXPECT_EQ(total_received, DATA_SIZE)
  8667. << "With content_receiver, the client should read all " << DATA_SIZE
  8668. << " bytes despite the default 100MB payload_max_length, but only read "
  8669. << total_received << " bytes.";
  8670. }
  8671. // Verify that an explicit set_payload_max_length smaller than the response is
  8672. // enforced even when a content_receiver is used.
  8673. TEST(ClientVulnerabilityTest,
  8674. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8675. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8676. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8677. #ifndef _WIN32
  8678. signal(SIGPIPE, SIG_IGN);
  8679. #endif
  8680. auto server_thread = std::thread([] {
  8681. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8682. default_socket_options(srv);
  8683. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8684. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8685. sockaddr_in addr{};
  8686. addr.sin_family = AF_INET;
  8687. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8688. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8689. int opt = 1;
  8690. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8691. #ifdef _WIN32
  8692. reinterpret_cast<const char *>(&opt),
  8693. #else
  8694. &opt,
  8695. #endif
  8696. sizeof(opt));
  8697. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8698. ::listen(srv, 1);
  8699. sockaddr_in cli_addr{};
  8700. socklen_t cli_len = sizeof(cli_addr);
  8701. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8702. if (cli != INVALID_SOCKET) {
  8703. char buf[4096];
  8704. ::recv(cli, buf, sizeof(buf), 0);
  8705. auto content_length = std::to_string(DATA_SIZE);
  8706. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8707. "Content-Length: " +
  8708. content_length +
  8709. "\r\n"
  8710. "Connection: close\r\n"
  8711. "\r\n";
  8712. ::send(cli,
  8713. #ifdef _WIN32
  8714. static_cast<const char *>(response_header.c_str()),
  8715. static_cast<int>(response_header.size()),
  8716. #else
  8717. response_header.c_str(), response_header.size(),
  8718. #endif
  8719. 0);
  8720. std::string chunk(64 * 1024, 'A');
  8721. size_t total_sent = 0;
  8722. while (total_sent < DATA_SIZE) {
  8723. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8724. auto sent = ::send(cli,
  8725. #ifdef _WIN32
  8726. static_cast<const char *>(chunk.c_str()),
  8727. static_cast<int>(to_send),
  8728. #else
  8729. chunk.c_str(), to_send,
  8730. #endif
  8731. 0);
  8732. if (sent <= 0) break;
  8733. total_sent += static_cast<size_t>(sent);
  8734. }
  8735. detail::close_socket(cli);
  8736. }
  8737. detail::close_socket(srv);
  8738. });
  8739. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8740. size_t total_received = 0;
  8741. {
  8742. Client cli("127.0.0.1", PORT + 2);
  8743. cli.set_read_timeout(10, 0);
  8744. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8745. auto res =
  8746. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8747. total_received += data_length;
  8748. return true;
  8749. });
  8750. // Should fail because 200MB exceeds the explicit 150MB limit
  8751. EXPECT_FALSE(res);
  8752. }
  8753. server_thread.join();
  8754. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8755. << "Client with content_receiver should respect the explicit "
  8756. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8757. << total_received << " bytes.";
  8758. }
  8759. // Verify that an explicit set_payload_max_length larger than the response
  8760. // allows the content_receiver to read all data successfully.
  8761. TEST(ClientVulnerabilityTest,
  8762. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8763. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8764. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8765. #ifndef _WIN32
  8766. signal(SIGPIPE, SIG_IGN);
  8767. #endif
  8768. auto server_thread = std::thread([] {
  8769. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8770. default_socket_options(srv);
  8771. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8772. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8773. sockaddr_in addr{};
  8774. addr.sin_family = AF_INET;
  8775. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8776. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8777. int opt = 1;
  8778. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8779. #ifdef _WIN32
  8780. reinterpret_cast<const char *>(&opt),
  8781. #else
  8782. &opt,
  8783. #endif
  8784. sizeof(opt));
  8785. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8786. ::listen(srv, 1);
  8787. sockaddr_in cli_addr{};
  8788. socklen_t cli_len = sizeof(cli_addr);
  8789. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8790. if (cli != INVALID_SOCKET) {
  8791. char buf[4096];
  8792. ::recv(cli, buf, sizeof(buf), 0);
  8793. auto content_length = std::to_string(DATA_SIZE);
  8794. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8795. "Content-Length: " +
  8796. content_length +
  8797. "\r\n"
  8798. "Connection: close\r\n"
  8799. "\r\n";
  8800. ::send(cli,
  8801. #ifdef _WIN32
  8802. static_cast<const char *>(response_header.c_str()),
  8803. static_cast<int>(response_header.size()),
  8804. #else
  8805. response_header.c_str(), response_header.size(),
  8806. #endif
  8807. 0);
  8808. std::string chunk(64 * 1024, 'A');
  8809. size_t total_sent = 0;
  8810. while (total_sent < DATA_SIZE) {
  8811. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8812. auto sent = ::send(cli,
  8813. #ifdef _WIN32
  8814. static_cast<const char *>(chunk.c_str()),
  8815. static_cast<int>(to_send),
  8816. #else
  8817. chunk.c_str(), to_send,
  8818. #endif
  8819. 0);
  8820. if (sent <= 0) break;
  8821. total_sent += static_cast<size_t>(sent);
  8822. }
  8823. #ifdef _WIN32
  8824. ::shutdown(cli, SD_SEND);
  8825. #else
  8826. ::shutdown(cli, SHUT_WR);
  8827. #endif
  8828. char drain[1024];
  8829. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8830. detail::close_socket(cli);
  8831. }
  8832. detail::close_socket(srv);
  8833. });
  8834. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8835. size_t total_received = 0;
  8836. {
  8837. Client cli("127.0.0.1", PORT + 2);
  8838. cli.set_read_timeout(10, 0);
  8839. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8840. auto res =
  8841. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8842. total_received += data_length;
  8843. return true;
  8844. });
  8845. ASSERT_TRUE(res);
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. server_thread.join();
  8849. EXPECT_EQ(total_received, DATA_SIZE)
  8850. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8851. << " bytes (larger than " << DATA_SIZE
  8852. << " bytes response), content_receiver should read all data, but only "
  8853. "read "
  8854. << total_received << " bytes.";
  8855. }
  8856. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8857. // Regression test for "zip bomb" attack on the client side: a malicious server
  8858. // sends a small gzip-compressed response that decompresses to a huge payload.
  8859. // The client must enforce payload_max_length on the decompressed size.
  8860. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8861. constexpr size_t DECOMPRESSED_SIZE =
  8862. 10 * 1024 * 1024; // 10MB after decompression
  8863. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8864. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8865. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8866. std::string compressed;
  8867. {
  8868. httplib::detail::gzip_compressor compressor;
  8869. bool ok =
  8870. compressor.compress(uncompressed.data(), uncompressed.size(),
  8871. /*last=*/true, [&](const char *buf, size_t len) {
  8872. compressed.append(buf, len);
  8873. return true;
  8874. });
  8875. ASSERT_TRUE(ok);
  8876. }
  8877. // Sanity: compressed data should be much smaller than the decompressed size
  8878. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8879. #ifndef _WIN32
  8880. signal(SIGPIPE, SIG_IGN);
  8881. #endif
  8882. // Set up the listening socket in the main thread so the server is guaranteed
  8883. // to be ready before the client connects (eliminates race condition).
  8884. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8885. default_socket_options(srv);
  8886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8887. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8888. sockaddr_in addr{};
  8889. addr.sin_family = AF_INET;
  8890. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8891. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8892. int opt = 1;
  8893. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8894. #ifdef _WIN32
  8895. reinterpret_cast<const char *>(&opt),
  8896. #else
  8897. &opt,
  8898. #endif
  8899. sizeof(opt));
  8900. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8901. ASSERT_EQ(0, ::listen(srv, 1));
  8902. auto server_thread = std::thread([&compressed, srv] {
  8903. sockaddr_in cli_addr{};
  8904. socklen_t cli_len = sizeof(cli_addr);
  8905. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8906. if (cli != INVALID_SOCKET) {
  8907. // Read the full HTTP request (until \r\n\r\n)
  8908. char buf[4096];
  8909. size_t total = 0;
  8910. while (total < sizeof(buf)) {
  8911. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8912. if (n <= 0) break;
  8913. total += static_cast<size_t>(n);
  8914. // Check for end of headers
  8915. if (total >= 4) {
  8916. std::string req(buf, total);
  8917. if (req.find("\r\n\r\n") != std::string::npos) break;
  8918. }
  8919. }
  8920. // Malicious response: gzip-compressed body, no Content-Length
  8921. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8922. "Content-Encoding: gzip\r\n"
  8923. "Connection: close\r\n"
  8924. "\r\n";
  8925. ::send(cli,
  8926. #ifdef _WIN32
  8927. static_cast<const char *>(response_header.c_str()),
  8928. static_cast<int>(response_header.size()),
  8929. #else
  8930. response_header.c_str(), response_header.size(),
  8931. #endif
  8932. 0);
  8933. // Send the compressed payload (small on the wire, huge when decompressed)
  8934. size_t total_sent = 0;
  8935. while (total_sent < compressed.size()) {
  8936. auto to_send = std::min(compressed.size() - total_sent,
  8937. static_cast<size_t>(64 * 1024));
  8938. auto sent =
  8939. ::send(cli,
  8940. #ifdef _WIN32
  8941. static_cast<const char *>(compressed.c_str() + total_sent),
  8942. static_cast<int>(to_send),
  8943. #else
  8944. compressed.c_str() + total_sent, to_send,
  8945. #endif
  8946. 0);
  8947. if (sent <= 0) break;
  8948. total_sent += static_cast<size_t>(sent);
  8949. }
  8950. detail::close_socket(cli);
  8951. }
  8952. });
  8953. auto se = detail::scope_exit([&] {
  8954. detail::close_socket(srv);
  8955. server_thread.join();
  8956. });
  8957. size_t total_decompressed = 0;
  8958. {
  8959. Client cli("127.0.0.1", PORT + 3);
  8960. cli.set_read_timeout(5, 0);
  8961. cli.set_decompress(true);
  8962. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8963. auto stream = cli.open_stream("GET", "/zipbomb");
  8964. ASSERT_TRUE(stream.is_valid());
  8965. char buffer[64 * 1024];
  8966. ssize_t n;
  8967. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8968. total_decompressed += static_cast<size_t>(n);
  8969. }
  8970. }
  8971. // The decompressed size must be capped by payload_max_length. Without
  8972. // protection, the client would decompress the full 10MB from a tiny
  8973. // compressed payload, enabling a zip bomb DoS attack.
  8974. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8975. << "Client decompressed " << total_decompressed
  8976. << " bytes from a gzip response. The decompressed size should be "
  8977. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8978. }
  8979. #endif
  8980. TEST(HostAndPortPropertiesTest, NoSSL) {
  8981. httplib::Client cli("www.google.com", 1234);
  8982. ASSERT_EQ("www.google.com", cli.host());
  8983. ASSERT_EQ(1234, cli.port());
  8984. }
  8985. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8986. httplib::Client cli("www.google.com:1234");
  8987. ASSERT_EQ("www.google.com", cli.host());
  8988. ASSERT_EQ(1234, cli.port());
  8989. }
  8990. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8991. // Port number that overflows int — should not crash, client becomes invalid
  8992. httplib::Client cli("http://www.google.com:99999999999999999999");
  8993. ASSERT_FALSE(cli.is_valid());
  8994. }
  8995. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8996. // Port 99999 exceeds valid range (1-65535) — should not crash
  8997. httplib::Client cli("http://www.google.com:99999");
  8998. ASSERT_FALSE(cli.is_valid());
  8999. }
  9000. #ifdef CPPHTTPLIB_SSL_ENABLED
  9001. TEST(HostAndPortPropertiesTest, SSL) {
  9002. httplib::SSLClient cli("www.google.com");
  9003. ASSERT_EQ("www.google.com", cli.host());
  9004. ASSERT_EQ(443, cli.port());
  9005. }
  9006. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9007. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9008. std::string cert;
  9009. read_file(CA_CERT_FILE, cert);
  9010. httplib::SSLClient httplib_client("www.google.com");
  9011. // Load CA store first time
  9012. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9013. // Load CA store second time (update)
  9014. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9015. // Verify client is still valid and can make connections
  9016. httplib_client.enable_server_certificate_verification(true);
  9017. auto res = httplib_client.Get("/");
  9018. ASSERT_TRUE(res);
  9019. // Google may return 200 or 301 depending on various factors
  9020. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9021. res->status == StatusCode::MovedPermanently_301);
  9022. }
  9023. TEST(SSLClientTest, ServerNameIndication_Online) {
  9024. auto host = "httpbingo.org";
  9025. auto path = std::string{"/get"};
  9026. SSLClient cli(host, 443);
  9027. auto res = cli.Get(path);
  9028. ASSERT_TRUE(res);
  9029. ASSERT_EQ(StatusCode::OK_200, res->status);
  9030. }
  9031. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9032. // Use a site that will cause SSL verification failure due to self-signed cert
  9033. SSLClient cli("self-signed.badssl.com", 443);
  9034. cli.enable_server_certificate_verification(true);
  9035. auto res = cli.Get("/");
  9036. ASSERT_TRUE(!res);
  9037. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9038. // Verify backend error is captured for SSLServerVerification
  9039. // This occurs when certificate verification fails
  9040. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9041. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9042. EXPECT_NE(0UL, res.ssl_backend_error());
  9043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9044. // For OpenSSL, ssl_error is 0 for verification errors
  9045. EXPECT_EQ(0, res.ssl_error());
  9046. #if !defined(_WIN32) || \
  9047. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9048. // On non-Windows or when Windows Schannel is disabled, the error comes
  9049. // from OpenSSL's verification
  9050. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9051. res.ssl_backend_error());
  9052. #endif
  9053. #endif
  9054. }
  9055. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9056. // Use a site where hostname doesn't match the certificate
  9057. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9058. SSLClient cli("wrong.host.badssl.com", 443);
  9059. cli.enable_server_certificate_verification(true);
  9060. cli.enable_server_hostname_verification(true);
  9061. auto res = cli.Get("/");
  9062. ASSERT_TRUE(!res);
  9063. // The error type depends on when hostname verification occurs:
  9064. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9065. // - Mbed TLS: SSLServerVerification (during handshake)
  9066. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9067. res.error() == Error::SSLServerVerification);
  9068. // Verify backend error is captured for hostname verification failure
  9069. EXPECT_NE(0UL, res.ssl_backend_error());
  9070. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9071. // For OpenSSL, ssl_error is 0 for verification errors
  9072. EXPECT_EQ(0, res.ssl_error());
  9073. #if !defined(_WIN32) || \
  9074. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9075. // On non-Windows or when Windows Schannel is disabled, the error comes
  9076. // from OpenSSL's hostname verification
  9077. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9078. res.ssl_backend_error());
  9079. #endif
  9080. #endif
  9081. }
  9082. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9083. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9084. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9085. SSLClient cli("www.google.com", 443);
  9086. cli.enable_server_certificate_verification(true);
  9087. auto res = cli.Get("/");
  9088. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9089. }
  9090. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9091. SSLClient cli("www.google.com", 443);
  9092. cli.enable_server_certificate_verification(true);
  9093. cli.enable_windows_certificate_verification(false);
  9094. auto res = cli.Get("/");
  9095. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9096. }
  9097. #endif
  9098. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9099. Client cli("https://google.com");
  9100. auto res = cli.Get("/");
  9101. ASSERT_TRUE(res);
  9102. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9103. }
  9104. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9105. SSLClient cli("google.com");
  9106. cli.set_ca_cert_path(CA_CERT_FILE);
  9107. auto res = cli.Get("/");
  9108. ASSERT_TRUE(res);
  9109. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9110. }
  9111. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9112. SSLClient cli("google.com");
  9113. cli.enable_server_certificate_verification(true);
  9114. cli.set_ca_cert_path("hello");
  9115. auto res = cli.Get("/");
  9116. ASSERT_TRUE(!res);
  9117. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9118. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9119. // should be set
  9120. EXPECT_EQ(0, res.ssl_error());
  9121. // Verify backend error is captured for SSLLoadingCerts
  9122. // This error occurs when loading CA certificates fails
  9123. EXPECT_NE(0UL, res.ssl_backend_error());
  9124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9125. // OpenSSL specific error codes:
  9126. // > openssl errstr 0x80000002
  9127. // error:80000002:system library::No such file or directory
  9128. // > openssl errstr 0xA000126
  9129. // error:0A000126:SSL routines::unexpected eof while reading
  9130. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9131. res.ssl_backend_error() == 0xA000126);
  9132. #endif
  9133. }
  9134. TEST(SSLClientTest, ServerCertificateVerification4) {
  9135. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9136. ASSERT_TRUE(svr.is_valid());
  9137. svr.Get("/test", [&](const Request &, Response &res) {
  9138. res.set_content("test", "text/plain");
  9139. svr.stop();
  9140. ASSERT_TRUE(true);
  9141. });
  9142. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9143. auto se = detail::scope_exit([&] {
  9144. t.join();
  9145. ASSERT_FALSE(svr.is_running());
  9146. });
  9147. svr.wait_until_ready();
  9148. SSLClient cli("127.0.0.1", PORT);
  9149. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9150. cli.enable_server_certificate_verification(true);
  9151. cli.set_connection_timeout(30);
  9152. auto res = cli.Get("/test");
  9153. ASSERT_TRUE(res);
  9154. ASSERT_EQ(StatusCode::OK_200, res->status);
  9155. }
  9156. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9157. std::string cert;
  9158. read_file(CA_CERT_FILE, cert);
  9159. SSLClient cli("google.com");
  9160. cli.load_ca_cert_store(cert.data(), cert.size());
  9161. const auto res = cli.Get("/");
  9162. ASSERT_TRUE(res);
  9163. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9164. }
  9165. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9166. // clang-format off
  9167. static constexpr char cert[] =
  9168. "GlobalSign Root CA\n"
  9169. "==================\n"
  9170. "-----BEGIN CERTIFICATE-----\n"
  9171. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9172. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9173. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9174. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9175. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9176. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9177. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9178. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9179. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9180. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9181. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9182. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9183. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9184. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9185. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9186. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9187. "-----END CERTIFICATE-----\n";
  9188. // clang-format on
  9189. SSLClient cli("google.com");
  9190. cli.load_ca_cert_store(cert, sizeof(cert));
  9191. const auto res = cli.Get("/");
  9192. ASSERT_TRUE(res);
  9193. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9194. }
  9195. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9196. SSLClient cli("www.youtube.com");
  9197. cli.set_ca_cert_path(CA_CERT_FILE);
  9198. cli.enable_server_certificate_verification(true);
  9199. cli.set_follow_location(true);
  9200. auto res = cli.Get("/");
  9201. ASSERT_TRUE(res);
  9202. ASSERT_EQ(StatusCode::OK_200, res->status);
  9203. }
  9204. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9205. SSLClient cli("wWw.YouTube.Com");
  9206. cli.set_ca_cert_path(CA_CERT_FILE);
  9207. cli.enable_server_certificate_verification(true);
  9208. cli.enable_server_hostname_verification(true);
  9209. cli.set_follow_location(true);
  9210. auto res = cli.Get("/");
  9211. ASSERT_TRUE(res);
  9212. ASSERT_EQ(StatusCode::OK_200, res->status);
  9213. }
  9214. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9215. SSLClient cli("gOoGlE.COm");
  9216. cli.enable_server_certificate_verification(true);
  9217. cli.enable_server_hostname_verification(true);
  9218. cli.set_follow_location(true);
  9219. auto res = cli.Get("/");
  9220. ASSERT_TRUE(res);
  9221. ASSERT_EQ(StatusCode::OK_200, res->status);
  9222. }
  9223. TEST(SSLClientTest, Issue2004_Online) {
  9224. Client client("https://google.com");
  9225. client.set_follow_location(true);
  9226. auto res = client.Get("/");
  9227. ASSERT_TRUE(res);
  9228. ASSERT_EQ(StatusCode::OK_200, res->status);
  9229. auto body = res->body;
  9230. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9231. }
  9232. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9233. // Create SSLClient with invalid cert/key to make is_valid() return false
  9234. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9235. "nonexistent_key.pem");
  9236. // is_valid() should be false due to cert loading failure
  9237. ASSERT_FALSE(cli.is_valid());
  9238. auto res = cli.Get("/");
  9239. ASSERT_FALSE(res);
  9240. EXPECT_EQ(Error::SSLConnection, res.error());
  9241. }
  9242. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9243. // Test for Issue #2251: SSL error not properly reported when client cert
  9244. // and key paths are swapped or mismatched
  9245. // This simulates the scenario where user accidentally swaps the cert and key
  9246. // files
  9247. // Using client cert file as private key and vice versa (completely wrong)
  9248. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9249. // Should fail validation due to cert/key mismatch
  9250. ASSERT_FALSE(cli.is_valid());
  9251. // Attempt to make a request should fail with proper error
  9252. auto res = cli.Get("/");
  9253. ASSERT_FALSE(res);
  9254. EXPECT_EQ(Error::SSLConnection, res.error());
  9255. // SSL error should be recorded in the Result object (this is the key fix for
  9256. // Issue #2251)
  9257. auto backend_error = res.ssl_backend_error();
  9258. EXPECT_NE(0u, backend_error);
  9259. }
  9260. // Tests cert/key mismatch detection at the TLS context level
  9261. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9262. // Test that using mismatched cert/key causes connection failure.
  9263. // We verify this at the SSLClient level rather than through internal
  9264. // TLS API functions.
  9265. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9266. cli.enable_server_certificate_verification(false);
  9267. cli.set_connection_timeout(2);
  9268. // The mismatch should cause a connection or handshake error
  9269. auto res = cli.Get("/test");
  9270. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9271. // Either way, the request should fail
  9272. EXPECT_FALSE(res);
  9273. }
  9274. #endif
  9275. #if 0
  9276. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9277. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9278. ASSERT_TRUE(cli != nullptr);
  9279. cli->set_address_family(AF_INET6);
  9280. cli->set_interface("en0");
  9281. auto res = cli->Get("/get");
  9282. ASSERT_TRUE(res);
  9283. ASSERT_EQ(StatusCode::OK_200, res->status);
  9284. }
  9285. #endif
  9286. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9287. #ifdef CPPHTTPLIB_SSL_ENABLED
  9288. void ClientCertPresent(
  9289. const std::string &client_cert_file,
  9290. const std::string &client_private_key_file,
  9291. const std::string &client_encrypted_private_key_pass = std::string()) {
  9292. using namespace httplib::tls;
  9293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9294. CLIENT_CA_CERT_DIR);
  9295. ASSERT_TRUE(svr.is_valid());
  9296. svr.Get("/test", [&](const Request &req, Response &res) {
  9297. res.set_content("test", "text/plain");
  9298. auto cert = req.peer_cert();
  9299. ASSERT_TRUE(static_cast<bool>(cert));
  9300. std::string common_name = cert.subject_cn();
  9301. EXPECT_EQ("Common Name", common_name);
  9302. });
  9303. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9304. auto se = detail::scope_exit([&] {
  9305. svr.stop();
  9306. t.join();
  9307. ASSERT_FALSE(svr.is_running());
  9308. });
  9309. svr.wait_until_ready();
  9310. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9311. client_encrypted_private_key_pass);
  9312. cli.enable_server_certificate_verification(false);
  9313. cli.set_connection_timeout(30);
  9314. auto res = cli.Get("/test");
  9315. ASSERT_TRUE(res);
  9316. ASSERT_EQ(StatusCode::OK_200, res->status);
  9317. }
  9318. TEST(SSLClientServerTest, ClientCertPresent) {
  9319. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9320. }
  9321. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9322. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9323. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9324. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9325. }
  9326. // PEM memory-based constructor tests (works with all TLS backends)
  9327. void PemMemoryClientCertPresent(
  9328. const std::string &client_cert_file,
  9329. const std::string &client_private_key_file,
  9330. const std::string &client_encrypted_private_key_pass = std::string()) {
  9331. // Read PEM files into memory
  9332. std::string server_cert_pem, server_key_pem;
  9333. std::string client_ca_pem;
  9334. std::string client_cert_pem, client_key_pem;
  9335. read_file(SERVER_CERT_FILE, server_cert_pem);
  9336. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9337. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9338. read_file(client_cert_file, client_cert_pem);
  9339. read_file(client_private_key_file, client_key_pem);
  9340. // Create server with PEM memory
  9341. SSLServer::PemMemory server_pem = {
  9342. server_cert_pem.c_str(),
  9343. server_cert_pem.size(),
  9344. server_key_pem.c_str(),
  9345. server_key_pem.size(),
  9346. client_ca_pem.c_str(),
  9347. client_ca_pem.size(),
  9348. nullptr // no password for server key
  9349. };
  9350. SSLServer svr(server_pem);
  9351. ASSERT_TRUE(svr.is_valid());
  9352. svr.Get("/test", [&](const Request &, Response &res) {
  9353. res.set_content("test", "text/plain");
  9354. });
  9355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. ASSERT_FALSE(svr.is_running());
  9360. });
  9361. svr.wait_until_ready();
  9362. // Create client with PEM memory
  9363. const char *password = client_encrypted_private_key_pass.empty()
  9364. ? nullptr
  9365. : client_encrypted_private_key_pass.c_str();
  9366. SSLClient::PemMemory client_pem = {
  9367. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9368. client_key_pem.size(), password};
  9369. SSLClient cli(HOST, PORT, client_pem);
  9370. cli.enable_server_certificate_verification(false);
  9371. cli.set_connection_timeout(30);
  9372. auto res = cli.Get("/test");
  9373. ASSERT_TRUE(res);
  9374. ASSERT_EQ(StatusCode::OK_200, res->status);
  9375. }
  9376. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9377. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9378. }
  9379. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9380. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9381. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9382. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9383. }
  9384. TEST(SSLClientServerTest, ClientCertMissing) {
  9385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9386. CLIENT_CA_CERT_DIR);
  9387. ASSERT_TRUE(svr.is_valid());
  9388. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9389. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9390. auto se = detail::scope_exit([&] {
  9391. svr.stop();
  9392. t.join();
  9393. ASSERT_FALSE(svr.is_running());
  9394. });
  9395. svr.wait_until_ready();
  9396. SSLClient cli(HOST, PORT);
  9397. cli.set_connection_timeout(30);
  9398. auto res = cli.Get("/test");
  9399. ASSERT_TRUE(!res);
  9400. // When client cert is missing and server requires it, connection fails
  9401. // Error type depends on backend implementation
  9402. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9403. res.error() == Error::SSLConnection);
  9404. // Verify backend error is captured
  9405. // Note: This test may have different error codes depending on the exact
  9406. // verification failure
  9407. EXPECT_NE(0UL, res.ssl_backend_error());
  9408. }
  9409. TEST(SSLClientServerTest, TrustDirOptional) {
  9410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9411. ASSERT_TRUE(svr.is_valid());
  9412. svr.Get("/test", [&](const Request &, Response &res) {
  9413. res.set_content("test", "text/plain");
  9414. });
  9415. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9416. auto se = detail::scope_exit([&] {
  9417. svr.stop();
  9418. t.join();
  9419. ASSERT_FALSE(svr.is_running());
  9420. });
  9421. svr.wait_until_ready();
  9422. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9423. cli.enable_server_certificate_verification(false);
  9424. cli.set_connection_timeout(30);
  9425. auto res = cli.Get("/test");
  9426. ASSERT_TRUE(res);
  9427. ASSERT_EQ(StatusCode::OK_200, res->status);
  9428. }
  9429. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9430. class NoListenSSLServer : public SSLServer {
  9431. public:
  9432. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9433. const char *client_ca_cert_file_path,
  9434. const char *client_ca_cert_dir_path = nullptr)
  9435. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9436. client_ca_cert_dir_path),
  9437. stop_(false) {}
  9438. std::atomic_bool stop_;
  9439. private:
  9440. bool process_and_close_socket(socket_t /*sock*/) override {
  9441. // Don't create SSL context
  9442. while (!stop_.load()) {
  9443. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9444. }
  9445. return true;
  9446. }
  9447. };
  9448. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9449. CLIENT_CA_CERT_FILE);
  9450. ASSERT_TRUE(svr.is_valid());
  9451. svr.Get("/test", [&](const Request &, Response &res) {
  9452. res.set_content("test", "text/plain");
  9453. });
  9454. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9455. auto se = detail::scope_exit([&] {
  9456. svr.stop_ = true;
  9457. svr.stop();
  9458. t.join();
  9459. ASSERT_FALSE(svr.is_running());
  9460. });
  9461. svr.wait_until_ready();
  9462. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9463. cli.enable_server_certificate_verification(false);
  9464. cli.set_connection_timeout(1);
  9465. auto res = cli.Get("/test");
  9466. ASSERT_TRUE(!res);
  9467. EXPECT_EQ(Error::SSLConnection, res.error());
  9468. // Timeout results in WantRead error code (maps to backend-specific value)
  9469. EXPECT_NE(0, res.ssl_error());
  9470. }
  9471. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9472. // Test SSLServer with client certificate verification using the standard
  9473. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9475. CLIENT_CA_CERT_DIR);
  9476. ASSERT_TRUE(svr.is_valid());
  9477. svr.Get("/test", [&](const Request &req, Response &res) {
  9478. res.set_content("test", "text/plain");
  9479. auto cert = req.peer_cert();
  9480. ASSERT_TRUE(static_cast<bool>(cert));
  9481. auto common_name = cert.subject_cn();
  9482. EXPECT_EQ("Common Name", common_name);
  9483. });
  9484. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9485. auto se = detail::scope_exit([&] {
  9486. svr.stop();
  9487. t.join();
  9488. ASSERT_FALSE(svr.is_running());
  9489. });
  9490. svr.wait_until_ready();
  9491. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9492. cli.enable_server_certificate_verification(false);
  9493. cli.set_connection_timeout(30);
  9494. auto res = cli.Get("/test");
  9495. ASSERT_TRUE(res);
  9496. ASSERT_EQ(StatusCode::OK_200, res->status);
  9497. }
  9498. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9499. // Verifies that wildcard matching and exact matching work consistently
  9500. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9501. using namespace httplib::tls;
  9502. // We need a running server to test against
  9503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9504. ASSERT_TRUE(svr.is_valid());
  9505. svr.Get("/test", [](const Request &, Response &res) {
  9506. res.set_content("ok", "text/plain");
  9507. });
  9508. thread t([&]() { svr.listen(HOST, PORT); });
  9509. auto se = detail::scope_exit([&] {
  9510. svr.stop();
  9511. t.join();
  9512. });
  9513. svr.wait_until_ready();
  9514. bool verify_callback_called = false;
  9515. bool verify_result_wrong = false;
  9516. SSLClient cli(HOST, PORT);
  9517. cli.enable_server_certificate_verification(true);
  9518. cli.set_ca_cert_path(CA_CERT_FILE);
  9519. cli.set_connection_timeout(5);
  9520. // Note: Test certificate has CN="Common Name", not "localhost"
  9521. bool verify_result_cn = false;
  9522. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9523. verify_callback_called = true;
  9524. if (!ctx.cert) return false;
  9525. // Test 1: "Common Name" should match (our test server cert CN)
  9526. verify_result_cn = ctx.check_hostname("Common Name");
  9527. // Test 2: wrong hostname should not match
  9528. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9529. return true; // Accept for the purpose of this test
  9530. });
  9531. auto res = cli.Get("/test");
  9532. // The request may succeed or fail depending on cert configuration
  9533. // but the callback should have been called
  9534. ASSERT_TRUE(verify_callback_called)
  9535. << "Verify callback should have been called";
  9536. // CN="Common Name" should match our test certificate
  9537. //
  9538. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9539. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9540. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9541. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9542. // <openssl/base.h>, which is included transitively when
  9543. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9544. #if defined(OPENSSL_IS_BORINGSSL)
  9545. EXPECT_FALSE(verify_result_cn)
  9546. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9547. #else
  9548. EXPECT_TRUE(verify_result_cn)
  9549. << "verify_hostname should match 'Common Name' (certificate CN)";
  9550. #endif
  9551. // Wrong hostname should not match
  9552. EXPECT_FALSE(verify_result_wrong)
  9553. << "verify_hostname should not match 'wronghost.example.com'";
  9554. }
  9555. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9556. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9557. // X509_check_ip behavior and must hold for every backend.
  9558. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9559. using namespace httplib::tls;
  9560. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9561. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9562. ASSERT_TRUE(svr.is_valid());
  9563. svr.Get("/test", [](const Request &, Response &res) {
  9564. res.set_content("ok", "text/plain");
  9565. });
  9566. thread t([&]() { svr.listen(HOST, PORT); });
  9567. auto se = detail::scope_exit([&] {
  9568. svr.stop();
  9569. t.join();
  9570. });
  9571. svr.wait_until_ready();
  9572. bool verify_callback_called = false;
  9573. bool ip_matched_via_cn = true;
  9574. SSLClient cli(HOST, PORT);
  9575. cli.enable_server_certificate_verification(true);
  9576. cli.set_ca_cert_path(CA_CERT_FILE);
  9577. cli.set_connection_timeout(5);
  9578. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9579. verify_callback_called = true;
  9580. if (!ctx.cert) return false;
  9581. // The IP appears only in the CN, so it must NOT be accepted.
  9582. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9583. return true; // Accept for the purpose of this test
  9584. });
  9585. cli.Get("/test");
  9586. ASSERT_TRUE(verify_callback_called)
  9587. << "Verify callback should have been called";
  9588. EXPECT_FALSE(ip_matched_via_cn)
  9589. << "An IP host must not be authenticated via the certificate CN";
  9590. }
  9591. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9592. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9593. using namespace httplib::tls;
  9594. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9595. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9596. ASSERT_TRUE(svr.is_valid());
  9597. svr.Get("/test", [](const Request &, Response &res) {
  9598. res.set_content("ok", "text/plain");
  9599. });
  9600. thread t([&]() { svr.listen(HOST, PORT); });
  9601. auto se = detail::scope_exit([&] {
  9602. svr.stop();
  9603. t.join();
  9604. });
  9605. svr.wait_until_ready();
  9606. bool verify_callback_called = false;
  9607. bool san_matched = false;
  9608. bool wrong_ipv6_matched = true;
  9609. bool cn_ipv6_matched = true;
  9610. SSLClient cli(HOST, PORT);
  9611. cli.enable_server_certificate_verification(true);
  9612. cli.set_ca_cert_path(CA_CERT_FILE);
  9613. cli.set_connection_timeout(5);
  9614. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9615. verify_callback_called = true;
  9616. if (!ctx.cert) return false;
  9617. // Matches the IPv6 iPAddress SAN.
  9618. san_matched = ctx.check_hostname("2001:db8::1");
  9619. // A different IPv6 address must not match.
  9620. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9621. // "::1" lives only in the CN, so it must not be accepted.
  9622. cn_ipv6_matched = ctx.check_hostname("::1");
  9623. return true; // Accept for the purpose of this test
  9624. });
  9625. cli.Get("/test");
  9626. ASSERT_TRUE(verify_callback_called)
  9627. << "Verify callback should have been called";
  9628. EXPECT_TRUE(san_matched)
  9629. << "verify_hostname should match an IPv6 iPAddress SAN";
  9630. EXPECT_FALSE(wrong_ipv6_matched)
  9631. << "verify_hostname should not match a non-matching IPv6 address";
  9632. EXPECT_FALSE(cn_ipv6_matched)
  9633. << "An IPv6 host must not be authenticated via the certificate CN";
  9634. }
  9635. #endif
  9636. // mbedTLS-specific callback constructor test
  9637. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9638. #ifdef CPPHTTPLIB_SSL_ENABLED
  9639. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9640. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9641. ASSERT_TRUE(svr.is_valid());
  9642. // Set up a handler to verify client certificate is present
  9643. bool client_cert_verified = false;
  9644. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9645. // Verify that client certificate was provided
  9646. client_cert_verified = true;
  9647. res.set_content("success", "text/plain");
  9648. });
  9649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9650. auto se = detail::scope_exit([&] {
  9651. svr.stop();
  9652. t.join();
  9653. ASSERT_FALSE(svr.is_running());
  9654. });
  9655. svr.wait_until_ready();
  9656. // Client with certificate
  9657. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9658. cli.enable_server_certificate_verification(false);
  9659. cli.set_connection_timeout(30);
  9660. auto res = cli.Get("/test");
  9661. ASSERT_TRUE(res);
  9662. ASSERT_EQ(StatusCode::OK_200, res->status);
  9663. ASSERT_TRUE(client_cert_verified);
  9664. EXPECT_EQ("success", res->body);
  9665. }
  9666. #endif
  9667. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9668. // backends
  9669. #ifdef CPPHTTPLIB_SSL_ENABLED
  9670. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9671. using namespace httplib::tls;
  9672. // Test that when client CA cert file is provided,
  9673. // the server properly requests and validates client certificates
  9674. // Create a server with client authentication
  9675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9676. ASSERT_TRUE(svr.is_valid());
  9677. bool handler_called = false;
  9678. svr.Get("/test", [&](const Request &req, Response &res) {
  9679. handler_called = true;
  9680. // Verify that a client certificate was provided
  9681. auto cert = req.peer_cert();
  9682. ASSERT_TRUE(static_cast<bool>(cert));
  9683. // Get the issuer name
  9684. std::string issuer_str = cert.issuer_name();
  9685. ASSERT_FALSE(issuer_str.empty());
  9686. // The client certificate should be issued by our test CA
  9687. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9688. res.set_content("authenticated", "text/plain");
  9689. });
  9690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9691. auto se = detail::scope_exit([&] {
  9692. svr.stop();
  9693. t.join();
  9694. ASSERT_FALSE(svr.is_running());
  9695. });
  9696. svr.wait_until_ready();
  9697. // Connect with a client certificate issued by the CA
  9698. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9699. cli.enable_server_certificate_verification(false);
  9700. cli.set_connection_timeout(30);
  9701. auto res = cli.Get("/test");
  9702. ASSERT_TRUE(res);
  9703. ASSERT_EQ(StatusCode::OK_200, res->status);
  9704. ASSERT_TRUE(handler_called);
  9705. EXPECT_EQ("authenticated", res->body);
  9706. }
  9707. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9708. using namespace httplib::tls;
  9709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9710. ASSERT_TRUE(svr.is_valid());
  9711. svr.Get("/test", [](const Request &, Response &res) {
  9712. res.set_content("ok", "text/plain");
  9713. });
  9714. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9715. auto se = detail::scope_exit([&] {
  9716. svr.stop();
  9717. t.join();
  9718. });
  9719. svr.wait_until_ready();
  9720. SSLClient cli(HOST, PORT);
  9721. cli.enable_server_certificate_verification(false);
  9722. cli.set_connection_timeout(30);
  9723. bool cert_checked = false;
  9724. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9725. if (ctx.cert) {
  9726. auto sans = ctx.sans();
  9727. // Test certificate may or may not have SANs - just verify the API
  9728. // works If SANs exist, verify the types are valid
  9729. for (const auto &san : sans) {
  9730. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9731. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9732. san.type == SanType::OTHER);
  9733. EXPECT_FALSE(san.value.empty());
  9734. }
  9735. cert_checked = true;
  9736. }
  9737. return true;
  9738. });
  9739. auto res = cli.Get("/test");
  9740. ASSERT_TRUE(res);
  9741. EXPECT_TRUE(cert_checked);
  9742. }
  9743. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9744. using namespace httplib::tls;
  9745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9746. ASSERT_TRUE(svr.is_valid());
  9747. svr.Get("/test", [](const Request &, Response &res) {
  9748. res.set_content("ok", "text/plain");
  9749. });
  9750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. t.join();
  9754. });
  9755. svr.wait_until_ready();
  9756. SSLClient cli(HOST, PORT);
  9757. cli.enable_server_certificate_verification(false);
  9758. cli.set_connection_timeout(30);
  9759. bool validity_checked = false;
  9760. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9761. if (ctx.cert) {
  9762. time_t not_before = 0, not_after = 0;
  9763. bool result = ctx.validity(not_before, not_after);
  9764. EXPECT_TRUE(result);
  9765. // Verify that not_before < now < not_after for a valid cert
  9766. time_t now = time(nullptr);
  9767. EXPECT_LT(not_before, now);
  9768. EXPECT_GT(not_after, now);
  9769. validity_checked = true;
  9770. }
  9771. return true;
  9772. });
  9773. auto res = cli.Get("/test");
  9774. ASSERT_TRUE(res);
  9775. EXPECT_TRUE(validity_checked);
  9776. }
  9777. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9778. using namespace httplib::tls;
  9779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9780. ASSERT_TRUE(svr.is_valid());
  9781. svr.Get("/test", [](const Request &, Response &res) {
  9782. res.set_content("ok", "text/plain");
  9783. });
  9784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9785. auto se = detail::scope_exit([&] {
  9786. svr.stop();
  9787. t.join();
  9788. });
  9789. svr.wait_until_ready();
  9790. SSLClient cli(HOST, PORT);
  9791. cli.enable_server_certificate_verification(false);
  9792. cli.set_connection_timeout(30);
  9793. bool serial_checked = false;
  9794. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9795. if (ctx.cert) {
  9796. std::string serial = ctx.serial();
  9797. EXPECT_FALSE(serial.empty());
  9798. // Serial should be a hex string
  9799. for (char c : serial) {
  9800. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9801. (c >= 'a' && c <= 'f'));
  9802. }
  9803. serial_checked = true;
  9804. }
  9805. return true;
  9806. });
  9807. auto res = cli.Get("/test");
  9808. ASSERT_TRUE(res);
  9809. EXPECT_TRUE(serial_checked);
  9810. }
  9811. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9812. // Test 1: Valid CA file - no error should be recorded
  9813. {
  9814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9815. CLIENT_CA_CERT_FILE);
  9816. ASSERT_TRUE(svr.is_valid());
  9817. // With valid setup, last_ssl_error should be 0
  9818. EXPECT_EQ(0, svr.ssl_last_error());
  9819. }
  9820. // Test 2: Invalid CA file content
  9821. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9822. {
  9823. // Create a temporary file with completely invalid content
  9824. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9825. {
  9826. std::ofstream ofs(temp_invalid_ca);
  9827. ofs << "This is not a certificate file at all\n";
  9828. ofs << "Just plain text content\n";
  9829. }
  9830. // Create server with invalid CA file
  9831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9832. // Clean up temporary file
  9833. std::remove(temp_invalid_ca);
  9834. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9835. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9836. // Note: SSL_CTX_load_verify_locations typically fails first,
  9837. // but our error handling code path is still exercised
  9838. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9839. }
  9840. }
  9841. TEST(VerifyCallbackTest, VerifyContextFields) {
  9842. using namespace httplib::tls;
  9843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9844. ASSERT_TRUE(svr.is_valid());
  9845. svr.Get("/test", [](const Request &, Response &res) {
  9846. res.set_content("ok", "text/plain");
  9847. });
  9848. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9849. auto se = detail::scope_exit([&] {
  9850. svr.stop();
  9851. t.join();
  9852. });
  9853. svr.wait_until_ready();
  9854. SSLClient cli(HOST, PORT);
  9855. cli.enable_server_certificate_verification(false);
  9856. cli.set_connection_timeout(30);
  9857. int callback_count = 0;
  9858. bool saw_leaf_cert = false;
  9859. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9860. if (ctx.cert) {
  9861. callback_count++;
  9862. // We should see at least one certificate (the leaf)
  9863. std::string cn = ctx.subject_cn();
  9864. if (!cn.empty()) { saw_leaf_cert = true; }
  9865. // Verify context fields are populated
  9866. EXPECT_NE(ctx.session, nullptr);
  9867. EXPECT_GE(ctx.depth, 0);
  9868. }
  9869. return true;
  9870. });
  9871. auto res = cli.Get("/test");
  9872. ASSERT_TRUE(res);
  9873. EXPECT_GT(callback_count, 0);
  9874. EXPECT_TRUE(saw_leaf_cert);
  9875. }
  9876. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9877. using httplib::tls::TlsError;
  9878. // Test that verify_error_to_string returns empty for success
  9879. std::string success_str = TlsError::verify_error_to_string(0);
  9880. EXPECT_TRUE(success_str.empty());
  9881. // Test that verify_error_to_string returns non-empty for error codes
  9882. // Using a common error code (certificate expired)
  9883. std::string error_str =
  9884. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9885. EXPECT_FALSE(error_str.empty());
  9886. }
  9887. TEST(SessionVerifierTest, CertificateAccepted) {
  9888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9889. ASSERT_TRUE(svr.is_valid());
  9890. svr.Get("/test", [](const Request &, Response &res) {
  9891. res.set_content("ok", "text/plain");
  9892. });
  9893. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9894. auto se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. t.join();
  9897. });
  9898. svr.wait_until_ready();
  9899. SSLClient cli(HOST, PORT);
  9900. cli.enable_server_certificate_verification(false);
  9901. cli.set_connection_timeout(30);
  9902. bool callback_called = false;
  9903. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9904. EXPECT_NE(session, nullptr);
  9905. callback_called = true;
  9906. return SSLVerifierResponse::CertificateAccepted;
  9907. });
  9908. auto res = cli.Get("/test");
  9909. ASSERT_TRUE(res);
  9910. EXPECT_EQ(200, res->status);
  9911. EXPECT_TRUE(callback_called);
  9912. }
  9913. TEST(SessionVerifierTest, CertificateRejected) {
  9914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9915. ASSERT_TRUE(svr.is_valid());
  9916. svr.Get("/test", [](const Request &, Response &res) {
  9917. res.set_content("ok", "text/plain");
  9918. });
  9919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9920. auto se = detail::scope_exit([&] {
  9921. svr.stop();
  9922. t.join();
  9923. });
  9924. svr.wait_until_ready();
  9925. SSLClient cli(HOST, PORT);
  9926. cli.enable_server_certificate_verification(false);
  9927. cli.set_connection_timeout(30);
  9928. bool callback_called = false;
  9929. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9930. EXPECT_NE(session, nullptr);
  9931. callback_called = true;
  9932. return SSLVerifierResponse::CertificateRejected;
  9933. });
  9934. auto res = cli.Get("/test");
  9935. EXPECT_FALSE(res);
  9936. EXPECT_TRUE(callback_called);
  9937. }
  9938. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9940. ASSERT_TRUE(svr.is_valid());
  9941. svr.Get("/test", [](const Request &, Response &res) {
  9942. res.set_content("ok", "text/plain");
  9943. });
  9944. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9945. auto se = detail::scope_exit([&] {
  9946. svr.stop();
  9947. t.join();
  9948. });
  9949. svr.wait_until_ready();
  9950. // NoDecisionMade with verification disabled should succeed (no default check)
  9951. SSLClient cli(HOST, PORT);
  9952. cli.enable_server_certificate_verification(false);
  9953. cli.set_connection_timeout(30);
  9954. bool callback_called = false;
  9955. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9956. EXPECT_NE(session, nullptr);
  9957. callback_called = true;
  9958. return SSLVerifierResponse::NoDecisionMade;
  9959. });
  9960. auto res = cli.Get("/test");
  9961. ASSERT_TRUE(res);
  9962. EXPECT_EQ(200, res->status);
  9963. EXPECT_TRUE(callback_called);
  9964. }
  9965. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9967. ASSERT_TRUE(svr.is_valid());
  9968. svr.Get("/test", [](const Request &, Response &res) {
  9969. res.set_content("ok", "text/plain");
  9970. });
  9971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9972. auto se = detail::scope_exit([&] {
  9973. svr.stop();
  9974. t.join();
  9975. });
  9976. svr.wait_until_ready();
  9977. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9978. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9979. // so we only check that the request fails, not whether the callback was
  9980. // called.
  9981. SSLClient cli(HOST, PORT);
  9982. cli.enable_server_certificate_verification(true);
  9983. cli.set_connection_timeout(30);
  9984. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9985. EXPECT_NE(session, nullptr);
  9986. return SSLVerifierResponse::NoDecisionMade;
  9987. });
  9988. auto res = cli.Get("/test");
  9989. EXPECT_FALSE(res);
  9990. }
  9991. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9992. // Test SSL server using PemMemory constructor with client CA certificates
  9993. // Read PEM files
  9994. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9995. read_file(SERVER_CERT_FILE, server_cert_pem);
  9996. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9997. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9998. // Create SSLServer with PemMemory constructor including client CA
  9999. SSLServer::PemMemory server_pem = {
  10000. server_cert_pem.c_str(),
  10001. server_cert_pem.size(),
  10002. server_key_pem.c_str(),
  10003. server_key_pem.size(),
  10004. client_ca_pem.c_str(),
  10005. client_ca_pem.size(),
  10006. nullptr // no password for server key
  10007. };
  10008. SSLServer svr(server_pem);
  10009. ASSERT_TRUE(svr.is_valid());
  10010. // No SSL error should be recorded for valid setup
  10011. EXPECT_EQ(0, svr.ssl_last_error());
  10012. // Set up server endpoints
  10013. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10014. res.set_content("ok", "text/plain");
  10015. });
  10016. // Start server in a thread
  10017. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10018. svr.wait_until_ready();
  10019. // Connect with client certificate (using constructor with paths)
  10020. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10021. cli.enable_server_certificate_verification(false);
  10022. auto res = cli.Get("/test-pem-ca");
  10023. ASSERT_TRUE(res);
  10024. EXPECT_EQ(200, res->status);
  10025. EXPECT_EQ("ok", res->body);
  10026. svr.stop();
  10027. server_thread.join();
  10028. }
  10029. #endif
  10030. #ifdef _WIN32
  10031. TEST(CleanupTest, WSACleanup) {
  10032. int ret = WSACleanup();
  10033. ASSERT_EQ(0, ret);
  10034. }
  10035. #endif
  10036. #ifndef CPPHTTPLIB_SSL_ENABLED
  10037. TEST(NoSSLSupport, SimpleInterface) {
  10038. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10039. }
  10040. #endif
  10041. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10042. TEST(InvalidScheme, SimpleInterface) {
  10043. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10044. }
  10045. #endif
  10046. TEST(NoScheme, SimpleInterface) {
  10047. Client cli("yahoo.com:80");
  10048. ASSERT_TRUE(cli.is_valid());
  10049. }
  10050. TEST(SendAPI, SimpleInterface_Online) {
  10051. Client cli("http://yahoo.com");
  10052. Request req;
  10053. req.method = "GET";
  10054. req.path = "/";
  10055. auto res = cli.send(req);
  10056. ASSERT_TRUE(res);
  10057. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10058. }
  10059. TEST(SendAPI, WithParamsInRequest) {
  10060. Server svr;
  10061. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10062. EXPECT_TRUE(req.has_param("test"));
  10063. EXPECT_EQ("test_value", req.get_param_value("test"));
  10064. });
  10065. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10066. auto se = detail::scope_exit([&] {
  10067. svr.stop();
  10068. t.join();
  10069. ASSERT_FALSE(svr.is_running());
  10070. });
  10071. svr.wait_until_ready();
  10072. Client cli(HOST, PORT);
  10073. {
  10074. Request req;
  10075. req.method = "GET";
  10076. req.path = "/";
  10077. req.params.emplace("test", "test_value");
  10078. auto res = cli.send(req);
  10079. ASSERT_TRUE(res);
  10080. }
  10081. {
  10082. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10083. ASSERT_TRUE(res);
  10084. }
  10085. }
  10086. TEST(ClientImplMethods, GetSocketTest) {
  10087. httplib::Server svr;
  10088. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10089. res.status = StatusCode::OK_200;
  10090. });
  10091. auto port = svr.bind_to_any_port("127.0.0.1");
  10092. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10093. auto se = detail::scope_exit([&] {
  10094. svr.stop();
  10095. thread.join();
  10096. ASSERT_FALSE(svr.is_running());
  10097. });
  10098. svr.wait_until_ready();
  10099. {
  10100. httplib::Client cli("127.0.0.1", port);
  10101. cli.set_keep_alive(true);
  10102. // Use the behavior of cpp-httplib of opening the connection
  10103. // only when the first request happens. If that changes,
  10104. // this test would be obsolete.
  10105. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10106. // This also implicitly tests the server. But other tests would fail much
  10107. // earlier than this one to be considered.
  10108. auto res = cli.Get("/");
  10109. ASSERT_TRUE(res);
  10110. EXPECT_EQ(StatusCode::OK_200, res->status);
  10111. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10112. }
  10113. }
  10114. #ifdef CPPHTTPLIB_SSL_ENABLED
  10115. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10116. Client cli("http://yahoo.com");
  10117. auto res = cli.Get("/");
  10118. ASSERT_TRUE(res);
  10119. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10120. cli.set_follow_location(true);
  10121. res = cli.Get("/");
  10122. ASSERT_TRUE(res);
  10123. EXPECT_EQ(StatusCode::OK_200, res->status);
  10124. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10125. }
  10126. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10127. Client cli("https://yahoo.com");
  10128. auto res = cli.Get("/");
  10129. ASSERT_TRUE(res);
  10130. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10131. cli.set_follow_location(true);
  10132. res = cli.Get("/");
  10133. ASSERT_TRUE(res);
  10134. EXPECT_EQ(StatusCode::OK_200, res->status);
  10135. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10136. }
  10137. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10138. Client cli("https://yahoo.com");
  10139. auto res = cli.Get("/");
  10140. ASSERT_TRUE(res);
  10141. ASSERT_FALSE(!res);
  10142. ASSERT_TRUE(res);
  10143. ASSERT_FALSE(res == nullptr);
  10144. ASSERT_TRUE(res != nullptr);
  10145. EXPECT_EQ(Error::Success, res.error());
  10146. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10147. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10148. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10149. cli.set_follow_location(true);
  10150. res = cli.Get("/");
  10151. ASSERT_TRUE(res);
  10152. EXPECT_EQ(Error::Success, res.error());
  10153. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10154. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10155. EXPECT_EQ(StatusCode::OK_200, res->status);
  10156. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10157. }
  10158. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10159. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10160. Client cli("https://cdnjs.cloudflare.com");
  10161. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10162. Headers{{"Accept-Encoding", "br"}});
  10163. ASSERT_TRUE(res);
  10164. EXPECT_EQ(StatusCode::OK_200, res->status);
  10165. EXPECT_EQ(287630U, res->body.size());
  10166. EXPECT_EQ("application/javascript; charset=utf-8",
  10167. res->get_header_value("Content-Type"));
  10168. }
  10169. #endif
  10170. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10171. #undef REDIR_HOST // Silence compiler warning
  10172. #define REDIR_HOST "https://httpbingo.org"
  10173. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10174. Client cli(REDIR_HOST);
  10175. cli.set_follow_location(true);
  10176. auto res =
  10177. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10178. ASSERT_TRUE(res);
  10179. EXPECT_EQ(StatusCode::OK_200, res->status);
  10180. }
  10181. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10182. Client cli(REDIR_HOST);
  10183. cli.set_follow_location(true);
  10184. Params params;
  10185. params.emplace("url", "http://example.com");
  10186. params.emplace("status_code", "302");
  10187. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10188. ASSERT_TRUE(res);
  10189. EXPECT_EQ(StatusCode::OK_200, res->status);
  10190. }
  10191. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10192. Client cli(REDIR_HOST);
  10193. cli.set_follow_location(true);
  10194. Params params;
  10195. params.emplace("url", "http://example.com");
  10196. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10197. ASSERT_TRUE(res);
  10198. EXPECT_EQ(StatusCode::OK_200, res->status);
  10199. }
  10200. TEST(HttpToHttpsRedirectTest, CertFile) {
  10201. auto ssl_port = PORT + 1;
  10202. Server svr;
  10203. ASSERT_TRUE(svr.is_valid());
  10204. svr.Get("/index", [&](const Request &, Response &res) {
  10205. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10206. "/index");
  10207. svr.stop();
  10208. });
  10209. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10210. ASSERT_TRUE(ssl_svr.is_valid());
  10211. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10212. res.set_content("test", "text/plain");
  10213. ssl_svr.stop();
  10214. });
  10215. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10216. thread t2 =
  10217. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10218. auto se = detail::scope_exit([&] {
  10219. t2.join();
  10220. t.join();
  10221. ASSERT_FALSE(svr.is_running());
  10222. });
  10223. svr.wait_until_ready();
  10224. ssl_svr.wait_until_ready();
  10225. Client cli("127.0.0.1", PORT);
  10226. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10227. cli.enable_server_certificate_verification(true);
  10228. cli.set_follow_location(true);
  10229. cli.set_connection_timeout(30);
  10230. auto res = cli.Get("/index");
  10231. ASSERT_TRUE(res);
  10232. ASSERT_EQ(StatusCode::OK_200, res->status);
  10233. }
  10234. TEST(SSLClientRedirectTest, CertFile) {
  10235. auto ssl_port = PORT + 1;
  10236. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10237. ASSERT_TRUE(ssl_svr1.is_valid());
  10238. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10239. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10240. "/index");
  10241. ssl_svr1.stop();
  10242. });
  10243. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10244. ASSERT_TRUE(ssl_svr2.is_valid());
  10245. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10246. res.set_content("test", "text/plain");
  10247. ssl_svr2.stop();
  10248. });
  10249. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10250. thread t2 =
  10251. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10252. auto se = detail::scope_exit([&] {
  10253. t2.join();
  10254. t.join();
  10255. ASSERT_FALSE(ssl_svr1.is_running());
  10256. });
  10257. ssl_svr1.wait_until_ready();
  10258. ssl_svr2.wait_until_ready();
  10259. SSLClient cli("127.0.0.1", PORT);
  10260. std::string cert;
  10261. read_file(SERVER_CERT2_FILE, cert);
  10262. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10263. cli.enable_server_certificate_verification(true);
  10264. cli.set_follow_location(true);
  10265. cli.set_connection_timeout(30);
  10266. auto res = cli.Get("/index");
  10267. ASSERT_TRUE(res);
  10268. ASSERT_EQ(StatusCode::OK_200, res->status);
  10269. }
  10270. #endif
  10271. #ifdef CPPHTTPLIB_SSL_ENABLED
  10272. // Test that set_ca_cert_store() skips system certs (consistent with
  10273. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10274. // should be trusted - system certs should NOT be loaded.
  10275. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10276. // Load a specific cert that is NOT a system CA cert
  10277. std::string cert;
  10278. read_file(SERVER_CERT2_FILE, cert);
  10279. SSLClient cli("google.com");
  10280. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10281. cli.enable_server_certificate_verification(true);
  10282. // This should FAIL because:
  10283. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10284. // 2. System certs should NOT be loaded when custom store is set
  10285. // If system certs WERE loaded, this would succeed
  10286. auto res = cli.Get("/");
  10287. ASSERT_FALSE(res);
  10288. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10289. }
  10290. // Same as above, but through the native store handle path. Regression test:
  10291. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10292. // merged system certs into the user-provided store.
  10293. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10294. std::string cert;
  10295. read_file(SERVER_CERT2_FILE, cert);
  10296. SSLClient cli("google.com");
  10297. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10298. cli.enable_server_certificate_verification(true);
  10299. auto res = cli.Get("/");
  10300. ASSERT_FALSE(res);
  10301. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10302. }
  10303. // A custom store set via the native handle must still verify a server whose
  10304. // cert it does contain.
  10305. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10306. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10307. ASSERT_TRUE(svr.is_valid());
  10308. svr.Get("/test", [&](const Request &, Response &res) {
  10309. res.set_content("test", "text/plain");
  10310. });
  10311. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10312. auto se = detail::scope_exit([&] {
  10313. svr.stop();
  10314. t.join();
  10315. ASSERT_FALSE(svr.is_running());
  10316. });
  10317. svr.wait_until_ready();
  10318. SSLClient cli("127.0.0.1", PORT);
  10319. std::string cert;
  10320. read_file(SERVER_CERT2_FILE, cert);
  10321. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10322. cli.enable_server_certificate_verification(true);
  10323. cli.set_connection_timeout(30);
  10324. auto res = cli.Get("/test");
  10325. ASSERT_TRUE(res);
  10326. ASSERT_EQ(StatusCode::OK_200, res->status);
  10327. }
  10328. // CA certs loaded through the universal Client must be transferred to the
  10329. // client created internally for following an HTTPS redirect. Regression test:
  10330. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10331. // the CA data for redirect transfer.
  10332. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10333. auto ssl_port = PORT + 1;
  10334. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10335. ASSERT_TRUE(ssl_svr1.is_valid());
  10336. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10337. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10338. "/index");
  10339. });
  10340. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10341. ASSERT_TRUE(ssl_svr2.is_valid());
  10342. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10343. res.set_content("test", "text/plain");
  10344. });
  10345. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10346. thread t2 =
  10347. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10348. auto se = detail::scope_exit([&] {
  10349. ssl_svr2.stop();
  10350. ssl_svr1.stop();
  10351. t2.join();
  10352. t.join();
  10353. ASSERT_FALSE(ssl_svr1.is_running());
  10354. });
  10355. ssl_svr1.wait_until_ready();
  10356. ssl_svr2.wait_until_ready();
  10357. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10358. std::string cert;
  10359. read_file(SERVER_CERT2_FILE, cert);
  10360. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10361. cli.enable_server_certificate_verification(true);
  10362. cli.set_follow_location(true);
  10363. cli.set_connection_timeout(30);
  10364. auto res = cli.Get("/index");
  10365. ASSERT_TRUE(res);
  10366. ASSERT_EQ(StatusCode::OK_200, res->status);
  10367. }
  10368. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10369. // so a host signed by a system CA verifies even though a custom CA is set
  10370. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10371. std::string cert;
  10372. read_file(SERVER_CERT2_FILE, cert);
  10373. SSLClient cli("google.com");
  10374. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10375. cli.enable_system_ca(true);
  10376. cli.enable_server_certificate_verification(true);
  10377. auto res = cli.Get("/");
  10378. ASSERT_TRUE(res);
  10379. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10380. }
  10381. // The custom CA remains effective when combined with the system CA
  10382. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10383. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10384. ASSERT_TRUE(svr.is_valid());
  10385. svr.Get("/test", [&](const Request &, Response &res) {
  10386. res.set_content("test", "text/plain");
  10387. });
  10388. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. t.join();
  10392. ASSERT_FALSE(svr.is_running());
  10393. });
  10394. svr.wait_until_ready();
  10395. SSLClient cli("127.0.0.1", PORT);
  10396. std::string cert;
  10397. read_file(SERVER_CERT2_FILE, cert);
  10398. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10399. cli.enable_system_ca(true);
  10400. cli.enable_server_certificate_verification(true);
  10401. cli.set_connection_timeout(30);
  10402. auto res = cli.Get("/test");
  10403. ASSERT_TRUE(res);
  10404. ASSERT_EQ(StatusCode::OK_200, res->status);
  10405. }
  10406. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10407. // skip chain verification entirely (only the certificate identity was
  10408. // checked), so a server presenting an untrusted certificate with a matching
  10409. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10410. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10411. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10412. ASSERT_TRUE(svr.is_valid());
  10413. svr.Get("/test", [&](const Request &, Response &res) {
  10414. res.set_content("test", "text/plain");
  10415. });
  10416. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10417. auto se = detail::scope_exit([&] {
  10418. svr.stop();
  10419. t.join();
  10420. ASSERT_FALSE(svr.is_running());
  10421. });
  10422. svr.wait_until_ready();
  10423. SSLClient cli("127.0.0.1", PORT);
  10424. std::string cert;
  10425. // A trusted CA that did not sign the server certificate. The server cert
  10426. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10427. // this connection.
  10428. read_file(CLIENT_CA_CERT_FILE, cert);
  10429. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10430. cli.enable_server_certificate_verification(true);
  10431. cli.set_connection_timeout(30);
  10432. auto res = cli.Get("/test");
  10433. ASSERT_FALSE(res);
  10434. }
  10435. // enable_system_ca(false) prevents system CA loading entirely
  10436. TEST(SSLClientTest, DisableSystemCa_Online) {
  10437. SSLClient cli("google.com");
  10438. cli.enable_system_ca(false);
  10439. cli.enable_server_certificate_verification(true);
  10440. auto res = cli.Get("/");
  10441. ASSERT_FALSE(res);
  10442. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10443. // itself when the CA chain is empty
  10444. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10445. res.error() == Error::SSLConnection);
  10446. }
  10447. // The universal Client forwards enable_system_ca()
  10448. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10449. std::string cert;
  10450. read_file(SERVER_CERT2_FILE, cert);
  10451. Client cli("https://google.com");
  10452. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10453. cli.enable_system_ca(true);
  10454. cli.enable_server_certificate_verification(true);
  10455. auto res = cli.Get("/");
  10456. ASSERT_TRUE(res);
  10457. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10458. }
  10459. // The system CA policy must carry over to the client created internally for
  10460. // following a cross-host HTTPS redirect
  10461. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10462. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10463. ASSERT_TRUE(svr.is_valid());
  10464. svr.Get("/index", [&](const Request &, Response &res) {
  10465. res.set_redirect("https://www.google.com/");
  10466. });
  10467. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10468. auto se = detail::scope_exit([&] {
  10469. svr.stop();
  10470. t.join();
  10471. ASSERT_FALSE(svr.is_running());
  10472. });
  10473. svr.wait_until_ready();
  10474. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10475. std::string cert;
  10476. read_file(SERVER_CERT2_FILE, cert);
  10477. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10478. cli.enable_system_ca(true);
  10479. cli.enable_server_certificate_verification(true);
  10480. cli.set_follow_location(true);
  10481. cli.set_connection_timeout(30);
  10482. // Receiving any response proves the redirect client completed the TLS
  10483. // handshake with a system-CA-signed host
  10484. auto res = cli.Get("/index");
  10485. ASSERT_TRUE(res);
  10486. }
  10487. TEST(MultipartFormDataTest, LargeData) {
  10488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10489. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10490. const ContentReader &content_reader) {
  10491. if (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. EXPECT_TRUE(std::string(items[0].name) == "document");
  10503. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10504. EXPECT_TRUE(items[0].filename == "2MB_data");
  10505. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10506. EXPECT_TRUE(items[1].name == "hello");
  10507. EXPECT_TRUE(items[1].content == "world");
  10508. EXPECT_TRUE(items[1].filename == "");
  10509. EXPECT_TRUE(items[1].content_type == "");
  10510. } else {
  10511. std::string body;
  10512. content_reader([&](const char *data, size_t data_length) {
  10513. body.append(data, data_length);
  10514. return true;
  10515. });
  10516. }
  10517. });
  10518. auto port = svr.bind_to_any_port(HOST);
  10519. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10520. auto se = detail::scope_exit([&] {
  10521. svr.stop();
  10522. t.join();
  10523. ASSERT_FALSE(svr.is_running());
  10524. });
  10525. svr.wait_until_ready();
  10526. {
  10527. std::string data(1024 * 1024 * 2, '.');
  10528. std::stringstream buffer;
  10529. buffer << data;
  10530. SSLClient cli(HOST, port);
  10531. cli.enable_server_certificate_verification(false);
  10532. UploadFormDataItems items{
  10533. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10534. {"hello", "world", "", ""},
  10535. };
  10536. auto res = cli.Post("/post", items);
  10537. ASSERT_TRUE(res);
  10538. ASSERT_EQ(StatusCode::OK_200, res->status);
  10539. }
  10540. }
  10541. TEST(MultipartFormDataTest, DataProviderItems) {
  10542. std::random_device seed_gen;
  10543. std::mt19937 random(seed_gen());
  10544. std::string rand1;
  10545. rand1.resize(1000);
  10546. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10547. std::string rand2;
  10548. rand2.resize(3000);
  10549. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10551. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10552. const ContentReader &content_reader) {
  10553. ASSERT_FALSE(req.is_multipart_form_data());
  10554. std::string body;
  10555. content_reader([&](const char *data, size_t data_length) {
  10556. body.append(data, data_length);
  10557. return true;
  10558. });
  10559. EXPECT_EQ(body, "");
  10560. });
  10561. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10562. const ContentReader &content_reader) {
  10563. ASSERT_TRUE(req.is_multipart_form_data());
  10564. std::vector<FormData> items;
  10565. content_reader(
  10566. [&](const FormData &file) {
  10567. items.push_back(file);
  10568. return true;
  10569. },
  10570. [&](const char *data, size_t data_length) {
  10571. items.back().content.append(data, data_length);
  10572. return true;
  10573. });
  10574. ASSERT_TRUE(items.size() == 2);
  10575. EXPECT_EQ(std::string(items[0].name), "name1");
  10576. EXPECT_EQ(items[0].content, "Testing123");
  10577. EXPECT_EQ(items[0].filename, "filename1");
  10578. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10579. EXPECT_EQ(items[1].name, "name2");
  10580. EXPECT_EQ(items[1].content, "Testing456");
  10581. EXPECT_EQ(items[1].filename, "");
  10582. EXPECT_EQ(items[1].content_type, "");
  10583. });
  10584. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10585. const ContentReader &content_reader) {
  10586. ASSERT_TRUE(req.is_multipart_form_data());
  10587. std::vector<FormData> items;
  10588. content_reader(
  10589. [&](const FormData &file) {
  10590. items.push_back(file);
  10591. return true;
  10592. },
  10593. [&](const char *data, size_t data_length) {
  10594. items.back().content.append(data, data_length);
  10595. return true;
  10596. });
  10597. ASSERT_TRUE(items.size() == 2);
  10598. EXPECT_EQ(items[0].name, "name3");
  10599. EXPECT_EQ(items[0].content, rand1);
  10600. EXPECT_EQ(items[0].filename, "filename3");
  10601. EXPECT_EQ(items[0].content_type, "");
  10602. EXPECT_EQ(items[1].name, "name4");
  10603. EXPECT_EQ(items[1].content, rand2);
  10604. EXPECT_EQ(items[1].filename, "filename4");
  10605. EXPECT_EQ(items[1].content_type, "");
  10606. });
  10607. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10608. const ContentReader &content_reader) {
  10609. ASSERT_TRUE(req.is_multipart_form_data());
  10610. std::vector<FormData> items;
  10611. content_reader(
  10612. [&](const FormData &file) {
  10613. items.push_back(file);
  10614. return true;
  10615. },
  10616. [&](const char *data, size_t data_length) {
  10617. items.back().content.append(data, data_length);
  10618. return true;
  10619. });
  10620. ASSERT_TRUE(items.size() == 4);
  10621. EXPECT_EQ(std::string(items[0].name), "name1");
  10622. EXPECT_EQ(items[0].content, "Testing123");
  10623. EXPECT_EQ(items[0].filename, "filename1");
  10624. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10625. EXPECT_EQ(items[1].name, "name2");
  10626. EXPECT_EQ(items[1].content, "Testing456");
  10627. EXPECT_EQ(items[1].filename, "");
  10628. EXPECT_EQ(items[1].content_type, "");
  10629. EXPECT_EQ(items[2].name, "name3");
  10630. EXPECT_EQ(items[2].content, rand1);
  10631. EXPECT_EQ(items[2].filename, "filename3");
  10632. EXPECT_EQ(items[2].content_type, "");
  10633. EXPECT_EQ(items[3].name, "name4");
  10634. EXPECT_EQ(items[3].content, rand2);
  10635. EXPECT_EQ(items[3].filename, "filename4");
  10636. EXPECT_EQ(items[3].content_type, "");
  10637. });
  10638. auto port = svr.bind_to_any_port("localhost");
  10639. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10640. auto se = detail::scope_exit([&] {
  10641. svr.stop();
  10642. t.join();
  10643. ASSERT_FALSE(svr.is_running());
  10644. });
  10645. svr.wait_until_ready();
  10646. {
  10647. SSLClient cli("localhost", port);
  10648. cli.enable_server_certificate_verification(false);
  10649. UploadFormDataItems items{
  10650. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10651. {"name2", "Testing456", "", ""}, // not a file
  10652. };
  10653. {
  10654. auto res = cli.Post("/post-none", {}, {}, {});
  10655. ASSERT_TRUE(res);
  10656. ASSERT_EQ(StatusCode::OK_200, res->status);
  10657. }
  10658. FormDataProviderItems providers;
  10659. {
  10660. auto res =
  10661. cli.Post("/post-items", {}, items, providers); // empty providers
  10662. ASSERT_TRUE(res);
  10663. ASSERT_EQ(StatusCode::OK_200, res->status);
  10664. }
  10665. providers.push_back({"name3",
  10666. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10667. // test the offset is given correctly at each step
  10668. if (!offset)
  10669. sink.os.write(rand1.data(), 30);
  10670. else if (offset == 30)
  10671. sink.os.write(rand1.data() + 30, 300);
  10672. else if (offset == 330)
  10673. sink.os.write(rand1.data() + 330, 670);
  10674. else if (offset == rand1.size())
  10675. sink.done();
  10676. return true;
  10677. },
  10678. "filename3",
  10679. {}});
  10680. providers.push_back({"name4",
  10681. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10682. // test the offset is given correctly at each step
  10683. if (!offset)
  10684. sink.os.write(rand2.data(), 2000);
  10685. else if (offset == 2000)
  10686. sink.os.write(rand2.data() + 2000, 1);
  10687. else if (offset == 2001)
  10688. sink.os.write(rand2.data() + 2001, 999);
  10689. else if (offset == rand2.size())
  10690. sink.done();
  10691. return true;
  10692. },
  10693. "filename4",
  10694. {}});
  10695. {
  10696. auto res = cli.Post("/post-providers", {}, {}, providers);
  10697. ASSERT_TRUE(res);
  10698. ASSERT_EQ(StatusCode::OK_200, res->status);
  10699. }
  10700. {
  10701. auto res = cli.Post("/post-both", {}, items, providers);
  10702. ASSERT_TRUE(res);
  10703. ASSERT_EQ(StatusCode::OK_200, res->status);
  10704. }
  10705. }
  10706. }
  10707. TEST(MultipartFormDataTest, BadHeader) {
  10708. Server svr;
  10709. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10710. res.set_content("ok", "text/plain");
  10711. });
  10712. thread t = thread([&] { svr.listen(HOST, PORT); });
  10713. auto se = detail::scope_exit([&] {
  10714. svr.stop();
  10715. t.join();
  10716. ASSERT_FALSE(svr.is_running());
  10717. });
  10718. svr.wait_until_ready();
  10719. const std::string body =
  10720. "This is the preamble. It is to be ignored, though it\r\n"
  10721. "is a handy place for composition agents to include an\r\n"
  10722. "explanatory note to non-MIME conformant readers.\r\n"
  10723. "\r\n"
  10724. "\r\n"
  10725. "--simple boundary\r\n"
  10726. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10727. ": BAD...\r\n"
  10728. "\r\n"
  10729. "value1\r\n"
  10730. "--simple boundary\r\n"
  10731. "Content-Disposition: form-data; name=\"field2\"; "
  10732. "filename=\"example.txt\"\r\n"
  10733. "\r\n"
  10734. "value2\r\n"
  10735. "--simple boundary--\r\n"
  10736. "This is the epilogue. It is also to be ignored.\r\n";
  10737. std::string content_type =
  10738. R"(multipart/form-data; boundary="simple boundary")";
  10739. Client cli(HOST, PORT);
  10740. auto res = cli.Post("/post", body, content_type.c_str());
  10741. ASSERT_TRUE(res);
  10742. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10743. }
  10744. TEST(MultipartFormDataTest, WithPreamble) {
  10745. Server svr;
  10746. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10747. res.set_content("ok", "text/plain");
  10748. });
  10749. thread t = thread([&] { svr.listen(HOST, PORT); });
  10750. auto se = detail::scope_exit([&] {
  10751. svr.stop();
  10752. t.join();
  10753. ASSERT_FALSE(svr.is_running());
  10754. });
  10755. svr.wait_until_ready();
  10756. const std::string body =
  10757. "This is the preamble. It is to be ignored, though it\r\n"
  10758. "is a handy place for composition agents to include an\r\n"
  10759. "explanatory note to non-MIME conformant readers.\r\n"
  10760. "\r\n"
  10761. "\r\n"
  10762. "--simple boundary\r\n"
  10763. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10764. "\r\n"
  10765. "value1\r\n"
  10766. "--simple boundary\r\n"
  10767. "Content-Disposition: form-data; name=\"field2\"; "
  10768. "filename=\"example.txt\"\r\n"
  10769. "\r\n"
  10770. "value2\r\n"
  10771. "--simple boundary--\r\n"
  10772. "This is the epilogue. It is also to be ignored.\r\n";
  10773. std::string content_type =
  10774. R"(multipart/form-data; boundary="simple boundary")";
  10775. Client cli(HOST, PORT);
  10776. auto res = cli.Post("/post", body, content_type.c_str());
  10777. ASSERT_TRUE(res);
  10778. EXPECT_EQ(StatusCode::OK_200, res->status);
  10779. }
  10780. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10782. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10783. const ContentReader &content_reader) {
  10784. if (req.is_multipart_form_data()) {
  10785. std::vector<FormData> items;
  10786. content_reader(
  10787. [&](const FormData &file) {
  10788. items.push_back(file);
  10789. return true;
  10790. },
  10791. [&](const char *data, size_t data_length) {
  10792. items.back().content.append(data, data_length);
  10793. return true;
  10794. });
  10795. EXPECT_TRUE(std::string(items[0].name) == "document");
  10796. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10797. EXPECT_TRUE(items[0].filename == "2MB_data");
  10798. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10799. EXPECT_TRUE(items[1].name == "hello");
  10800. EXPECT_TRUE(items[1].content == "world");
  10801. EXPECT_TRUE(items[1].filename == "");
  10802. EXPECT_TRUE(items[1].content_type == "");
  10803. } else {
  10804. std::string body;
  10805. content_reader([&](const char *data, size_t data_length) {
  10806. body.append(data, data_length);
  10807. return true;
  10808. });
  10809. }
  10810. });
  10811. auto port = svr.bind_to_any_port("localhost");
  10812. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10813. auto se = detail::scope_exit([&] {
  10814. svr.stop();
  10815. t.join();
  10816. ASSERT_FALSE(svr.is_running());
  10817. });
  10818. svr.wait_until_ready();
  10819. {
  10820. std::string data(1024 * 1024 * 2, '.');
  10821. std::stringstream buffer;
  10822. buffer << data;
  10823. SSLClient cli("localhost", port);
  10824. cli.enable_server_certificate_verification(false);
  10825. UploadFormDataItems items{
  10826. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10827. {"hello", "world", "", ""},
  10828. };
  10829. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10830. ASSERT_TRUE(res);
  10831. ASSERT_EQ(StatusCode::OK_200, res->status);
  10832. }
  10833. }
  10834. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10835. std::string data(1024 * 1024 * 2, '&');
  10836. std::stringstream buffer;
  10837. buffer << data;
  10838. Client cli("https://localhost:8080");
  10839. UploadFormDataItems items{
  10840. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10841. {"hello", "world", "", ""},
  10842. };
  10843. for (const char &c : " \t\r\n") {
  10844. auto res =
  10845. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10846. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10847. ASSERT_FALSE(res);
  10848. }
  10849. }
  10850. TEST(MultipartFormDataTest, PutFormData) {
  10851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10852. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10853. const ContentReader &content_reader) {
  10854. if (req.is_multipart_form_data()) {
  10855. std::vector<FormData> items;
  10856. content_reader(
  10857. [&](const FormData &file) {
  10858. items.push_back(file);
  10859. return true;
  10860. },
  10861. [&](const char *data, size_t data_length) {
  10862. items.back().content.append(data, data_length);
  10863. return true;
  10864. });
  10865. EXPECT_TRUE(std::string(items[0].name) == "document");
  10866. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10867. EXPECT_TRUE(items[0].filename == "2MB_data");
  10868. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10869. EXPECT_TRUE(items[1].name == "hello");
  10870. EXPECT_TRUE(items[1].content == "world");
  10871. EXPECT_TRUE(items[1].filename == "");
  10872. EXPECT_TRUE(items[1].content_type == "");
  10873. } else {
  10874. std::string body;
  10875. content_reader([&](const char *data, size_t data_length) {
  10876. body.append(data, data_length);
  10877. return true;
  10878. });
  10879. }
  10880. });
  10881. auto port = svr.bind_to_any_port("localhost");
  10882. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. t.join();
  10886. ASSERT_FALSE(svr.is_running());
  10887. });
  10888. svr.wait_until_ready();
  10889. {
  10890. std::string data(1024 * 1024 * 2, '&');
  10891. std::stringstream buffer;
  10892. buffer << data;
  10893. SSLClient cli("localhost", port);
  10894. cli.enable_server_certificate_verification(false);
  10895. UploadFormDataItems items{
  10896. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10897. {"hello", "world", "", ""},
  10898. };
  10899. auto res = cli.Put("/put", items);
  10900. ASSERT_TRUE(res);
  10901. ASSERT_EQ(StatusCode::OK_200, res->status);
  10902. }
  10903. }
  10904. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10906. svr.Put("/put_customboundary",
  10907. [&](const Request &req, const Response & /*res*/,
  10908. const ContentReader &content_reader) {
  10909. if (req.is_multipart_form_data()) {
  10910. std::vector<FormData> items;
  10911. content_reader(
  10912. [&](const FormData &file) {
  10913. items.push_back(file);
  10914. return true;
  10915. },
  10916. [&](const char *data, size_t data_length) {
  10917. items.back().content.append(data, data_length);
  10918. return true;
  10919. });
  10920. EXPECT_TRUE(std::string(items[0].name) == "document");
  10921. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10922. EXPECT_TRUE(items[0].filename == "2MB_data");
  10923. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10924. EXPECT_TRUE(items[1].name == "hello");
  10925. EXPECT_TRUE(items[1].content == "world");
  10926. EXPECT_TRUE(items[1].filename == "");
  10927. EXPECT_TRUE(items[1].content_type == "");
  10928. } else {
  10929. std::string body;
  10930. content_reader([&](const char *data, size_t data_length) {
  10931. body.append(data, data_length);
  10932. return true;
  10933. });
  10934. }
  10935. });
  10936. auto port = svr.bind_to_any_port("localhost");
  10937. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. t.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. {
  10945. std::string data(1024 * 1024 * 2, '&');
  10946. std::stringstream buffer;
  10947. buffer << data;
  10948. SSLClient cli("localhost", port);
  10949. cli.enable_server_certificate_verification(false);
  10950. UploadFormDataItems items{
  10951. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10952. {"hello", "world", "", ""},
  10953. };
  10954. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10955. ASSERT_TRUE(res);
  10956. ASSERT_EQ(StatusCode::OK_200, res->status);
  10957. }
  10958. }
  10959. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10960. std::string data(1024 * 1024 * 2, '&');
  10961. std::stringstream buffer;
  10962. buffer << data;
  10963. Client cli("https://localhost:8080");
  10964. cli.enable_server_certificate_verification(false);
  10965. UploadFormDataItems items{
  10966. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10967. {"hello", "world", "", ""},
  10968. };
  10969. for (const char &c : " \t\r\n") {
  10970. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10971. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10972. ASSERT_FALSE(res);
  10973. }
  10974. }
  10975. TEST(MultipartFormDataTest, AlternateFilename) {
  10976. auto handled = false;
  10977. Server svr;
  10978. svr.Post("/test", [&](const Request &req, Response &res) {
  10979. ASSERT_EQ(2u, req.form.files.size());
  10980. ASSERT_EQ(1u, req.form.fields.size());
  10981. // Test files
  10982. const auto &file1 = req.form.get_file("file1");
  10983. ASSERT_EQ("file1", file1.name);
  10984. ASSERT_EQ("A.txt", file1.filename);
  10985. ASSERT_EQ("text/plain", file1.content_type);
  10986. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10987. const auto &file2 = req.form.get_file("file2");
  10988. ASSERT_EQ("file2", file2.name);
  10989. ASSERT_EQ("a.html", file2.filename);
  10990. ASSERT_EQ("text/html", file2.content_type);
  10991. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10992. file2.content);
  10993. // Test text field
  10994. const auto &text = req.form.get_field("text");
  10995. ASSERT_EQ("text default", text);
  10996. res.set_content("ok", "text/plain");
  10997. handled = true;
  10998. });
  10999. thread t = thread([&] { svr.listen(HOST, PORT); });
  11000. auto se = detail::scope_exit([&] {
  11001. svr.stop();
  11002. t.join();
  11003. ASSERT_FALSE(svr.is_running());
  11004. ASSERT_TRUE(handled);
  11005. });
  11006. svr.wait_until_ready();
  11007. auto req = "POST /test HTTP/1.1\r\n"
  11008. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11009. "Content-Length: 399\r\n"
  11010. "\r\n"
  11011. "----------\r\n"
  11012. "Content-Disposition: form-data; name=\"text\"\r\n"
  11013. "\r\n"
  11014. "text default\r\n"
  11015. "----------\r\n"
  11016. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11017. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11018. "Content-Type: text/plain\r\n"
  11019. "\r\n"
  11020. "Content of a.txt.\r\n"
  11021. "\r\n"
  11022. "----------\r\n"
  11023. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11024. "\"a.html\"\r\n"
  11025. "Content-Type: text/html\r\n"
  11026. "\r\n"
  11027. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11028. "\r\n"
  11029. "------------\r\n";
  11030. ASSERT_TRUE(send_request(1, req));
  11031. }
  11032. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11033. auto handled = false;
  11034. Server svr;
  11035. svr.Post("/test", [&](const Request &req, Response &res) {
  11036. // Case-insensitive "utf-8''" prefix with a long value
  11037. const auto &file = req.form.get_file("file1");
  11038. ASSERT_EQ("file1", file.name);
  11039. // 8000 chars exercises both the Content-Disposition parser and the
  11040. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11041. // Prior to the fix, std::regex_match on this header would cause O(N)
  11042. // stack recursion in libstdc++, leading to SIGSEGV.
  11043. std::string expected_filename(8000, 'A');
  11044. ASSERT_EQ(expected_filename, file.filename);
  11045. res.set_content("ok", "text/plain");
  11046. handled = true;
  11047. });
  11048. thread t = thread([&] { svr.listen(HOST, PORT); });
  11049. auto se = detail::scope_exit([&] {
  11050. svr.stop();
  11051. t.join();
  11052. ASSERT_FALSE(svr.is_running());
  11053. ASSERT_TRUE(handled);
  11054. });
  11055. svr.wait_until_ready();
  11056. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11057. // Regression test for GHSA-qq6v-r583-3h69
  11058. std::string long_filename(8000, 'A');
  11059. std::string body = "----------\r\n"
  11060. "Content-Disposition: form-data; name=\"file1\"; "
  11061. "filename*=\"Utf-8''" +
  11062. long_filename +
  11063. "\"\r\n"
  11064. "\r\n"
  11065. "hello\r\n"
  11066. "------------\r\n";
  11067. auto req = "POST /test HTTP/1.1\r\n"
  11068. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11069. "Content-Length: " +
  11070. std::to_string(body.size()) + "\r\n\r\n" + body;
  11071. ASSERT_TRUE(send_request(1, req));
  11072. }
  11073. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11074. auto handled = false;
  11075. Server svr;
  11076. svr.Post("/test", [&](const Request &req, Response &) {
  11077. ASSERT_EQ(2u, req.form.fields.size());
  11078. const auto &text1 = req.form.get_field("text1");
  11079. ASSERT_EQ("text1", text1);
  11080. const auto &text2 = req.form.get_field("text2");
  11081. ASSERT_EQ("text2", text2);
  11082. handled = true;
  11083. });
  11084. thread t = thread([&] { svr.listen(HOST, PORT); });
  11085. auto se = detail::scope_exit([&] {
  11086. svr.stop();
  11087. t.join();
  11088. ASSERT_FALSE(svr.is_running());
  11089. ASSERT_TRUE(handled);
  11090. });
  11091. svr.wait_until_ready();
  11092. auto req = "POST /test HTTP/1.1\r\n"
  11093. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11094. "Content-Length: 146\r\n"
  11095. "\r\n----------\r\n"
  11096. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11097. "\r\n"
  11098. "text1"
  11099. "\r\n----------\r\n"
  11100. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11101. "\r\n"
  11102. "text2"
  11103. "\r\n------------";
  11104. std::string response;
  11105. ASSERT_TRUE(send_request(1, req, &response));
  11106. ASSERT_EQ("200", response.substr(9, 3));
  11107. }
  11108. TEST(MultipartFormDataTest, ContentLength) {
  11109. auto handled = false;
  11110. Server svr;
  11111. svr.Post("/test", [&](const Request &req, Response &) {
  11112. ASSERT_EQ(2u, req.form.fields.size());
  11113. const auto &text1 = req.form.get_field("text1");
  11114. ASSERT_EQ("text1", text1);
  11115. const auto &text2 = req.form.get_field("text2");
  11116. ASSERT_EQ("text2", text2);
  11117. handled = true;
  11118. });
  11119. thread t = thread([&] { svr.listen(HOST, PORT); });
  11120. auto se = detail::scope_exit([&] {
  11121. svr.stop();
  11122. t.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. ASSERT_TRUE(handled);
  11125. });
  11126. svr.wait_until_ready();
  11127. auto req = "POST /test HTTP/1.1\r\n"
  11128. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11129. "Content-Length: 167\r\n"
  11130. "\r\n----------\r\n"
  11131. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11132. "Content-Length: 5\r\n"
  11133. "\r\n"
  11134. "text1"
  11135. "\r\n----------\r\n"
  11136. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11137. "\r\n"
  11138. "text2"
  11139. "\r\n------------\r\n";
  11140. std::string response;
  11141. ASSERT_TRUE(send_request(1, req, &response));
  11142. ASSERT_EQ("200", response.substr(9, 3));
  11143. }
  11144. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11145. auto handled = false;
  11146. Server svr;
  11147. svr.Post("/test", [&](const Request &req, Response &) {
  11148. ASSERT_EQ(2u, req.form.fields.size());
  11149. const auto &text1 = req.form.get_field("text1");
  11150. ASSERT_EQ("text1", text1);
  11151. // TODO: Add header access for text fields if needed
  11152. const auto &text2 = req.form.get_field("text2");
  11153. ASSERT_EQ("text2", text2);
  11154. // TODO: Header access for text fields needs to be implemented
  11155. // auto &headers = it->second.headers;
  11156. // ASSERT_EQ(3U, headers.size());
  11157. // auto custom_header = headers.find("x-whatever");
  11158. // ASSERT_TRUE(custom_header != headers.end());
  11159. // ASSERT_NE("customvalue", custom_header->second);
  11160. // ASSERT_EQ("CustomValue", custom_header->second);
  11161. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11162. handled = true;
  11163. });
  11164. thread t = thread([&] { svr.listen(HOST, PORT); });
  11165. auto se = detail::scope_exit([&] {
  11166. svr.stop();
  11167. t.join();
  11168. ASSERT_FALSE(svr.is_running());
  11169. ASSERT_TRUE(handled);
  11170. });
  11171. svr.wait_until_ready();
  11172. auto req = "POST /test HTTP/1.1\r\n"
  11173. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11174. "Content-Length: 232\r\n"
  11175. "\r\n----------\r\n"
  11176. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11177. "Content-Length: 5\r\n"
  11178. "X-Test: 1\r\n"
  11179. "\r\n"
  11180. "text1"
  11181. "\r\n----------\r\n"
  11182. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11183. "Content-Type: text/plain\r\n"
  11184. "X-Whatever: CustomValue\r\n"
  11185. "\r\n"
  11186. "text2"
  11187. "\r\n------------\r\n"
  11188. "That should be disregarded. Not even read";
  11189. std::string response;
  11190. ASSERT_TRUE(send_request(1, req, &response));
  11191. ASSERT_EQ("200", response.substr(9, 3));
  11192. }
  11193. TEST(MultipartFormDataTest, LargeHeader) {
  11194. auto handled = false;
  11195. Server svr;
  11196. svr.Post("/test", [&](const Request &req, Response &) {
  11197. ASSERT_EQ(1u, req.form.fields.size());
  11198. const auto &text = req.form.get_field("name1");
  11199. ASSERT_EQ("text1", text);
  11200. handled = true;
  11201. });
  11202. thread t = thread([&] { svr.listen(HOST, PORT); });
  11203. auto se = detail::scope_exit([&] {
  11204. svr.stop();
  11205. t.join();
  11206. ASSERT_FALSE(svr.is_running());
  11207. ASSERT_TRUE(handled);
  11208. });
  11209. svr.wait_until_ready();
  11210. auto boundary = std::string("cpp-httplib-multipart-data");
  11211. std::string content = "--" + boundary +
  11212. "\r\n"
  11213. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11214. "\r\n"
  11215. "text1\r\n"
  11216. "--" +
  11217. boundary + "--\r\n";
  11218. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11219. "Content-Type: multipart/form-data;boundary=" +
  11220. boundary +
  11221. "\r\n"
  11222. "Content-Length: " +
  11223. std::to_string(content.size()) +
  11224. "\r\n"
  11225. "Dummy-Header: ";
  11226. std::string header_suffix = "\r\n"
  11227. "\r\n";
  11228. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11229. size_t header_dummy_size =
  11230. read_buff_size -
  11231. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11232. auto header_dummy = std::string(header_dummy_size, '@');
  11233. auto req = header_prefix + header_dummy + header_suffix + content;
  11234. std::string response;
  11235. ASSERT_TRUE(send_request(1, req, &response));
  11236. ASSERT_EQ("200", response.substr(9, 3));
  11237. }
  11238. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11239. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11240. // (not chunked Transfer-Encoding) after the streaming refactor.
  11241. auto handled = false;
  11242. Server svr;
  11243. svr.Post("/upload", [&](const Request &req, Response &res) {
  11244. auto cl_it = req.headers.find("Content-Length");
  11245. EXPECT_TRUE(cl_it != req.headers.end());
  11246. auto te_it = req.headers.find("Transfer-Encoding");
  11247. EXPECT_TRUE(te_it == req.headers.end());
  11248. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11249. res.set_content("ok", "text/plain");
  11250. handled = true;
  11251. });
  11252. auto port = svr.bind_to_any_port(HOST);
  11253. auto t = thread([&] { svr.listen_after_bind(); });
  11254. auto se = detail::scope_exit([&] {
  11255. svr.stop();
  11256. t.join();
  11257. ASSERT_FALSE(svr.is_running());
  11258. ASSERT_TRUE(handled);
  11259. });
  11260. svr.wait_until_ready();
  11261. UploadFormDataItems items = {
  11262. {"field1", "hello", "", "text/plain"},
  11263. {"file1", "world", "test.txt", "application/octet-stream"},
  11264. };
  11265. Client cli(HOST, port);
  11266. auto res = cli.Post("/upload", {}, items);
  11267. ASSERT_TRUE(res);
  11268. EXPECT_EQ(StatusCode::OK_200, res->status);
  11269. }
  11270. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11271. // Verify that make_multipart_content_provider coalesces many small segments
  11272. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11273. constexpr size_t kItemCount = 1000;
  11274. UploadFormDataItems items;
  11275. items.reserve(kItemCount);
  11276. for (size_t i = 0; i < kItemCount; i++) {
  11277. items.push_back(
  11278. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11279. }
  11280. const std::string boundary = "----test-boundary";
  11281. auto content_length = detail::get_multipart_content_length(items, boundary);
  11282. auto provider = detail::make_multipart_content_provider(items, boundary);
  11283. // Drive the provider the same way write_content_with_progress does
  11284. size_t write_count = 0;
  11285. size_t total_bytes = 0;
  11286. DataSink sink;
  11287. size_t offset = 0;
  11288. sink.write = [&](const char *d, size_t l) -> bool {
  11289. (void)d;
  11290. write_count++;
  11291. total_bytes += l;
  11292. offset += l;
  11293. return true;
  11294. };
  11295. sink.is_writable = []() -> bool { return true; };
  11296. while (offset < content_length) {
  11297. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11298. }
  11299. EXPECT_EQ(content_length, total_bytes);
  11300. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11301. // With buffering into 64KB blocks, write_count should be much smaller.
  11302. auto segment_count = 3 * kItemCount + 1;
  11303. EXPECT_LT(write_count, segment_count / 10);
  11304. }
  11305. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11306. // Integration test: send many UploadFormDataItems and verify the server
  11307. // receives all of them correctly (#2410).
  11308. constexpr size_t kItemCount = 500;
  11309. auto handled = false;
  11310. Server svr;
  11311. svr.Post("/upload", [&](const Request &req, Response &res) {
  11312. EXPECT_EQ(kItemCount, req.form.fields.size());
  11313. for (size_t i = 0; i < kItemCount; i++) {
  11314. auto key = "field" + std::to_string(i);
  11315. auto val = "value" + std::to_string(i);
  11316. auto it = req.form.fields.find(key);
  11317. if (it != req.form.fields.end()) {
  11318. EXPECT_EQ(val, it->second.content);
  11319. } else {
  11320. ADD_FAILURE() << "Missing field: " << key;
  11321. }
  11322. }
  11323. res.set_content("ok", "text/plain");
  11324. handled = true;
  11325. });
  11326. auto port = svr.bind_to_any_port(HOST);
  11327. auto t = thread([&] { svr.listen_after_bind(); });
  11328. auto se = detail::scope_exit([&] {
  11329. svr.stop();
  11330. t.join();
  11331. ASSERT_FALSE(svr.is_running());
  11332. ASSERT_TRUE(handled);
  11333. });
  11334. svr.wait_until_ready();
  11335. UploadFormDataItems items;
  11336. items.reserve(kItemCount);
  11337. for (size_t i = 0; i < kItemCount; i++) {
  11338. items.push_back(
  11339. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11340. }
  11341. Client cli(HOST, port);
  11342. auto res = cli.Post("/upload", items);
  11343. ASSERT_TRUE(res);
  11344. EXPECT_EQ(StatusCode::OK_200, res->status);
  11345. }
  11346. TEST(MultipartFormDataTest, MakeFileProvider) {
  11347. // Verify make_file_provider sends a file's contents correctly.
  11348. const std::string file_content(4096, 'Z');
  11349. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11350. {
  11351. std::ofstream ofs(tmp_path, std::ios::binary);
  11352. ofs.write(file_content.data(),
  11353. static_cast<std::streamsize>(file_content.size()));
  11354. }
  11355. auto handled = false;
  11356. Server svr;
  11357. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11358. const ContentReader &content_reader) {
  11359. ASSERT_TRUE(req.is_multipart_form_data());
  11360. std::vector<FormData> items;
  11361. content_reader(
  11362. [&](const FormData &file) {
  11363. items.push_back(file);
  11364. return true;
  11365. },
  11366. [&](const char *data, size_t data_length) {
  11367. items.back().content.append(data, data_length);
  11368. return true;
  11369. });
  11370. ASSERT_EQ(1u, items.size());
  11371. EXPECT_EQ("myfile", items[0].name);
  11372. EXPECT_EQ("data.bin", items[0].filename);
  11373. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11374. EXPECT_EQ(file_content, items[0].content);
  11375. handled = true;
  11376. });
  11377. auto port = svr.bind_to_any_port(HOST);
  11378. auto t = thread([&] { svr.listen_after_bind(); });
  11379. auto se = detail::scope_exit([&] {
  11380. svr.stop();
  11381. t.join();
  11382. ASSERT_FALSE(svr.is_running());
  11383. ASSERT_TRUE(handled);
  11384. std::remove(tmp_path.c_str());
  11385. });
  11386. svr.wait_until_ready();
  11387. FormDataProviderItems providers;
  11388. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11389. "application/octet-stream"));
  11390. Client cli(HOST, port);
  11391. auto res = cli.Post("/upload", {}, {}, providers);
  11392. ASSERT_TRUE(res);
  11393. EXPECT_EQ(StatusCode::OK_200, res->status);
  11394. }
  11395. TEST(MakeFileBodyTest, Basic) {
  11396. const std::string file_content(4096, 'Z');
  11397. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11398. {
  11399. std::ofstream ofs(tmp_path, std::ios::binary);
  11400. ofs.write(file_content.data(),
  11401. static_cast<std::streamsize>(file_content.size()));
  11402. }
  11403. auto handled = false;
  11404. Server svr;
  11405. svr.Post("/upload", [&](const Request &req, Response &res) {
  11406. EXPECT_EQ(file_content, req.body);
  11407. handled = true;
  11408. res.status = StatusCode::OK_200;
  11409. });
  11410. auto port = svr.bind_to_any_port(HOST);
  11411. auto t = thread([&] { svr.listen_after_bind(); });
  11412. auto se = detail::scope_exit([&] {
  11413. svr.stop();
  11414. t.join();
  11415. ASSERT_FALSE(svr.is_running());
  11416. ASSERT_TRUE(handled);
  11417. std::remove(tmp_path.c_str());
  11418. });
  11419. svr.wait_until_ready();
  11420. auto fb = make_file_body(tmp_path);
  11421. ASSERT_GT(fb.first, 0u);
  11422. Client cli(HOST, port);
  11423. auto res =
  11424. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11425. ASSERT_TRUE(res);
  11426. EXPECT_EQ(StatusCode::OK_200, res->status);
  11427. }
  11428. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11429. static constexpr unsigned int number_of_tasks{1000000};
  11430. std::atomic_uint count{0};
  11431. std::unique_ptr<TaskQueue> task_queue{
  11432. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11433. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11434. auto queued = task_queue->enqueue(
  11435. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11436. EXPECT_TRUE(queued);
  11437. }
  11438. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11439. task_queue->shutdown();
  11440. #else
  11441. EXPECT_NO_THROW(task_queue->shutdown());
  11442. #endif
  11443. EXPECT_EQ(number_of_tasks, count.load());
  11444. }
  11445. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11446. static constexpr unsigned int number_of_tasks{1000000};
  11447. static constexpr unsigned int qlimit{2};
  11448. unsigned int queued_count{0};
  11449. std::atomic_uint count{0};
  11450. std::unique_ptr<TaskQueue> task_queue{
  11451. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11452. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11453. if (task_queue->enqueue(
  11454. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11455. queued_count++;
  11456. }
  11457. }
  11458. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11459. task_queue->shutdown();
  11460. #else
  11461. EXPECT_NO_THROW(task_queue->shutdown());
  11462. #endif
  11463. EXPECT_EQ(queued_count, count.load());
  11464. EXPECT_TRUE(queued_count <= number_of_tasks);
  11465. EXPECT_TRUE(queued_count >= qlimit);
  11466. }
  11467. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11468. // Use a short idle timeout so a dynamic thread spawns, times out and
  11469. // exits during the test, and the pool keeps working afterwards.
  11470. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11471. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11472. /*idle_timeout_sec=*/1}};
  11473. std::atomic_uint count{0};
  11474. std::condition_variable cv;
  11475. std::mutex mtx;
  11476. bool release = false;
  11477. // Block the base thread so the second task spawns a dynamic thread.
  11478. EXPECT_TRUE(task_queue->enqueue([&] {
  11479. std::unique_lock<std::mutex> lock(mtx);
  11480. while (!release) {
  11481. cv.wait(lock);
  11482. }
  11483. count++;
  11484. }));
  11485. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11486. // Let the dynamic thread finish its task and exceed the idle timeout.
  11487. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11488. {
  11489. std::unique_lock<std::mutex> lock(mtx);
  11490. release = true;
  11491. }
  11492. cv.notify_all();
  11493. // The pool must still accept and run tasks after the dynamic thread exited.
  11494. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11495. task_queue->shutdown();
  11496. EXPECT_EQ(3u, count.load());
  11497. }
  11498. TEST(TaskQueueTest, MaxQueuedRequests) {
  11499. static constexpr unsigned int qlimit{3};
  11500. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11501. std::condition_variable sem_cv;
  11502. std::mutex sem_mtx;
  11503. int credits = 0;
  11504. bool queued;
  11505. /* Fill up the queue with tasks that will block until we give them credits to
  11506. * complete. */
  11507. for (unsigned int n = 0; n <= qlimit;) {
  11508. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11509. std::unique_lock<std::mutex> lock(sem_mtx);
  11510. while (credits <= 0) {
  11511. sem_cv.wait(lock);
  11512. }
  11513. /* Consume the credit and signal the test code if they are all gone. */
  11514. if (--credits == 0) { sem_cv.notify_one(); }
  11515. });
  11516. if (n < qlimit) {
  11517. /* The first qlimit enqueues must succeed. */
  11518. EXPECT_TRUE(queued);
  11519. } else {
  11520. /* The last one will succeed only when the worker thread
  11521. * starts and dequeues the first blocking task. Although
  11522. * not necessary for the correctness of this test, we sleep for
  11523. * a short while to avoid busy waiting. */
  11524. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11525. }
  11526. if (queued) { n++; }
  11527. }
  11528. /* Further enqueues must fail since the queue is full. */
  11529. for (auto i = 0; i < 4; i++) {
  11530. queued = task_queue->enqueue([] {});
  11531. EXPECT_FALSE(queued);
  11532. }
  11533. /* Give the credits to allow the previous tasks to complete. */
  11534. {
  11535. std::unique_lock<std::mutex> lock(sem_mtx);
  11536. credits += qlimit + 1;
  11537. }
  11538. sem_cv.notify_all();
  11539. /* Wait for all the credits to be consumed. */
  11540. {
  11541. std::unique_lock<std::mutex> lock(sem_mtx);
  11542. while (credits > 0) {
  11543. sem_cv.wait(lock);
  11544. }
  11545. }
  11546. /* Check that we are able again to enqueue at least qlimit tasks. */
  11547. for (unsigned int i = 0; i < qlimit; i++) {
  11548. queued = task_queue->enqueue([] {});
  11549. EXPECT_TRUE(queued);
  11550. }
  11551. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11552. task_queue->shutdown();
  11553. #else
  11554. EXPECT_NO_THROW(task_queue->shutdown());
  11555. #endif
  11556. }
  11557. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11558. Server svr;
  11559. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11560. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11561. });
  11562. svr.Get("/hello", [](const Request &req, Response &res) {
  11563. res.set_content(req.get_param_value("key"), "text/plain");
  11564. });
  11565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11566. auto se = detail::scope_exit([&] {
  11567. svr.stop();
  11568. thread.join();
  11569. ASSERT_FALSE(svr.is_running());
  11570. });
  11571. svr.wait_until_ready();
  11572. {
  11573. Client cli(HOST, PORT);
  11574. cli.set_follow_location(true);
  11575. auto res = cli.Get("/");
  11576. ASSERT_TRUE(res);
  11577. EXPECT_EQ(StatusCode::OK_200, res->status);
  11578. EXPECT_EQ("val&key2=val2", res->body);
  11579. }
  11580. }
  11581. #endif
  11582. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11583. Server svr;
  11584. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11585. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11586. });
  11587. svr.Get("/hello", [](const Request &req, Response &res) {
  11588. res.set_content(req.get_param_value("key"), "text/plain");
  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.set_follow_location(true);
  11600. auto res = cli.Get("/");
  11601. ASSERT_TRUE(res);
  11602. EXPECT_EQ(StatusCode::OK_200, res->status);
  11603. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11604. }
  11605. }
  11606. TEST(RedirectTest, RedirectWithPlusInPath) {
  11607. Server svr;
  11608. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11609. res.set_redirect("/a+b");
  11610. });
  11611. // Route pattern uses regex; escape + as \\+
  11612. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11613. res.set_content(req.path, "text/plain");
  11614. });
  11615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11616. auto se = detail::scope_exit([&] {
  11617. svr.stop();
  11618. thread.join();
  11619. ASSERT_FALSE(svr.is_running());
  11620. });
  11621. svr.wait_until_ready();
  11622. {
  11623. Client cli(HOST, PORT);
  11624. cli.set_follow_location(true);
  11625. auto res = cli.Get("/");
  11626. ASSERT_TRUE(res);
  11627. EXPECT_EQ(StatusCode::OK_200, res->status);
  11628. EXPECT_EQ("/a+b", res->body);
  11629. }
  11630. }
  11631. #ifdef CPPHTTPLIB_SSL_ENABLED
  11632. TEST(RedirectTest, Issue2185_Online) {
  11633. SSLClient client("github.com");
  11634. client.set_follow_location(true);
  11635. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11636. "Coollab-Windows.zip");
  11637. ASSERT_TRUE(res);
  11638. EXPECT_EQ(StatusCode::OK_200, res->status);
  11639. EXPECT_EQ(9920427U, res->body.size());
  11640. }
  11641. #endif
  11642. TEST(VulnerabilityTest, CRLFInjection) {
  11643. Server svr;
  11644. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11645. res.set_content("Hello 1", "text/plain");
  11646. });
  11647. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11648. res.set_content("Hello 2", "text/plain");
  11649. });
  11650. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11651. res.set_content("Hello 3", "text/plain");
  11652. });
  11653. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11654. res.set_content("Hello 4", "text/plain");
  11655. });
  11656. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11657. for (const auto &x : req.headers) {
  11658. auto key = x.first;
  11659. EXPECT_STRNE("evil", key.c_str());
  11660. }
  11661. });
  11662. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11663. auto se = detail::scope_exit([&] {
  11664. svr.stop();
  11665. thread.join();
  11666. ASSERT_FALSE(svr.is_running());
  11667. });
  11668. svr.wait_until_ready();
  11669. {
  11670. Client cli(HOST, PORT);
  11671. cli.Post("/test1", "A=B",
  11672. "application/x-www-form-urlencoded\r\nevil: hello1");
  11673. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11674. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11675. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11676. }
  11677. }
  11678. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11679. auto server_thread = std::thread([] {
  11680. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11681. default_socket_options(srv);
  11682. sockaddr_in addr{};
  11683. addr.sin_family = AF_INET;
  11684. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11685. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11686. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11687. ::listen(srv, 1);
  11688. sockaddr_in cli_addr{};
  11689. socklen_t cli_len = sizeof(cli_addr);
  11690. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11691. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11692. std::string buf_all;
  11693. char buf[2048];
  11694. ssize_t n;
  11695. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11696. buf_all.append(buf, static_cast<size_t>(n));
  11697. size_t pos;
  11698. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11699. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11700. auto e = request_block.find("\r\n");
  11701. if (e != std::string::npos) {
  11702. auto request_line = request_block.substr(0, e);
  11703. std::string msg =
  11704. "CRLF injection detected in request line: '" + request_line + "'";
  11705. EXPECT_FALSE(true) << msg;
  11706. }
  11707. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11708. ::send(cli,
  11709. #ifdef _WIN32
  11710. static_cast<const char *>(resp.c_str()),
  11711. static_cast<int>(resp.size()),
  11712. #else
  11713. resp.c_str(), resp.size(),
  11714. #endif
  11715. 0);
  11716. buf_all.erase(0, pos + 4);
  11717. }
  11718. }
  11719. detail::close_socket(cli);
  11720. detail::close_socket(srv);
  11721. });
  11722. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11723. auto cli = Client("127.0.0.1", PORT + 1);
  11724. auto headers = Headers{
  11725. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11726. {"Connection", "keep-alive"}};
  11727. auto res = cli.Get("/hi", headers);
  11728. EXPECT_FALSE(res);
  11729. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11730. server_thread.join();
  11731. }
  11732. TEST(PathParamsTest, StaticMatch) {
  11733. const auto pattern = "/users/all";
  11734. detail::PathParamsMatcher matcher(pattern);
  11735. Request request;
  11736. request.path = "/users/all";
  11737. ASSERT_TRUE(matcher.match(request));
  11738. std::unordered_map<std::string, std::string> expected_params = {};
  11739. EXPECT_EQ(request.path_params, expected_params);
  11740. }
  11741. TEST(PathParamsTest, StaticMismatch) {
  11742. const auto pattern = "/users/all";
  11743. detail::PathParamsMatcher matcher(pattern);
  11744. Request request;
  11745. request.path = "/users/1";
  11746. ASSERT_FALSE(matcher.match(request));
  11747. }
  11748. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11749. const auto pattern = "/users/:id/subscriptions";
  11750. detail::PathParamsMatcher matcher(pattern);
  11751. Request request;
  11752. request.path = "/users/42/subscriptions";
  11753. ASSERT_TRUE(matcher.match(request));
  11754. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11755. EXPECT_EQ(request.path_params, expected_params);
  11756. }
  11757. TEST(PathParamsTest, SingleParamInTheEnd) {
  11758. const auto pattern = "/users/:id";
  11759. detail::PathParamsMatcher matcher(pattern);
  11760. Request request;
  11761. request.path = "/users/24";
  11762. ASSERT_TRUE(matcher.match(request));
  11763. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11764. EXPECT_EQ(request.path_params, expected_params);
  11765. }
  11766. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11767. const auto pattern = "/users/:id/";
  11768. detail::PathParamsMatcher matcher(pattern);
  11769. Request request;
  11770. request.path = "/users/42/";
  11771. ASSERT_TRUE(matcher.match(request));
  11772. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11773. EXPECT_EQ(request.path_params, expected_params);
  11774. }
  11775. TEST(PathParamsTest, EmptyParam) {
  11776. const auto pattern = "/users/:id/";
  11777. detail::PathParamsMatcher matcher(pattern);
  11778. Request request;
  11779. request.path = "/users//";
  11780. ASSERT_TRUE(matcher.match(request));
  11781. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11782. EXPECT_EQ(request.path_params, expected_params);
  11783. }
  11784. TEST(PathParamsTest, FragmentMismatch) {
  11785. const auto pattern = "/users/:id/";
  11786. detail::PathParamsMatcher matcher(pattern);
  11787. Request request;
  11788. request.path = "/admins/24/";
  11789. ASSERT_FALSE(matcher.match(request));
  11790. }
  11791. TEST(PathParamsTest, ExtraFragments) {
  11792. const auto pattern = "/users/:id";
  11793. detail::PathParamsMatcher matcher(pattern);
  11794. Request request;
  11795. request.path = "/users/42/subscriptions";
  11796. ASSERT_FALSE(matcher.match(request));
  11797. }
  11798. TEST(PathParamsTest, MissingTrailingParam) {
  11799. const auto pattern = "/users/:id";
  11800. detail::PathParamsMatcher matcher(pattern);
  11801. Request request;
  11802. request.path = "/users";
  11803. ASSERT_FALSE(matcher.match(request));
  11804. }
  11805. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11806. const auto pattern = "/users/:id/subscriptions";
  11807. detail::PathParamsMatcher matcher(pattern);
  11808. Request request;
  11809. request.path = "/users/subscriptions";
  11810. ASSERT_FALSE(matcher.match(request));
  11811. }
  11812. TEST(PathParamsTest, MultipleParams) {
  11813. const auto pattern = "/users/:userid/subscriptions/:subid";
  11814. detail::PathParamsMatcher matcher(pattern);
  11815. Request request;
  11816. request.path = "/users/42/subscriptions/2";
  11817. ASSERT_TRUE(matcher.match(request));
  11818. std::unordered_map<std::string, std::string> expected_params = {
  11819. {"userid", "42"}, {"subid", "2"}};
  11820. EXPECT_EQ(request.path_params, expected_params);
  11821. }
  11822. TEST(PathParamsTest, SequenceOfParams) {
  11823. const auto pattern = "/values/:x/:y/:z";
  11824. detail::PathParamsMatcher matcher(pattern);
  11825. Request request;
  11826. request.path = "/values/1/2/3";
  11827. ASSERT_TRUE(matcher.match(request));
  11828. std::unordered_map<std::string, std::string> expected_params = {
  11829. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11830. EXPECT_EQ(request.path_params, expected_params);
  11831. }
  11832. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11833. const auto pattern = "/prefix:suffix";
  11834. detail::PathParamsMatcher matcher(pattern);
  11835. Request request;
  11836. request.path = "/prefix:suffix";
  11837. ASSERT_TRUE(matcher.match(request));
  11838. const std::unordered_map<std::string, std::string> expected_params = {};
  11839. EXPECT_EQ(request.path_params, expected_params);
  11840. }
  11841. TEST(ParseUrlTest, VariousPatterns) {
  11842. {
  11843. detail::UrlComponents uc;
  11844. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11845. EXPECT_EQ("http", uc.scheme);
  11846. EXPECT_EQ("example.com", uc.host);
  11847. EXPECT_EQ("8080", uc.port);
  11848. EXPECT_EQ("/path", uc.path);
  11849. EXPECT_EQ("?q=1", uc.query);
  11850. }
  11851. {
  11852. detail::UrlComponents uc;
  11853. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11854. EXPECT_EQ("https", uc.scheme);
  11855. EXPECT_EQ("example.com", uc.host);
  11856. EXPECT_TRUE(uc.port.empty());
  11857. EXPECT_EQ("/path", uc.path);
  11858. }
  11859. {
  11860. detail::UrlComponents uc;
  11861. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11862. EXPECT_EQ("::1", uc.host);
  11863. EXPECT_EQ("8080", uc.port);
  11864. EXPECT_EQ("/path", uc.path);
  11865. }
  11866. {
  11867. detail::UrlComponents uc;
  11868. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11869. }
  11870. {
  11871. detail::UrlComponents uc;
  11872. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11873. EXPECT_TRUE(uc.scheme.empty());
  11874. EXPECT_EQ("example.com", uc.host);
  11875. EXPECT_EQ("/path", uc.path);
  11876. EXPECT_EQ("?q=1", uc.query);
  11877. }
  11878. {
  11879. detail::UrlComponents uc;
  11880. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11881. EXPECT_TRUE(uc.host.empty());
  11882. EXPECT_EQ("/path", uc.path);
  11883. EXPECT_EQ("?q=1", uc.query);
  11884. }
  11885. {
  11886. detail::UrlComponents uc;
  11887. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11888. EXPECT_EQ("example.com", uc.host);
  11889. EXPECT_EQ("8080", uc.port);
  11890. }
  11891. {
  11892. // Unix socket path — must not be parsed as host
  11893. detail::UrlComponents uc;
  11894. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11895. EXPECT_TRUE(uc.host.empty());
  11896. }
  11897. {
  11898. detail::UrlComponents uc;
  11899. ASSERT_TRUE(detail::parse_url("", uc));
  11900. EXPECT_TRUE(uc.host.empty());
  11901. EXPECT_TRUE(uc.path.empty());
  11902. }
  11903. {
  11904. detail::UrlComponents uc;
  11905. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11906. }
  11907. {
  11908. detail::UrlComponents uc;
  11909. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11910. }
  11911. {
  11912. // Accepted by parse_url; callers restrict to http/https
  11913. detail::UrlComponents uc;
  11914. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11915. EXPECT_EQ("ftp", uc.scheme);
  11916. }
  11917. {
  11918. detail::UrlComponents uc;
  11919. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11920. }
  11921. {
  11922. detail::UrlComponents uc;
  11923. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11924. }
  11925. }
  11926. TEST(ParseUrlTest, FragmentHandling) {
  11927. {
  11928. detail::UrlComponents uc;
  11929. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11930. EXPECT_EQ("/path", uc.path);
  11931. EXPECT_TRUE(uc.query.empty());
  11932. }
  11933. {
  11934. detail::UrlComponents uc;
  11935. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11936. EXPECT_TRUE(uc.path.empty());
  11937. EXPECT_TRUE(uc.query.empty());
  11938. }
  11939. }
  11940. TEST(ParseUrlTest, UserinfoHandling) {
  11941. // Userinfo with @ but no colon — host includes @
  11942. detail::UrlComponents uc;
  11943. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11944. EXPECT_EQ("user@host.com", uc.host);
  11945. EXPECT_EQ("/path", uc.path);
  11946. }
  11947. TEST(ParseUrlTest, IPv6EdgeCases) {
  11948. {
  11949. detail::UrlComponents uc;
  11950. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11951. EXPECT_TRUE(uc.scheme.empty());
  11952. EXPECT_EQ("::1", uc.host);
  11953. EXPECT_EQ("8080", uc.port);
  11954. }
  11955. {
  11956. // Zone ID '%25' is not in [a-fA-F0-9:]
  11957. detail::UrlComponents uc;
  11958. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11959. }
  11960. }
  11961. TEST(ParseUrlTest, SchemeEdgeCases) {
  11962. {
  11963. detail::UrlComponents uc;
  11964. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11965. }
  11966. {
  11967. detail::UrlComponents uc;
  11968. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11969. }
  11970. {
  11971. detail::UrlComponents uc;
  11972. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11973. }
  11974. }
  11975. TEST(ParseUrlTest, PortEdgeCases) {
  11976. {
  11977. detail::UrlComponents uc;
  11978. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11979. EXPECT_TRUE(uc.port.empty());
  11980. EXPECT_EQ("/path", uc.path);
  11981. }
  11982. {
  11983. // parse_url accepts any port string; validation is done by parse_port
  11984. detail::UrlComponents uc;
  11985. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11986. EXPECT_EQ("abc", uc.port);
  11987. }
  11988. }
  11989. TEST(ParseUrlTest, WebSocketPatterns) {
  11990. {
  11991. detail::UrlComponents uc;
  11992. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11993. EXPECT_EQ("ws", uc.scheme);
  11994. EXPECT_EQ("echo.example.com", uc.host);
  11995. EXPECT_EQ("8080", uc.port);
  11996. EXPECT_EQ("/ws", uc.path);
  11997. }
  11998. {
  11999. detail::UrlComponents uc;
  12000. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12001. EXPECT_EQ("wss", uc.scheme);
  12002. EXPECT_EQ("echo.example.com", uc.host);
  12003. EXPECT_TRUE(uc.port.empty());
  12004. EXPECT_EQ("/ws", uc.path);
  12005. }
  12006. }
  12007. TEST(ParseUrlTest, QueryOnly) {
  12008. detail::UrlComponents uc;
  12009. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12010. EXPECT_TRUE(uc.host.empty());
  12011. EXPECT_TRUE(uc.path.empty());
  12012. EXPECT_EQ("?q=1&r=2", uc.query);
  12013. }
  12014. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12015. detail::UrlComponents uc;
  12016. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12017. EXPECT_TRUE(uc.scheme.empty());
  12018. EXPECT_EQ("example.com", uc.host);
  12019. EXPECT_EQ("443", uc.port);
  12020. EXPECT_EQ("/path", uc.path);
  12021. }
  12022. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12023. // If ipv6 regex working, regex match codepath is taken.
  12024. // else port will default to 80 in Client impl
  12025. int clientImplMagicPort = 80;
  12026. int port = 4321;
  12027. // above ports must be different to avoid false negative
  12028. EXPECT_NE(clientImplMagicPort, port);
  12029. std::string ipV6TestURL = "http://[ff06::c3]";
  12030. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12031. CLIENT_PRIVATE_KEY_FILE);
  12032. EXPECT_EQ(cli.port(), port);
  12033. }
  12034. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12035. auto file_path = "./www/dir/index.html";
  12036. auto dir_path = "./www/dir";
  12037. detail::FileStat stat_file(file_path);
  12038. EXPECT_TRUE(stat_file.is_file());
  12039. EXPECT_FALSE(stat_file.is_dir());
  12040. detail::FileStat stat_dir(dir_path);
  12041. EXPECT_FALSE(stat_dir.is_file());
  12042. EXPECT_TRUE(stat_dir.is_dir());
  12043. }
  12044. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12045. // IPv4 with default HTTP port (80)
  12046. EXPECT_EQ("example.com",
  12047. detail::make_host_and_port_string("example.com", 80, false));
  12048. // IPv4 with default HTTPS port (443)
  12049. EXPECT_EQ("example.com",
  12050. detail::make_host_and_port_string("example.com", 443, true));
  12051. // IPv4 with non-default HTTP port
  12052. EXPECT_EQ("example.com:8080",
  12053. detail::make_host_and_port_string("example.com", 8080, false));
  12054. // IPv4 with non-default HTTPS port
  12055. EXPECT_EQ("example.com:8443",
  12056. detail::make_host_and_port_string("example.com", 8443, true));
  12057. // IPv6 with default HTTP port (80)
  12058. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12059. // IPv6 with default HTTPS port (443)
  12060. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12061. // IPv6 with non-default HTTP port
  12062. EXPECT_EQ("[::1]:8080",
  12063. detail::make_host_and_port_string("::1", 8080, false));
  12064. // IPv6 with non-default HTTPS port
  12065. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12066. // IPv6 full address with default port
  12067. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12068. detail::make_host_and_port_string(
  12069. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12070. // IPv6 full address with non-default port
  12071. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12072. detail::make_host_and_port_string(
  12073. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12074. // IPv6 localhost with non-default port
  12075. EXPECT_EQ("[::1]:3000",
  12076. detail::make_host_and_port_string("::1", 3000, false));
  12077. // IPv6 with zone ID (link-local address) with default port
  12078. EXPECT_EQ("[fe80::1%eth0]",
  12079. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12080. // IPv6 with zone ID (link-local address) with non-default port
  12081. EXPECT_EQ("[fe80::1%eth0]:8080",
  12082. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12083. // Edge case: Port 443 with is_ssl=false (should add port)
  12084. EXPECT_EQ("example.com:443",
  12085. detail::make_host_and_port_string("example.com", 443, false));
  12086. // Edge case: Port 80 with is_ssl=true (should add port)
  12087. EXPECT_EQ("example.com:80",
  12088. detail::make_host_and_port_string("example.com", 80, true));
  12089. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12090. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12091. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12092. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12093. // Security fix: Already bracketed IPv6 should not get double brackets
  12094. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12095. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12096. EXPECT_EQ("[::1]:8080",
  12097. detail::make_host_and_port_string("[::1]", 8080, false));
  12098. EXPECT_EQ("[2001:db8::1]:8080",
  12099. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12100. EXPECT_EQ("[fe80::1%eth0]",
  12101. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12102. EXPECT_EQ("[fe80::1%eth0]:8080",
  12103. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12104. // Edge case: Empty host (should return as-is)
  12105. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12106. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12107. // This is a known limitation but shouldn't crash
  12108. EXPECT_EQ("[host:name]",
  12109. detail::make_host_and_port_string("host:name", 80, false));
  12110. // Port number edge cases (no validation, but should not crash)
  12111. EXPECT_EQ("example.com:0",
  12112. detail::make_host_and_port_string("example.com", 0, false));
  12113. EXPECT_EQ("example.com:-1",
  12114. detail::make_host_and_port_string("example.com", -1, false));
  12115. EXPECT_EQ("example.com:65535",
  12116. detail::make_host_and_port_string("example.com", 65535, false));
  12117. EXPECT_EQ("example.com:65536",
  12118. detail::make_host_and_port_string("example.com", 65536, false));
  12119. }
  12120. #ifdef CPPHTTPLIB_SSL_ENABLED
  12121. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12122. httplib::SSLClient cli("roblox.com", 443);
  12123. cli.set_follow_location(true);
  12124. auto res = cli.Get("/");
  12125. ASSERT_TRUE(res);
  12126. EXPECT_EQ(StatusCode::OK_200, res->status);
  12127. }
  12128. #endif
  12129. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12130. Server svr;
  12131. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12132. EXPECT_EQ(res.status, 400);
  12133. });
  12134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12135. auto se = detail::scope_exit([&] {
  12136. svr.stop();
  12137. thread.join();
  12138. ASSERT_FALSE(svr.is_running());
  12139. });
  12140. svr.wait_until_ready();
  12141. Client cli(HOST, PORT);
  12142. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12143. }
  12144. TEST(InvalidHeaderCharsTest, is_field_name) {
  12145. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12146. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12147. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12148. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12149. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12150. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12151. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12152. EXPECT_FALSE(detail::fields::is_field_name(""));
  12153. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12154. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12155. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12156. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12157. }
  12158. TEST(InvalidHeaderCharsTest, is_field_value) {
  12159. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12160. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12161. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12162. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12163. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12164. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12165. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12166. EXPECT_TRUE(detail::fields::is_field_value(""));
  12167. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12168. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12169. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12170. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12171. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12172. }
  12173. TEST(InvalidHeaderCharsTest, OnServer) {
  12174. Server svr;
  12175. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12176. std::string header = "Not Set";
  12177. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12178. res.set_header(header, "value");
  12179. res.set_content("Page Content Page Content", "text/plain");
  12180. });
  12181. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12182. std::string header = "Not Set";
  12183. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12184. res.set_header("X-Test", header);
  12185. res.set_content("Page Content Page Content", "text/plain");
  12186. });
  12187. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12188. auto se = detail::scope_exit([&] {
  12189. svr.stop();
  12190. thread.join();
  12191. ASSERT_FALSE(svr.is_running());
  12192. });
  12193. svr.wait_until_ready();
  12194. Client cli(HOST, PORT);
  12195. {
  12196. auto res = cli.Get(
  12197. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12198. ASSERT_TRUE(res);
  12199. EXPECT_EQ("Page Content Page Content", res->body);
  12200. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12201. }
  12202. {
  12203. auto res = cli.Get(
  12204. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12205. ASSERT_TRUE(res);
  12206. EXPECT_EQ("Page Content Page Content", res->body);
  12207. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12208. }
  12209. }
  12210. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12211. auto handled = false;
  12212. Server svr;
  12213. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12214. thread t = thread([&] { svr.listen(HOST, PORT); });
  12215. auto se = detail::scope_exit([&] {
  12216. svr.stop();
  12217. t.join();
  12218. ASSERT_FALSE(svr.is_running());
  12219. ASSERT_FALSE(handled);
  12220. });
  12221. svr.wait_until_ready();
  12222. auto req = "POST /test HTTP/1.1\r\n"
  12223. "Content-Length: x\r\n"
  12224. "\r\n";
  12225. std::string response;
  12226. ASSERT_TRUE(send_request(1, req, &response));
  12227. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12228. response.substr(0, response.find("\r\n")));
  12229. }
  12230. #ifndef _WIN32
  12231. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12232. static constexpr char reject[] = "Unauthorized";
  12233. static constexpr char accept[] = "Upload accepted";
  12234. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12235. Server svr;
  12236. svr.set_expect_100_continue_handler(
  12237. [](const Request & /*req*/, Response &res) {
  12238. res.status = StatusCode::Unauthorized_401;
  12239. res.set_content(reject, "text/plain");
  12240. return res.status;
  12241. });
  12242. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12243. res.set_content(accept, "text/plain");
  12244. });
  12245. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12246. auto se = detail::scope_exit([&] {
  12247. svr.stop();
  12248. thread.join();
  12249. ASSERT_FALSE(svr.is_running());
  12250. });
  12251. svr.wait_until_ready();
  12252. {
  12253. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12254. curl_easy_init(), &curl_easy_cleanup};
  12255. ASSERT_NE(curl, nullptr);
  12256. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12257. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12258. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12259. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12260. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12261. &curl_slist_free_all};
  12262. ASSERT_NE(list, nullptr);
  12263. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12264. struct read_data {
  12265. size_t read_size;
  12266. size_t total_size;
  12267. } data = {0, total_size};
  12268. using read_callback_t =
  12269. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12270. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12271. void *userdata) -> size_t {
  12272. read_data *d = (read_data *)userdata;
  12273. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12274. std::fill_n(ptr, size * nmemb, 'A');
  12275. d->read_size += size * nmemb;
  12276. return size * nmemb;
  12277. };
  12278. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12279. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12280. std::vector<char> buffer;
  12281. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12282. using write_callback_t =
  12283. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12284. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12285. void *userdata) -> size_t {
  12286. std::vector<char> *buf = (std::vector<char> *)userdata;
  12287. buf->reserve(buf->size() + size * nmemb + 1);
  12288. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12289. return size * nmemb;
  12290. };
  12291. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12292. {
  12293. const auto res = curl_easy_perform(curl.get());
  12294. ASSERT_EQ(res, CURLE_OK);
  12295. }
  12296. {
  12297. auto response_code = long{};
  12298. const auto res =
  12299. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12300. ASSERT_EQ(res, CURLE_OK);
  12301. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12302. }
  12303. {
  12304. auto dl = curl_off_t{};
  12305. const auto res =
  12306. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12307. ASSERT_EQ(res, CURLE_OK);
  12308. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12309. }
  12310. {
  12311. buffer.push_back('\0');
  12312. ASSERT_STRCASEEQ(buffer.data(), reject);
  12313. }
  12314. }
  12315. }
  12316. #endif
  12317. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12318. // Regression test for #2458.
  12319. //
  12320. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12321. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12322. // ticket can make the client socket spuriously readable during the
  12323. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12324. // the client withholds the body and then blocks reading a response that never
  12325. // comes, failing with `Failed to read connection`.
  12326. //
  12327. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12328. // within the timeout. This raw OpenSSL server deliberately never sends
  12329. // `100 Continue`; the client must still deliver the body and receive 200.
  12330. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12331. signal(SIGPIPE, SIG_IGN);
  12332. const auto port = PORT + 4;
  12333. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12334. ASSERT_NE(srv, INVALID_SOCKET);
  12335. int opt = 1;
  12336. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12337. sockaddr_in addr{};
  12338. addr.sin_family = AF_INET;
  12339. addr.sin_port = htons(static_cast<uint16_t>(port));
  12340. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12341. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12342. ASSERT_EQ(0, ::listen(srv, 1));
  12343. std::atomic<size_t> server_body_bytes{0};
  12344. auto server_thread = std::thread([&] {
  12345. sockaddr_in cli_addr{};
  12346. socklen_t cli_len = sizeof(cli_addr);
  12347. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12348. if (cli == INVALID_SOCKET) { return; }
  12349. // Bound the lifetime of the server side so a buggy client (which never
  12350. // sends the body) cannot make this thread block forever on join.
  12351. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12352. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12353. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12354. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12355. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12356. SSL *ssl = SSL_new(ctx);
  12357. SSL_set_fd(ssl, static_cast<int>(cli));
  12358. if (SSL_accept(ssl) > 0) {
  12359. // Read the request headers. Reading here also flushes the TLS 1.3
  12360. // session tickets to the client. Deliberately do NOT send
  12361. // `100 Continue`.
  12362. std::string buf;
  12363. char tmp[1024];
  12364. while (buf.find("\r\n\r\n") == std::string::npos) {
  12365. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12366. if (n <= 0) { break; }
  12367. buf.append(tmp, static_cast<size_t>(n));
  12368. }
  12369. // A correct client sends the body now; count what arrives.
  12370. auto pos = buf.find("\r\n\r\n");
  12371. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12372. while (body < 4096) {
  12373. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12374. if (n <= 0) { break; }
  12375. body += static_cast<size_t>(n);
  12376. }
  12377. server_body_bytes = body;
  12378. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12379. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12380. SSL_shutdown(ssl);
  12381. }
  12382. SSL_free(ssl);
  12383. detail::close_socket(cli);
  12384. SSL_CTX_free(ctx);
  12385. });
  12386. auto se = detail::scope_exit([&] {
  12387. server_thread.join();
  12388. detail::close_socket(srv);
  12389. });
  12390. SSLClient cli("127.0.0.1", port);
  12391. cli.enable_server_certificate_verification(false);
  12392. cli.set_connection_timeout(5, 0);
  12393. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12394. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12395. std::string body(4096, 'A');
  12396. auto res = cli.Put("/api/test", body, "application/json");
  12397. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12398. EXPECT_EQ(StatusCode::OK_200, res->status);
  12399. EXPECT_EQ(body.size(), server_body_bytes.load());
  12400. }
  12401. #endif
  12402. template <typename S, typename C>
  12403. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12404. svr.Get("/stream", [&](const Request &, Response &res) {
  12405. auto data = new std::string("01234567890123456789");
  12406. res.set_content_provider(
  12407. data->size(), "text/plain",
  12408. [&, data](size_t offset, size_t length, DataSink &sink) {
  12409. const size_t DATA_CHUNK_SIZE = 4;
  12410. const auto &d = *data;
  12411. std::this_thread::sleep_for(std::chrono::seconds(1));
  12412. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12413. return true;
  12414. },
  12415. [data](bool success) {
  12416. EXPECT_FALSE(success);
  12417. delete data;
  12418. });
  12419. });
  12420. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12421. auto i = new size_t(0);
  12422. res.set_content_provider(
  12423. "text/plain",
  12424. [i](size_t, DataSink &sink) {
  12425. if (*i < 5) {
  12426. std::this_thread::sleep_for(std::chrono::seconds(1));
  12427. sink.write("abcd", 4);
  12428. (*i)++;
  12429. } else {
  12430. sink.done();
  12431. }
  12432. return true;
  12433. },
  12434. [i](bool success) {
  12435. EXPECT_FALSE(success);
  12436. delete i;
  12437. });
  12438. });
  12439. svr.Get("/chunked", [&](const Request &, Response &res) {
  12440. auto i = new size_t(0);
  12441. res.set_chunked_content_provider(
  12442. "text/plain",
  12443. [i](size_t, DataSink &sink) {
  12444. if (*i < 5) {
  12445. std::this_thread::sleep_for(std::chrono::seconds(1));
  12446. sink.os << "abcd";
  12447. (*i)++;
  12448. } else {
  12449. sink.done();
  12450. }
  12451. return true;
  12452. },
  12453. [i](bool success) {
  12454. EXPECT_FALSE(success);
  12455. delete i;
  12456. });
  12457. });
  12458. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12459. auto se = detail::scope_exit([&] {
  12460. svr.stop();
  12461. listen_thread.join();
  12462. ASSERT_FALSE(svr.is_running());
  12463. });
  12464. svr.wait_until_ready();
  12465. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12466. {
  12467. auto start = std::chrono::steady_clock::now();
  12468. auto res = cli.Get("/stream");
  12469. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12470. std::chrono::steady_clock::now() - start)
  12471. .count();
  12472. ASSERT_FALSE(res);
  12473. EXPECT_EQ(Error::Read, res.error());
  12474. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12475. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12476. }
  12477. {
  12478. auto start = std::chrono::steady_clock::now();
  12479. auto res = cli.Get("/stream_without_length");
  12480. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12481. std::chrono::steady_clock::now() - start)
  12482. .count();
  12483. ASSERT_FALSE(res);
  12484. EXPECT_EQ(Error::Read, res.error());
  12485. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12486. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12487. }
  12488. {
  12489. auto start = std::chrono::steady_clock::now();
  12490. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12491. EXPECT_EQ("abcd", string(data, data_length));
  12492. return true;
  12493. });
  12494. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12495. std::chrono::steady_clock::now() - start)
  12496. .count();
  12497. ASSERT_FALSE(res);
  12498. EXPECT_EQ(Error::Read, res.error());
  12499. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12500. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12501. }
  12502. }
  12503. TEST(MaxTimeoutTest, ContentStream) {
  12504. time_t timeout = 2000;
  12505. time_t threshold = 200;
  12506. Server svr;
  12507. Client cli("localhost", PORT);
  12508. max_timeout_test(svr, cli, timeout, threshold);
  12509. }
  12510. #ifdef CPPHTTPLIB_SSL_ENABLED
  12511. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12512. time_t timeout = 2000;
  12513. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12515. SSLClient cli("localhost", PORT);
  12516. cli.enable_server_certificate_verification(false);
  12517. max_timeout_test(svr, cli, timeout, threshold);
  12518. }
  12519. #endif
  12520. class EventDispatcher {
  12521. public:
  12522. EventDispatcher() {}
  12523. bool wait_event(DataSink *sink) {
  12524. unique_lock<mutex> lk(m_);
  12525. int id = id_;
  12526. // Wait with timeout to prevent hanging if client disconnects
  12527. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12528. [&] { return cid_ == id; })) {
  12529. return false; // Timeout occurred
  12530. }
  12531. sink->write(message_.data(), message_.size());
  12532. return true;
  12533. }
  12534. void send_event(const string &message) {
  12535. lock_guard<mutex> lk(m_);
  12536. cid_ = id_++;
  12537. message_ = message;
  12538. cv_.notify_all();
  12539. }
  12540. private:
  12541. mutex m_;
  12542. condition_variable cv_;
  12543. atomic_int id_{0};
  12544. atomic_int cid_{-1};
  12545. string message_;
  12546. };
  12547. TEST(ClientInThreadTest, Issue2068) {
  12548. EventDispatcher ed;
  12549. Server svr;
  12550. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12551. res.set_chunked_content_provider("text/event-stream",
  12552. [&](size_t /*offset*/, DataSink &sink) {
  12553. return ed.wait_event(&sink);
  12554. });
  12555. });
  12556. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12557. svr.wait_until_ready();
  12558. thread event_thread([&] {
  12559. int id = 0;
  12560. while (svr.is_running()) {
  12561. this_thread::sleep_for(chrono::milliseconds(500));
  12562. std::stringstream ss;
  12563. ss << "data: " << id << "\n\n";
  12564. ed.send_event(ss.str());
  12565. id++;
  12566. }
  12567. });
  12568. auto se = detail::scope_exit([&] {
  12569. svr.stop();
  12570. listen_thread.join();
  12571. event_thread.join();
  12572. ASSERT_FALSE(svr.is_running());
  12573. });
  12574. {
  12575. auto client = detail::make_unique<Client>(HOST, PORT);
  12576. client->set_read_timeout(std::chrono::minutes(10));
  12577. std::atomic<bool> stop{false};
  12578. std::thread t([&] {
  12579. client->Get("/event1",
  12580. [&](const char *, size_t) -> bool { return !stop; });
  12581. });
  12582. std::this_thread::sleep_for(std::chrono::seconds(2));
  12583. stop = true;
  12584. client->stop();
  12585. t.join();
  12586. // Reset client after thread has finished
  12587. client.reset();
  12588. }
  12589. }
  12590. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12591. auto handled = false;
  12592. Server svr;
  12593. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12594. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12595. auto se = detail::scope_exit([&] {
  12596. svr.stop();
  12597. t.join();
  12598. ASSERT_FALSE(svr.is_running());
  12599. ASSERT_FALSE(handled);
  12600. });
  12601. svr.wait_until_ready();
  12602. // Two Content-Length headers with different values — must be rejected
  12603. auto req = "POST /test HTTP/1.1\r\n"
  12604. "Content-Length: 5\r\n"
  12605. "Content-Length: 10\r\n"
  12606. "\r\n"
  12607. "hello";
  12608. std::string response;
  12609. ASSERT_TRUE(send_request(1, req, &response));
  12610. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12611. response.substr(0, response.find("\r\n")));
  12612. }
  12613. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12614. auto handled = false;
  12615. Server svr;
  12616. svr.Post("/test", [&](const Request &, Response &res) {
  12617. handled = true;
  12618. res.set_content("ok", "text/plain");
  12619. });
  12620. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12621. auto se = detail::scope_exit([&] {
  12622. svr.stop();
  12623. t.join();
  12624. ASSERT_FALSE(svr.is_running());
  12625. ASSERT_TRUE(handled);
  12626. });
  12627. svr.wait_until_ready();
  12628. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12629. auto req = "POST /test HTTP/1.1\r\n"
  12630. "Content-Length: 5\r\n"
  12631. "Content-Length: 5\r\n"
  12632. "\r\n"
  12633. "hello";
  12634. std::string response;
  12635. ASSERT_TRUE(send_request(1, req, &response));
  12636. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12637. }
  12638. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12639. Server svr;
  12640. svr.Get("/", [](const Request &req, Response &res) {
  12641. EXPECT_EQ(2U, req.trailers.size());
  12642. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12643. // Denied
  12644. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12645. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12646. // Accepted
  12647. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12648. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12649. EXPECT_TRUE(req.has_trailer("X-World"));
  12650. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12651. res.set_content("ok", "text/plain");
  12652. });
  12653. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12654. auto se = detail::scope_exit([&] {
  12655. svr.stop();
  12656. t.join();
  12657. ASSERT_FALSE(svr.is_running());
  12658. });
  12659. svr.wait_until_ready();
  12660. const std::string req = "GET / HTTP/1.1\r\n"
  12661. "Transfer-Encoding: chunked\r\n"
  12662. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12663. "\r\n"
  12664. "0\r\n"
  12665. "Content-Length: 10\r\n"
  12666. "Host: internal.local\r\n"
  12667. "Content-Type: malicious/content\r\n"
  12668. "Cookie: any\r\n"
  12669. "Set-Cookie: any\r\n"
  12670. "X-Forwarded-For: attacker.com\r\n"
  12671. "X-Real-Ip: 1.1.1.1\r\n"
  12672. "X-Hello: hello\r\n"
  12673. "X-World: world\r\n"
  12674. "\r\n";
  12675. std::string res;
  12676. ASSERT_TRUE(send_request(1, req, &res));
  12677. }
  12678. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12679. Server svr;
  12680. std::string observed_remote_addr;
  12681. std::string observed_xff;
  12682. svr.Get("/ip", [&](const Request &req, Response &res) {
  12683. observed_remote_addr = req.remote_addr;
  12684. observed_xff = req.get_header_value("X-Forwarded-For");
  12685. res.set_content("ok", "text/plain");
  12686. });
  12687. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12688. auto se = detail::scope_exit([&] {
  12689. svr.stop();
  12690. t.join();
  12691. ASSERT_FALSE(svr.is_running());
  12692. });
  12693. svr.wait_until_ready();
  12694. Client cli(HOST, PORT);
  12695. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12696. ASSERT_TRUE(res);
  12697. EXPECT_EQ(StatusCode::OK_200, res->status);
  12698. EXPECT_EQ(observed_xff, "203.0.113.66");
  12699. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12700. observed_remote_addr == "127.0.0.1");
  12701. }
  12702. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12703. Server svr;
  12704. svr.set_trusted_proxies({"203.0.113.66"});
  12705. std::string observed_remote_addr;
  12706. std::string observed_xff;
  12707. svr.Get("/ip", [&](const Request &req, Response &res) {
  12708. observed_remote_addr = req.remote_addr;
  12709. observed_xff = req.get_header_value("X-Forwarded-For");
  12710. res.set_content("ok", "text/plain");
  12711. });
  12712. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12713. auto se = detail::scope_exit([&] {
  12714. svr.stop();
  12715. t.join();
  12716. ASSERT_FALSE(svr.is_running());
  12717. });
  12718. svr.wait_until_ready();
  12719. Client cli(HOST, PORT);
  12720. auto res = cli.Get("/ip");
  12721. ASSERT_TRUE(res);
  12722. EXPECT_EQ(StatusCode::OK_200, res->status);
  12723. EXPECT_EQ(observed_xff, "");
  12724. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12725. observed_remote_addr == "127.0.0.1");
  12726. }
  12727. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12728. Server svr;
  12729. svr.set_trusted_proxies({"203.0.113.66"});
  12730. std::string observed_remote_addr;
  12731. std::string observed_xff;
  12732. svr.Get("/ip", [&](const Request &req, Response &res) {
  12733. observed_remote_addr = req.remote_addr;
  12734. observed_xff = req.get_header_value("X-Forwarded-For");
  12735. res.set_content("ok", "text/plain");
  12736. });
  12737. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12738. auto se = detail::scope_exit([&] {
  12739. svr.stop();
  12740. t.join();
  12741. ASSERT_FALSE(svr.is_running());
  12742. });
  12743. svr.wait_until_ready();
  12744. Client cli(HOST, PORT);
  12745. auto res = cli.Get(
  12746. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12747. ASSERT_TRUE(res);
  12748. EXPECT_EQ(StatusCode::OK_200, res->status);
  12749. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12750. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12751. }
  12752. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12753. Server svr;
  12754. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12755. std::string observed_remote_addr;
  12756. std::string observed_xff;
  12757. svr.Get("/ip", [&](const Request &req, Response &res) {
  12758. observed_remote_addr = req.remote_addr;
  12759. observed_xff = req.get_header_value("X-Forwarded-For");
  12760. res.set_content("ok", "text/plain");
  12761. });
  12762. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12763. auto se = detail::scope_exit([&] {
  12764. svr.stop();
  12765. t.join();
  12766. ASSERT_FALSE(svr.is_running());
  12767. });
  12768. svr.wait_until_ready();
  12769. Client cli(HOST, PORT);
  12770. auto res = cli.Get(
  12771. "/ip",
  12772. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12773. ASSERT_TRUE(res);
  12774. EXPECT_EQ(StatusCode::OK_200, res->status);
  12775. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12776. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12777. }
  12778. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12779. Server svr;
  12780. svr.set_trusted_proxies({"192.0.2.45"});
  12781. std::string observed_remote_addr;
  12782. std::string observed_xff;
  12783. svr.Get("/ip", [&](const Request &req, Response &res) {
  12784. observed_remote_addr = req.remote_addr;
  12785. observed_xff = req.get_header_value("X-Forwarded-For");
  12786. res.set_content("ok", "text/plain");
  12787. });
  12788. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12789. auto se = detail::scope_exit([&] {
  12790. svr.stop();
  12791. t.join();
  12792. ASSERT_FALSE(svr.is_running());
  12793. });
  12794. svr.wait_until_ready();
  12795. Client cli(HOST, PORT);
  12796. auto res = cli.Get(
  12797. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12798. ASSERT_TRUE(res);
  12799. EXPECT_EQ(StatusCode::OK_200, res->status);
  12800. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12801. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12802. }
  12803. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12804. Server svr;
  12805. svr.set_trusted_proxies({"192.0.2.45"});
  12806. std::string observed_remote_addr;
  12807. std::string observed_xff;
  12808. svr.Get("/ip", [&](const Request &req, Response &res) {
  12809. observed_remote_addr = req.remote_addr;
  12810. observed_xff = req.get_header_value("X-Forwarded-For");
  12811. res.set_content("ok", "text/plain");
  12812. });
  12813. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop();
  12816. t.join();
  12817. ASSERT_FALSE(svr.is_running());
  12818. });
  12819. svr.wait_until_ready();
  12820. Client cli(HOST, PORT);
  12821. auto res = cli.Get(
  12822. "/ip",
  12823. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12824. ASSERT_TRUE(res);
  12825. EXPECT_EQ(StatusCode::OK_200, res->status);
  12826. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12827. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12828. }
  12829. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12830. Server svr;
  12831. svr.set_trusted_proxies({"192.0.2.45"});
  12832. std::string observed_remote_addr;
  12833. std::string observed_xff;
  12834. svr.Get("/ip", [&](const Request &req, Response &res) {
  12835. observed_remote_addr = req.remote_addr;
  12836. observed_xff = req.get_header_value("X-Forwarded-For");
  12837. res.set_content("ok", "text/plain");
  12838. });
  12839. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12840. auto se = detail::scope_exit([&] {
  12841. svr.stop();
  12842. t.join();
  12843. ASSERT_FALSE(svr.is_running());
  12844. });
  12845. svr.wait_until_ready();
  12846. std::string raw_req =
  12847. "GET /ip HTTP/1.1\r\n"
  12848. "Host: localhost\r\n"
  12849. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12850. "Connection: close\r\n"
  12851. "\r\n";
  12852. std::string out;
  12853. ASSERT_TRUE(send_request(5, raw_req, &out));
  12854. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12855. // Header parser trims surrounding whitespace of the header value
  12856. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12857. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12858. }
  12859. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12860. // crash the server (it used to call front() on an empty vector inside
  12861. // get_client_ip). The connection-level remote address must be retained instead.
  12862. static void run_malformed_xff_test(const std::string &xff_value) {
  12863. Server svr;
  12864. svr.set_trusted_proxies({"192.0.2.45"});
  12865. std::string observed_remote_addr;
  12866. svr.Get("/ip", [&](const Request &req, Response &res) {
  12867. observed_remote_addr = req.remote_addr;
  12868. res.set_content("ok", "text/plain");
  12869. });
  12870. int port = 0;
  12871. thread t = thread([&]() {
  12872. port = svr.bind_to_any_port(HOST);
  12873. svr.listen_after_bind();
  12874. });
  12875. auto se = detail::scope_exit([&] {
  12876. svr.stop();
  12877. t.join();
  12878. ASSERT_FALSE(svr.is_running());
  12879. });
  12880. svr.wait_until_ready();
  12881. Client cli(HOST, port);
  12882. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  12883. ASSERT_TRUE(res);
  12884. EXPECT_EQ(StatusCode::OK_200, res->status);
  12885. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12886. observed_remote_addr == "127.0.0.1");
  12887. }
  12888. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12889. run_malformed_xff_test("");
  12890. }
  12891. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12892. run_malformed_xff_test(",");
  12893. }
  12894. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12895. run_malformed_xff_test(", , ,");
  12896. }
  12897. #ifndef _WIN32
  12898. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12899. Server svr;
  12900. svr.Post("/post", [&](const Request &req, Response &res) {
  12901. res.set_content(req.body, "text/plain");
  12902. });
  12903. svr.Put("/put", [&](const Request &req, Response &res) {
  12904. res.set_content(req.body, "text/plain");
  12905. });
  12906. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12907. res.set_content(req.body, "text/plain");
  12908. });
  12909. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12910. res.set_content(req.body, "text/plain");
  12911. });
  12912. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12913. auto se = detail::scope_exit([&] {
  12914. svr.stop();
  12915. t.join();
  12916. ASSERT_FALSE(svr.is_running());
  12917. });
  12918. svr.wait_until_ready();
  12919. std::string resp;
  12920. // POST without Content-Length
  12921. ASSERT_TRUE(send_request(5,
  12922. "POST /post HTTP/1.1\r\n"
  12923. "Host: localhost\r\n"
  12924. "Connection: close\r\n"
  12925. "\r\n",
  12926. &resp));
  12927. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12928. // PUT without Content-Length
  12929. resp.clear();
  12930. ASSERT_TRUE(send_request(5,
  12931. "PUT /put HTTP/1.1\r\n"
  12932. "Host: localhost\r\n"
  12933. "Connection: close\r\n"
  12934. "\r\n",
  12935. &resp));
  12936. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12937. // PATCH without Content-Length
  12938. resp.clear();
  12939. ASSERT_TRUE(send_request(5,
  12940. "PATCH /patch HTTP/1.1\r\n"
  12941. "Host: localhost\r\n"
  12942. "Connection: close\r\n"
  12943. "\r\n",
  12944. &resp));
  12945. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12946. // DELETE without Content-Length
  12947. resp.clear();
  12948. ASSERT_TRUE(send_request(5,
  12949. "DELETE /delete HTTP/1.1\r\n"
  12950. "Host: localhost\r\n"
  12951. "Connection: close\r\n"
  12952. "\r\n",
  12953. &resp));
  12954. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12955. }
  12956. #endif
  12957. //==============================================================================
  12958. // open_stream() Tests
  12959. //==============================================================================
  12960. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12961. std::string result;
  12962. char buf[8192];
  12963. ssize_t n;
  12964. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12965. result.append(buf, static_cast<size_t>(n));
  12966. }
  12967. return result;
  12968. }
  12969. // Mock stream for unit tests
  12970. class MockStream : public Stream {
  12971. public:
  12972. std::string data;
  12973. size_t pos = 0;
  12974. ssize_t error_after = -1; // -1 = no error
  12975. explicit MockStream(const std::string &d, ssize_t err = -1)
  12976. : data(d), error_after(err) {}
  12977. bool is_readable() const override { return true; }
  12978. bool wait_readable() const override { return true; }
  12979. bool wait_writable() const override { return true; }
  12980. ssize_t read(char *ptr, size_t size) override {
  12981. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12982. if (pos >= data.size()) return 0;
  12983. size_t limit =
  12984. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12985. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12986. std::memcpy(ptr, data.data() + pos, to_read);
  12987. pos += to_read;
  12988. return static_cast<ssize_t>(to_read);
  12989. }
  12990. ssize_t write(const char *, size_t) override { return -1; }
  12991. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12992. ip = "127.0.0.1";
  12993. port = 0;
  12994. }
  12995. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12996. ip = "127.0.0.1";
  12997. port = 0;
  12998. }
  12999. socket_t socket() const override { return INVALID_SOCKET; }
  13000. time_t duration() const override { return 0; }
  13001. };
  13002. TEST(StreamHandleTest, Basic) {
  13003. ClientImpl::StreamHandle handle;
  13004. EXPECT_FALSE(handle.is_valid());
  13005. handle.response = detail::make_unique<Response>();
  13006. handle.error = Error::Connection;
  13007. EXPECT_FALSE(handle.is_valid());
  13008. handle.error = Error::Success;
  13009. EXPECT_TRUE(handle.is_valid());
  13010. }
  13011. TEST(BodyReaderTest, Basic) {
  13012. MockStream stream("Hello, World!");
  13013. detail::BodyReader reader;
  13014. reader.stream = &stream;
  13015. reader.content_length = 13;
  13016. char buf[32];
  13017. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13018. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13019. EXPECT_TRUE(reader.eof);
  13020. }
  13021. TEST(BodyReaderTest, NoStream) {
  13022. detail::BodyReader reader;
  13023. char buf[32];
  13024. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13025. EXPECT_EQ(Error::Connection, reader.last_error);
  13026. }
  13027. TEST(BodyReaderTest, Error) {
  13028. MockStream stream("Hello, World!", 5);
  13029. detail::BodyReader reader;
  13030. reader.stream = &stream;
  13031. reader.content_length = 13;
  13032. char buf[32];
  13033. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13034. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13035. EXPECT_EQ(Error::Read, reader.last_error);
  13036. }
  13037. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13038. // Mock-based StreamHandle tests relying on private internals are removed.
  13039. class OpenStreamTest : public ::testing::Test {
  13040. protected:
  13041. void SetUp() override {
  13042. svr_.Get("/hello", [](const Request &, Response &res) {
  13043. res.set_content("Hello World!", "text/plain");
  13044. });
  13045. svr_.Get("/large", [](const Request &, Response &res) {
  13046. res.set_content(std::string(10000, 'X'), "text/plain");
  13047. });
  13048. svr_.Get("/chunked", [](const Request &, Response &res) {
  13049. res.set_chunked_content_provider("text/plain",
  13050. [](size_t offset, DataSink &sink) {
  13051. if (offset < 15) {
  13052. sink.write("chunk", 5);
  13053. return true;
  13054. }
  13055. sink.done();
  13056. return true;
  13057. });
  13058. });
  13059. svr_.Get("/compressible", [](const Request &, Response &res) {
  13060. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13061. DataSink &sink) {
  13062. if (offset < 100 * 1024) {
  13063. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13064. sink.write(chunk.data(), chunk.size());
  13065. return true;
  13066. }
  13067. sink.done();
  13068. return true;
  13069. });
  13070. });
  13071. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13072. [](const Request & /*req*/, Response &res) {
  13073. auto i = new int(0);
  13074. res.set_header("Trailer", "Content-Length, X-Allowed");
  13075. res.set_chunked_content_provider(
  13076. "text/plain",
  13077. [i](size_t /*offset*/, DataSink &sink) {
  13078. switch (*i) {
  13079. case 0: sink.os << "123"; break;
  13080. case 1: sink.os << "456"; break;
  13081. case 2: sink.os << "789"; break;
  13082. case 3: {
  13083. sink.done_with_trailer(
  13084. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13085. } break;
  13086. }
  13087. (*i)++;
  13088. return true;
  13089. },
  13090. [i](bool success) {
  13091. EXPECT_TRUE(success);
  13092. delete i;
  13093. });
  13094. });
  13095. // Echo headers endpoint for header-related tests
  13096. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13097. std::string body;
  13098. for (const auto &h : req.headers) {
  13099. body.append(h.first);
  13100. body.push_back(':');
  13101. body.append(h.second);
  13102. body.push_back('\n');
  13103. }
  13104. res.set_content(body, "text/plain");
  13105. });
  13106. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13107. std::string body;
  13108. for (const auto &h : req.headers) {
  13109. body.append(h.first);
  13110. body.push_back(':');
  13111. body.append(h.second);
  13112. body.push_back('\n');
  13113. }
  13114. res.set_content(body, "text/plain");
  13115. });
  13116. port_ = svr_.bind_to_any_port("127.0.0.1");
  13117. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13118. svr_.wait_until_ready();
  13119. }
  13120. void TearDown() override {
  13121. svr_.stop();
  13122. if (thread_.joinable()) thread_.join();
  13123. }
  13124. Server svr_;
  13125. std::thread thread_;
  13126. int port_ = 0;
  13127. };
  13128. TEST_F(OpenStreamTest, Basic) {
  13129. Client cli("127.0.0.1", port_);
  13130. auto handle = cli.open_stream("GET", "/hello");
  13131. EXPECT_TRUE(handle.is_valid());
  13132. EXPECT_EQ("Hello World!", read_all(handle));
  13133. }
  13134. TEST_F(OpenStreamTest, SmallBuffer) {
  13135. Client cli("127.0.0.1", port_);
  13136. auto handle = cli.open_stream("GET", "/hello");
  13137. std::string result;
  13138. char buf[4];
  13139. ssize_t n;
  13140. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13141. result.append(buf, static_cast<size_t>(n));
  13142. EXPECT_EQ("Hello World!", result);
  13143. }
  13144. TEST_F(OpenStreamTest, DefaultHeaders) {
  13145. Client cli("127.0.0.1", port_);
  13146. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13147. {
  13148. auto handle = cli.open_stream("GET", "/echo-headers");
  13149. ASSERT_TRUE(handle.is_valid());
  13150. auto body = read_all(handle);
  13151. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13152. std::string::npos);
  13153. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13154. std::string::npos);
  13155. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13156. }
  13157. // open_stream POST with body and no explicit content_type should NOT add
  13158. // text/plain Content-Type (behavior differs from non-streaming path), but
  13159. // should include Content-Length
  13160. {
  13161. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13162. ASSERT_TRUE(handle.is_valid());
  13163. auto body = read_all(handle);
  13164. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13165. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13166. }
  13167. // open_stream POST with explicit Content-Type should preserve it
  13168. {
  13169. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13170. {{"Content-Type", "application/custom"}},
  13171. "{}", "application/custom");
  13172. ASSERT_TRUE(handle.is_valid());
  13173. auto body = read_all(handle);
  13174. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13175. }
  13176. // User-specified User-Agent must not be overwritten for stream API
  13177. {
  13178. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13179. {{"User-Agent", "MyAgent/1.2"}});
  13180. ASSERT_TRUE(handle.is_valid());
  13181. auto body = read_all(handle);
  13182. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13183. }
  13184. }
  13185. TEST_F(OpenStreamTest, Large) {
  13186. Client cli("127.0.0.1", port_);
  13187. auto handle = cli.open_stream("GET", "/large");
  13188. EXPECT_EQ(10000u, read_all(handle).size());
  13189. }
  13190. TEST_F(OpenStreamTest, ConnectionError) {
  13191. Client cli("127.0.0.1", 9999);
  13192. auto handle = cli.open_stream("GET", "/hello");
  13193. EXPECT_FALSE(handle.is_valid());
  13194. }
  13195. TEST_F(OpenStreamTest, Chunked) {
  13196. Client cli("127.0.0.1", port_);
  13197. auto handle = cli.open_stream("GET", "/chunked");
  13198. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13199. "Transfer-Encoding") == "chunked");
  13200. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13201. }
  13202. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13203. Client cli("127.0.0.1", port_);
  13204. auto handle =
  13205. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13206. ASSERT_TRUE(handle.is_valid());
  13207. // Consume body to allow trailers to be received/parsed
  13208. auto body = read_all(handle);
  13209. // Explicitly parse trailers (ensure trailers are available for assertion)
  13210. handle.parse_trailers_if_needed();
  13211. EXPECT_EQ(std::string("123456789"), body);
  13212. // The response should include a Trailer header declaring both names
  13213. ASSERT_TRUE(handle.response);
  13214. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13215. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13216. handle.response->get_header_value("Trailer"));
  13217. // Prohibited trailer must not be present
  13218. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13219. // Allowed trailer should be present
  13220. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13221. EXPECT_EQ(std::string("yes"),
  13222. handle.response->get_trailer_value("X-Allowed"));
  13223. // Verify trailers are NOT present as regular headers
  13224. EXPECT_EQ(std::string(""),
  13225. handle.response->get_header_value("Content-Length"));
  13226. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13227. }
  13228. static std::thread serve_single_response(std::promise<int> &port_promise,
  13229. const std::string &response) {
  13230. return std::thread([&port_promise, response] {
  13231. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13232. default_socket_options(srv);
  13233. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13234. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13235. sockaddr_in addr{};
  13236. addr.sin_family = AF_INET;
  13237. addr.sin_port = htons(0); // Let OS assign a free port
  13238. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13239. int opt = 1;
  13240. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13241. #ifdef _WIN32
  13242. reinterpret_cast<const char *>(&opt),
  13243. #else
  13244. &opt,
  13245. #endif
  13246. sizeof(opt));
  13247. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13248. ::listen(srv, 1) != 0) {
  13249. port_promise.set_value(-1);
  13250. detail::close_socket(srv);
  13251. return;
  13252. }
  13253. socklen_t addr_len = sizeof(addr);
  13254. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13255. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13256. sockaddr_in cli_addr{};
  13257. socklen_t cli_len = sizeof(cli_addr);
  13258. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13259. if (cli != INVALID_SOCKET) {
  13260. // Read the complete HTTP request (until the blank line that terminates
  13261. // headers) before sending the response. If the server closes the socket
  13262. // while the client's request data is still unread in the kernel receive
  13263. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13264. // connection on both sides: it discards the client's receive buffer
  13265. // (which already holds our response) and causes any in-progress write on
  13266. // the client to fail with ECONNRESET. Reading all request data first
  13267. // ensures close() emits a graceful FIN.
  13268. {
  13269. char rbuf[256];
  13270. std::string req;
  13271. while (req.find("\r\n\r\n") == std::string::npos) {
  13272. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13273. if (n <= 0) { break; }
  13274. req.append(rbuf, static_cast<size_t>(n));
  13275. }
  13276. }
  13277. ::send(cli,
  13278. #ifdef _WIN32
  13279. static_cast<const char *>(response.c_str()),
  13280. static_cast<int>(response.size()),
  13281. #else
  13282. response.c_str(), response.size(),
  13283. #endif
  13284. 0);
  13285. detail::close_socket(cli);
  13286. }
  13287. detail::close_socket(srv);
  13288. });
  13289. }
  13290. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13291. #ifndef _WIN32
  13292. signal(SIGPIPE, SIG_IGN);
  13293. #endif
  13294. std::promise<int> port_promise;
  13295. auto port_future = port_promise.get_future();
  13296. auto server_thread =
  13297. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13298. "Content-Type: text/plain\r\n"
  13299. "Content-Length: not-a-number\r\n"
  13300. "Connection: close\r\n"
  13301. "\r\n"
  13302. "hello");
  13303. auto port = port_future.get();
  13304. ASSERT_GT(port, 0);
  13305. Client cli("127.0.0.1", port);
  13306. auto handle = cli.open_stream("GET", "/");
  13307. EXPECT_FALSE(handle.is_valid());
  13308. server_thread.join();
  13309. }
  13310. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13311. #ifndef _WIN32
  13312. signal(SIGPIPE, SIG_IGN);
  13313. #endif
  13314. std::promise<int> port_promise;
  13315. auto port_future = port_promise.get_future();
  13316. auto server_thread = serve_single_response(
  13317. port_promise, "HTTP/1.1 200 OK\r\n"
  13318. "Content-Type: text/plain\r\n"
  13319. "Content-Length: 99999999999999999999999999\r\n"
  13320. "Connection: close\r\n"
  13321. "\r\n"
  13322. "hello");
  13323. auto port = port_future.get();
  13324. ASSERT_GT(port, 0);
  13325. // Before the fix, std::stoull would throw std::out_of_range here and
  13326. // crash the process. After the fix, strtoull silently clamps to
  13327. // ULLONG_MAX so the stream opens without crashing. The important thing
  13328. // is that the process does NOT terminate.
  13329. Client cli("127.0.0.1", port);
  13330. auto handle = cli.open_stream("GET", "/");
  13331. EXPECT_TRUE(handle.is_valid());
  13332. server_thread.join();
  13333. }
  13334. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13335. TEST_F(OpenStreamTest, Gzip) {
  13336. Client cli("127.0.0.1", port_);
  13337. auto handle = cli.open_stream("GET", "/compressible", {},
  13338. {{"Accept-Encoding", "gzip"}});
  13339. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13340. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13341. }
  13342. #endif
  13343. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13344. TEST_F(OpenStreamTest, Brotli) {
  13345. Client cli("127.0.0.1", port_);
  13346. auto handle =
  13347. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13348. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13349. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13350. }
  13351. #endif
  13352. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13353. TEST_F(OpenStreamTest, Zstd) {
  13354. Client cli("127.0.0.1", port_);
  13355. auto handle = cli.open_stream("GET", "/compressible", {},
  13356. {{"Accept-Encoding", "zstd"}});
  13357. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13358. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13359. }
  13360. #endif
  13361. #ifdef CPPHTTPLIB_SSL_ENABLED
  13362. class SSLOpenStreamTest : public ::testing::Test {
  13363. protected:
  13364. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13365. void SetUp() override {
  13366. svr_.Get("/hello", [](const Request &, Response &res) {
  13367. res.set_content("Hello SSL World!", "text/plain");
  13368. });
  13369. svr_.Get("/chunked", [](const Request &, Response &res) {
  13370. res.set_chunked_content_provider("text/plain",
  13371. [](size_t offset, DataSink &sink) {
  13372. if (offset < 15) {
  13373. sink.write("chunk", 5);
  13374. return true;
  13375. }
  13376. sink.done();
  13377. return true;
  13378. });
  13379. });
  13380. svr_.Post("/echo", [](const Request &req, Response &res) {
  13381. res.set_content(req.body, req.get_header_value("Content-Type"));
  13382. });
  13383. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13384. std::string body = req.body;
  13385. res.set_chunked_content_provider(
  13386. "text/plain", [body](size_t offset, DataSink &sink) {
  13387. if (offset < body.size()) {
  13388. sink.write(body.data() + offset, body.size() - offset);
  13389. }
  13390. sink.done();
  13391. return true;
  13392. });
  13393. });
  13394. port_ = svr_.bind_to_any_port("127.0.0.1");
  13395. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13396. svr_.wait_until_ready();
  13397. }
  13398. void TearDown() override {
  13399. svr_.stop();
  13400. if (thread_.joinable()) thread_.join();
  13401. }
  13402. SSLServer svr_;
  13403. std::thread thread_;
  13404. int port_ = 0;
  13405. };
  13406. TEST_F(SSLOpenStreamTest, Basic) {
  13407. SSLClient cli("127.0.0.1", port_);
  13408. cli.enable_server_certificate_verification(false);
  13409. auto handle = cli.open_stream("GET", "/hello");
  13410. ASSERT_TRUE(handle.is_valid());
  13411. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13412. }
  13413. TEST_F(SSLOpenStreamTest, Chunked) {
  13414. SSLClient cli("127.0.0.1", port_);
  13415. cli.enable_server_certificate_verification(false);
  13416. auto handle = cli.open_stream("GET", "/chunked");
  13417. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13418. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13419. "Transfer-Encoding") == "chunked");
  13420. auto body = read_all(handle);
  13421. EXPECT_EQ("chunkchunkchunk", body);
  13422. }
  13423. TEST_F(SSLOpenStreamTest, Post) {
  13424. SSLClient cli("127.0.0.1", port_);
  13425. cli.enable_server_certificate_verification(false);
  13426. auto handle =
  13427. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13428. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13429. EXPECT_EQ(200, handle.response->status);
  13430. auto body = read_all(handle);
  13431. EXPECT_EQ("Hello SSL POST", body);
  13432. }
  13433. TEST_F(SSLOpenStreamTest, PostChunked) {
  13434. SSLClient cli("127.0.0.1", port_);
  13435. cli.enable_server_certificate_verification(false);
  13436. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13437. "Chunked SSL Data", "text/plain");
  13438. ASSERT_TRUE(handle.is_valid());
  13439. EXPECT_EQ(200, handle.response->status);
  13440. auto body = read_all(handle);
  13441. EXPECT_EQ("Chunked SSL Data", body);
  13442. }
  13443. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13444. // Content-Length is terminated by the server closing the connection. When the
  13445. // SSL peer sends a close_notify after the body, the client must treat it as a
  13446. // clean EOF and return a successful response rather than an error.
  13447. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13449. ASSERT_TRUE(svr.is_valid());
  13450. svr.set_keep_alive_max_count(1);
  13451. const std::string expected_body = "Hello from connection-close response!";
  13452. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13453. res.set_content_provider("text/plain",
  13454. [&](size_t offset, DataSink &sink) -> bool {
  13455. if (offset < expected_body.size()) {
  13456. sink.write(expected_body.data() + offset,
  13457. expected_body.size() - offset);
  13458. }
  13459. sink.done();
  13460. return true;
  13461. });
  13462. });
  13463. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13464. auto se = detail::scope_exit([&] {
  13465. svr.stop();
  13466. listen_thread.join();
  13467. ASSERT_FALSE(svr.is_running());
  13468. });
  13469. svr.wait_until_ready();
  13470. SSLClient cli(HOST, PORT);
  13471. cli.enable_server_certificate_verification(false);
  13472. auto res = cli.Get("/no-content-length");
  13473. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13474. EXPECT_EQ(StatusCode::OK_200, res->status);
  13475. EXPECT_EQ(expected_body, res->body);
  13476. }
  13477. #endif // CPPHTTPLIB_SSL_ENABLED
  13478. //==============================================================================
  13479. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13480. // results for various scenarios.
  13481. //==============================================================================
  13482. TEST(ParityTest, GetVsOpenStream) {
  13483. Server svr;
  13484. const std::string path = "/parity";
  13485. const std::string content = "Parity test content: hello world";
  13486. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13487. res.set_content(content, "text/plain");
  13488. });
  13489. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13490. auto se = detail::scope_exit([&] {
  13491. svr.stop();
  13492. t.join();
  13493. ASSERT_FALSE(svr.is_running());
  13494. });
  13495. svr.wait_until_ready();
  13496. Client cli(HOST, PORT);
  13497. // Non-stream path
  13498. auto r1 = cli.Get(path);
  13499. ASSERT_TRUE(r1);
  13500. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13501. // Stream path
  13502. auto h = cli.open_stream("GET", path);
  13503. ASSERT_TRUE(h.is_valid());
  13504. EXPECT_EQ(r1->body, read_all(h));
  13505. }
  13506. // Helper to compress data with provided compressor type T
  13507. template <typename Compressor>
  13508. static std::string compress_payload_for_parity(const std::string &in) {
  13509. std::string out;
  13510. Compressor compressor;
  13511. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13512. [&](const char *data, size_t n) {
  13513. out.append(data, n);
  13514. return true;
  13515. });
  13516. EXPECT_TRUE(ok);
  13517. return out;
  13518. }
  13519. // Helper function for compression parity tests
  13520. template <typename Compressor>
  13521. static void test_compression_parity(const std::string &original,
  13522. const std::string &path,
  13523. const std::string &encoding) {
  13524. const std::string compressed =
  13525. compress_payload_for_parity<Compressor>(original);
  13526. Server svr;
  13527. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13528. res.set_content(compressed, "application/octet-stream");
  13529. res.set_header("Content-Encoding", encoding);
  13530. });
  13531. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13532. auto se = detail::scope_exit([&] {
  13533. svr.stop();
  13534. t.join();
  13535. ASSERT_FALSE(svr.is_running());
  13536. });
  13537. svr.wait_until_ready();
  13538. Client cli(HOST, PORT);
  13539. // Non-streaming
  13540. {
  13541. auto res = cli.Get(path);
  13542. ASSERT_TRUE(res);
  13543. EXPECT_EQ(StatusCode::OK_200, res->status);
  13544. EXPECT_EQ(original, res->body);
  13545. }
  13546. // Streaming
  13547. {
  13548. auto h = cli.open_stream("GET", path);
  13549. ASSERT_TRUE(h.is_valid());
  13550. EXPECT_EQ(original, read_all(h));
  13551. }
  13552. }
  13553. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13554. TEST(ParityTest, Gzip) {
  13555. test_compression_parity<detail::gzip_compressor>(
  13556. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13557. }
  13558. #endif
  13559. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13560. TEST(ParityTest, Brotli) {
  13561. test_compression_parity<detail::brotli_compressor>(
  13562. "Hello, brotli parity test payload", "/parity-br", "br");
  13563. }
  13564. #endif
  13565. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13566. TEST(ParityTest, Zstd) {
  13567. test_compression_parity<detail::zstd_compressor>(
  13568. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13569. }
  13570. #endif
  13571. //==============================================================================
  13572. // New Stream API Tests
  13573. //==============================================================================
  13574. inline std::string read_body(httplib::stream::Result &result) {
  13575. std::string body;
  13576. while (result.next()) {
  13577. body.append(result.data(), result.size());
  13578. }
  13579. return body;
  13580. }
  13581. TEST(ClientConnectionTest, Basic) {
  13582. httplib::ClientConnection conn;
  13583. EXPECT_FALSE(conn.is_open());
  13584. conn.sock = 1;
  13585. EXPECT_TRUE(conn.is_open());
  13586. httplib::ClientConnection conn2(std::move(conn));
  13587. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13588. conn2.sock = INVALID_SOCKET;
  13589. }
  13590. // Unified test server for all stream::* tests
  13591. class StreamApiTest : public ::testing::Test {
  13592. protected:
  13593. void SetUp() override {
  13594. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13595. res.set_content("Hello World!", "text/plain");
  13596. });
  13597. svr_.Get("/echo-params",
  13598. [](const httplib::Request &req, httplib::Response &res) {
  13599. std::string r;
  13600. for (const auto &p : req.params) {
  13601. if (!r.empty()) r += "&";
  13602. r += p.first + "=" + p.second;
  13603. }
  13604. res.set_content(r, "text/plain");
  13605. });
  13606. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13607. res.set_content(req.body, req.get_header_value("Content-Type"));
  13608. });
  13609. svr_.Post("/echo-headers",
  13610. [](const httplib::Request &req, httplib::Response &res) {
  13611. std::string r;
  13612. for (const auto &h : req.headers)
  13613. r += h.first + ": " + h.second + "\n";
  13614. res.set_content(r, "text/plain");
  13615. });
  13616. svr_.Post("/echo-params",
  13617. [](const httplib::Request &req, httplib::Response &res) {
  13618. std::string r = "params:";
  13619. for (const auto &p : req.params)
  13620. r += p.first + "=" + p.second + ";";
  13621. res.set_content(r + " body:" + req.body, "text/plain");
  13622. });
  13623. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13624. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13625. });
  13626. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13627. res.set_content("PUT:" + req.body, "text/plain");
  13628. });
  13629. svr_.Patch("/echo",
  13630. [](const httplib::Request &req, httplib::Response &res) {
  13631. res.set_content("PATCH:" + req.body, "text/plain");
  13632. });
  13633. svr_.Delete(
  13634. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13635. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13636. "text/plain");
  13637. });
  13638. svr_.Get("/head-test",
  13639. [](const httplib::Request &, httplib::Response &res) {
  13640. res.set_content("body for HEAD", "text/plain");
  13641. });
  13642. svr_.Options("/options",
  13643. [](const httplib::Request &, httplib::Response &res) {
  13644. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13645. });
  13646. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13647. svr_.wait_until_ready();
  13648. }
  13649. void TearDown() override {
  13650. svr_.stop();
  13651. if (thread_.joinable()) thread_.join();
  13652. }
  13653. httplib::Server svr_;
  13654. std::thread thread_;
  13655. };
  13656. // stream::Get tests
  13657. TEST_F(StreamApiTest, GetBasic) {
  13658. httplib::Client cli(HOST, PORT);
  13659. auto result = httplib::stream::Get(cli, "/hello");
  13660. ASSERT_TRUE(result.is_valid());
  13661. EXPECT_EQ(200, result.status());
  13662. EXPECT_EQ("Hello World!", read_body(result));
  13663. }
  13664. TEST_F(StreamApiTest, GetWithParams) {
  13665. httplib::Client cli(HOST, PORT);
  13666. httplib::Params params{{"foo", "bar"}};
  13667. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13668. ASSERT_TRUE(result.is_valid());
  13669. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13670. }
  13671. TEST_F(StreamApiTest, GetConnectionError) {
  13672. httplib::Client cli(HOST, 9999);
  13673. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13674. }
  13675. TEST_F(StreamApiTest, Get404) {
  13676. httplib::Client cli(HOST, PORT);
  13677. auto result = httplib::stream::Get(cli, "/nonexistent");
  13678. EXPECT_TRUE(result.is_valid());
  13679. EXPECT_EQ(404, result.status());
  13680. }
  13681. // stream::Post tests
  13682. TEST_F(StreamApiTest, PostBasic) {
  13683. httplib::Client cli(HOST, PORT);
  13684. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13685. "application/json");
  13686. ASSERT_TRUE(result.is_valid());
  13687. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13688. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13689. }
  13690. TEST_F(StreamApiTest, PostWithHeaders) {
  13691. httplib::Client cli(HOST, PORT);
  13692. httplib::Headers headers{{"X-Custom", "value"}};
  13693. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13694. "text/plain");
  13695. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13696. }
  13697. TEST_F(StreamApiTest, PostWithParams) {
  13698. httplib::Client cli(HOST, PORT);
  13699. httplib::Params params{{"k", "v"}};
  13700. auto result =
  13701. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13702. auto body = read_body(result);
  13703. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13704. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13705. }
  13706. TEST_F(StreamApiTest, PostLarge) {
  13707. httplib::Client cli(HOST, PORT);
  13708. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13709. size_t total = 0;
  13710. while (result.next()) {
  13711. total += result.size();
  13712. }
  13713. EXPECT_EQ(100u * 1024u, total);
  13714. }
  13715. // stream::Put/Patch tests
  13716. TEST_F(StreamApiTest, PutAndPatch) {
  13717. httplib::Client cli(HOST, PORT);
  13718. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13719. EXPECT_EQ("PUT:test", read_body(put));
  13720. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13721. EXPECT_EQ("PATCH:test", read_body(patch));
  13722. }
  13723. // stream::Delete tests
  13724. TEST_F(StreamApiTest, Delete) {
  13725. httplib::Client cli(HOST, PORT);
  13726. auto del1 = httplib::stream::Delete(cli, "/resource");
  13727. EXPECT_EQ("Deleted", read_body(del1));
  13728. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13729. EXPECT_EQ("Deleted:data", read_body(del2));
  13730. }
  13731. // stream::Head/Options tests
  13732. TEST_F(StreamApiTest, HeadAndOptions) {
  13733. httplib::Client cli(HOST, PORT);
  13734. auto head = httplib::stream::Head(cli, "/head-test");
  13735. EXPECT_TRUE(head.is_valid());
  13736. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13737. auto opts = httplib::stream::Options(cli, "/options");
  13738. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13739. }
  13740. // SSL stream::* tests
  13741. #ifdef CPPHTTPLIB_SSL_ENABLED
  13742. class SSLStreamApiTest : public ::testing::Test {
  13743. protected:
  13744. void SetUp() override {
  13745. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13746. res.set_content("Hello SSL!", "text/plain");
  13747. });
  13748. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13749. res.set_content(req.body, "text/plain");
  13750. });
  13751. port_ = svr_.bind_to_any_port("127.0.0.1");
  13752. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13753. svr_.wait_until_ready();
  13754. }
  13755. void TearDown() override {
  13756. svr_.stop();
  13757. if (thread_.joinable()) thread_.join();
  13758. }
  13759. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13760. std::thread thread_;
  13761. int port_ = 0;
  13762. };
  13763. TEST_F(SSLStreamApiTest, GetAndPost) {
  13764. httplib::SSLClient cli("127.0.0.1", port_);
  13765. cli.enable_server_certificate_verification(false);
  13766. auto get = httplib::stream::Get(cli, "/hello");
  13767. EXPECT_EQ("Hello SSL!", read_body(get));
  13768. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13769. EXPECT_EQ("test", read_body(post));
  13770. }
  13771. #endif
  13772. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13773. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13774. // BodyReader
  13775. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13776. // Test that read timeout during streaming is detected
  13777. // Use a large content-length response where server delays mid-stream
  13778. Server svr;
  13779. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13780. // Send a large response with delay in the middle
  13781. res.set_content_provider(
  13782. 1000, // content_length
  13783. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13784. if (offset < 100) {
  13785. // Send first 100 bytes immediately
  13786. std::string data(100, 'A');
  13787. sink.write(data.c_str(), data.size());
  13788. return true;
  13789. }
  13790. // Then delay longer than client timeout
  13791. std::this_thread::sleep_for(std::chrono::seconds(3));
  13792. std::string data(900, 'B');
  13793. sink.write(data.c_str(), data.size());
  13794. return true;
  13795. });
  13796. });
  13797. auto port = 8091;
  13798. std::thread t([&]() { svr.listen("localhost", port); });
  13799. svr.wait_until_ready();
  13800. Client cli("localhost", port);
  13801. cli.set_read_timeout(1, 0); // 1 second timeout
  13802. auto handle = cli.open_stream("GET", "/slow-stream");
  13803. ASSERT_TRUE(handle.is_valid());
  13804. char buf[256];
  13805. ssize_t total = 0;
  13806. ssize_t n;
  13807. bool got_error = false;
  13808. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13809. total += n;
  13810. }
  13811. if (n < 0) {
  13812. got_error = true;
  13813. // Should be timeout or read error
  13814. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13815. handle.get_read_error() == Error::Read)
  13816. << "Actual error: " << to_string(handle.get_read_error());
  13817. }
  13818. // Either we got an error, or we got less data than expected
  13819. EXPECT_TRUE(got_error || total < 1000)
  13820. << "Expected timeout but got all " << total << " bytes";
  13821. svr.stop();
  13822. t.join();
  13823. }
  13824. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13825. // Test connection closed detection via BodyReader
  13826. Server svr;
  13827. std::atomic<bool> close_now{false};
  13828. svr.Get("/will-close", [&](const Request &, Response &res) {
  13829. res.set_content_provider(
  13830. 10000, // Large content_length that we won't fully send
  13831. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13832. if (offset < 100) {
  13833. std::string data(100, 'X');
  13834. sink.write(data.c_str(), data.size());
  13835. return true;
  13836. }
  13837. // Wait for signal then abort
  13838. while (!close_now) {
  13839. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13840. }
  13841. return false; // Abort - server will close connection
  13842. });
  13843. });
  13844. auto port = 8092;
  13845. std::thread t([&]() { svr.listen("localhost", port); });
  13846. svr.wait_until_ready();
  13847. Client cli("localhost", port);
  13848. auto handle = cli.open_stream("GET", "/will-close");
  13849. ASSERT_TRUE(handle.is_valid());
  13850. char buf[256];
  13851. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13852. EXPECT_GT(n, 0) << "First read should succeed";
  13853. // Signal server to close
  13854. close_now = true;
  13855. // Keep reading until error or EOF
  13856. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13857. // Keep reading
  13858. }
  13859. // Should get an error since content_length wasn't satisfied
  13860. if (n < 0) {
  13861. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13862. handle.get_read_error() == Error::Read)
  13863. << "Actual error: " << to_string(handle.get_read_error());
  13864. }
  13865. svr.stop();
  13866. t.join();
  13867. }
  13868. #ifdef CPPHTTPLIB_SSL_ENABLED
  13869. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13870. // Test that read timeout during SSL streaming is detected
  13871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13872. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13873. res.set_content_provider(
  13874. 1000, "text/plain",
  13875. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13876. if (offset < 100) {
  13877. std::string data(100, 'A');
  13878. sink.write(data.c_str(), data.size());
  13879. return true;
  13880. }
  13881. std::this_thread::sleep_for(std::chrono::seconds(3));
  13882. std::string data(900, 'B');
  13883. sink.write(data.c_str(), data.size());
  13884. return true;
  13885. });
  13886. });
  13887. auto port = 8093;
  13888. std::thread t([&]() { svr.listen("localhost", port); });
  13889. svr.wait_until_ready();
  13890. SSLClient cli("localhost", port);
  13891. cli.enable_server_certificate_verification(false);
  13892. cli.set_read_timeout(1, 0); // 1 second timeout
  13893. auto handle = cli.open_stream("GET", "/slow-stream");
  13894. ASSERT_TRUE(handle.is_valid());
  13895. char buf[256];
  13896. ssize_t total = 0;
  13897. ssize_t n;
  13898. bool got_error = false;
  13899. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13900. total += n;
  13901. }
  13902. if (n < 0) {
  13903. got_error = true;
  13904. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13905. handle.get_read_error() == Error::Read)
  13906. << "Actual error: " << to_string(handle.get_read_error());
  13907. }
  13908. EXPECT_TRUE(got_error || total < 1000)
  13909. << "Expected timeout but got all " << total << " bytes";
  13910. svr.stop();
  13911. t.join();
  13912. }
  13913. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13914. // Test SSL connection closed detection
  13915. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13916. std::atomic<bool> close_now{false};
  13917. svr.Get("/will-close", [&](const Request &, Response &res) {
  13918. res.set_content_provider(
  13919. 10000, "text/plain",
  13920. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13921. if (offset < 100) {
  13922. std::string data(100, 'X');
  13923. sink.write(data.c_str(), data.size());
  13924. return true;
  13925. }
  13926. while (!close_now) {
  13927. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13928. }
  13929. return false;
  13930. });
  13931. });
  13932. auto port = 8094;
  13933. std::thread t([&]() { svr.listen("localhost", port); });
  13934. svr.wait_until_ready();
  13935. SSLClient cli("localhost", port);
  13936. cli.enable_server_certificate_verification(false);
  13937. auto handle = cli.open_stream("GET", "/will-close");
  13938. ASSERT_TRUE(handle.is_valid());
  13939. char buf[256];
  13940. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13941. EXPECT_GT(n, 0);
  13942. // Signal server to close
  13943. close_now = true;
  13944. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13945. // Keep reading
  13946. }
  13947. if (n < 0) {
  13948. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13949. handle.get_read_error() == Error::Read)
  13950. << "Actual error: " << to_string(handle.get_read_error());
  13951. }
  13952. svr.stop();
  13953. t.join();
  13954. }
  13955. #endif
  13956. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13957. using namespace httplib;
  13958. // Create a test file
  13959. const char *fname = "etag_testfile.txt";
  13960. const char *content = "etag-content";
  13961. {
  13962. std::ofstream ofs(fname);
  13963. ofs << content;
  13964. ASSERT_TRUE(ofs.good());
  13965. }
  13966. Server svr;
  13967. svr.set_mount_point("/static", ".");
  13968. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13969. svr.wait_until_ready();
  13970. Client cli(HOST, PORT);
  13971. // First request: should get 200 with ETag header
  13972. auto res1 = cli.Get("/static/etag_testfile.txt");
  13973. ASSERT_TRUE(res1);
  13974. ASSERT_EQ(200, res1->status);
  13975. ASSERT_TRUE(res1->has_header("ETag"));
  13976. std::string etag = res1->get_header_value("ETag");
  13977. EXPECT_FALSE(etag.empty());
  13978. // Verify ETag format: W/"hex-hex"
  13979. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13980. EXPECT_EQ('W', etag[0]);
  13981. EXPECT_EQ('/', etag[1]);
  13982. EXPECT_EQ('"', etag[2]);
  13983. EXPECT_EQ('"', etag.back());
  13984. // Exact match: expect 304 Not Modified
  13985. Headers h2 = {{"If-None-Match", etag}};
  13986. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13987. ASSERT_TRUE(res2);
  13988. EXPECT_EQ(304, res2->status);
  13989. // Wildcard match: expect 304 Not Modified
  13990. Headers h3 = {{"If-None-Match", "*"}};
  13991. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13992. ASSERT_TRUE(res3);
  13993. EXPECT_EQ(304, res3->status);
  13994. // Non-matching ETag: expect 200
  13995. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13996. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13997. ASSERT_TRUE(res4);
  13998. EXPECT_EQ(200, res4->status);
  13999. // Multiple ETags with one matching: expect 304
  14000. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14001. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14002. ASSERT_TRUE(res5);
  14003. EXPECT_EQ(304, res5->status);
  14004. svr.stop();
  14005. t.join();
  14006. std::remove(fname);
  14007. }
  14008. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14009. using namespace httplib;
  14010. Server svr;
  14011. svr.set_mount_point("/static", ".");
  14012. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14013. svr.wait_until_ready();
  14014. Client cli(HOST, PORT);
  14015. // Send If-None-Match: * to a non-existent file
  14016. Headers h = {{"If-None-Match", "*"}};
  14017. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14018. ASSERT_TRUE(res);
  14019. EXPECT_EQ(404, res->status);
  14020. svr.stop();
  14021. t.join();
  14022. }
  14023. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14024. using namespace httplib;
  14025. // Create a test file
  14026. const char *fname = "etag_boundary_testfile.txt";
  14027. const char *content = "boundary-test";
  14028. {
  14029. std::ofstream ofs(fname);
  14030. ofs << content;
  14031. ASSERT_TRUE(ofs.good());
  14032. }
  14033. Server svr;
  14034. svr.set_mount_point("/static", ".");
  14035. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14036. svr.wait_until_ready();
  14037. Client cli(HOST, PORT);
  14038. // Get the actual ETag
  14039. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14040. ASSERT_TRUE(res1);
  14041. ASSERT_EQ(200, res1->status);
  14042. ASSERT_TRUE(res1->has_header("ETag"));
  14043. std::string etag = res1->get_header_value("ETag");
  14044. // Test 1: Very long ETag value (longer than actual ETag)
  14045. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14046. Headers h1 = {{"If-None-Match", "W/"
  14047. "\"very-long-etag-value-that-is-much-longer-"
  14048. "than-the-actual-etag-value\""}};
  14049. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14050. ASSERT_TRUE(res2);
  14051. EXPECT_EQ(200, res2->status); // Should not match
  14052. // Test 2: Long string followed by wildcard
  14053. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14054. // string)
  14055. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14056. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14057. ASSERT_TRUE(res3);
  14058. EXPECT_EQ(304, res3->status); // Should match on "*"
  14059. // Test 3: Wildcard followed by long string
  14060. // Should match on "*" immediately and return 304
  14061. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14062. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14063. ASSERT_TRUE(res4);
  14064. EXPECT_EQ(304, res4->status); // Should match on "*"
  14065. // Test 4: Multiple long non-matching values
  14066. // Should NOT match and return 200 (test that all comparisons are safe)
  14067. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14068. "W/\"second-long-non-matching-value\", "
  14069. "W/\"third-long-non-matching-value\""}};
  14070. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14071. ASSERT_TRUE(res5);
  14072. EXPECT_EQ(200, res5->status); // Should not match
  14073. // Test 5: Single character that is not "*" (edge case)
  14074. Headers h5 = {{"If-None-Match", "X"}};
  14075. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14076. ASSERT_TRUE(res6);
  14077. EXPECT_EQ(200, res6->status); // Should not match
  14078. svr.stop();
  14079. t.join();
  14080. std::remove(fname);
  14081. }
  14082. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14083. using namespace httplib;
  14084. // Create a test file
  14085. const char *fname = "ims_testfile.txt";
  14086. const char *content = "if-modified-since-test";
  14087. {
  14088. std::ofstream ofs(fname);
  14089. ofs << content;
  14090. ASSERT_TRUE(ofs.good());
  14091. }
  14092. Server svr;
  14093. svr.set_mount_point("/static", ".");
  14094. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14095. svr.wait_until_ready();
  14096. Client cli(HOST, PORT);
  14097. // First request: should get 200 with Last-Modified header
  14098. auto res1 = cli.Get("/static/ims_testfile.txt");
  14099. ASSERT_TRUE(res1);
  14100. ASSERT_EQ(200, res1->status);
  14101. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14102. std::string last_modified = res1->get_header_value("Last-Modified");
  14103. EXPECT_FALSE(last_modified.empty());
  14104. // If-Modified-Since with same time: expect 304
  14105. Headers h2 = {{"If-Modified-Since", last_modified}};
  14106. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14107. ASSERT_TRUE(res2);
  14108. EXPECT_EQ(304, res2->status);
  14109. // If-Modified-Since with future time: expect 304
  14110. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14111. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14112. ASSERT_TRUE(res3);
  14113. EXPECT_EQ(304, res3->status);
  14114. // If-Modified-Since with past time: expect 200
  14115. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14116. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14117. ASSERT_TRUE(res4);
  14118. EXPECT_EQ(200, res4->status);
  14119. // If-None-Match takes precedence over If-Modified-Since
  14120. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14121. ASSERT_TRUE(res1->has_header("ETag"));
  14122. std::string etag = res1->get_header_value("ETag");
  14123. Headers h5 = {{"If-None-Match", etag},
  14124. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14125. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14126. ASSERT_TRUE(res5);
  14127. EXPECT_EQ(304, res5->status);
  14128. svr.stop();
  14129. t.join();
  14130. std::remove(fname);
  14131. }
  14132. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14133. using namespace httplib;
  14134. Server svr;
  14135. // Endpoint that returns compressible content
  14136. svr.Get("/compressible", [](const Request &, Response &res) {
  14137. // Return a large enough body to trigger compression
  14138. std::string body(1000, 'a');
  14139. res.set_content(body, "text/plain");
  14140. });
  14141. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14142. svr.wait_until_ready();
  14143. Client cli(HOST, PORT);
  14144. // Request with gzip support: should get Vary header when compressed
  14145. cli.set_compress(true);
  14146. auto res1 = cli.Get("/compressible");
  14147. ASSERT_TRUE(res1);
  14148. EXPECT_EQ(200, res1->status);
  14149. // If Content-Encoding is set, Vary should also be set
  14150. if (res1->has_header("Content-Encoding")) {
  14151. EXPECT_TRUE(res1->has_header("Vary"));
  14152. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14153. }
  14154. // Request without Accept-Encoding header: should not have compression
  14155. Headers h_no_compress;
  14156. auto res2 = cli.Get("/compressible", h_no_compress);
  14157. ASSERT_TRUE(res2);
  14158. EXPECT_EQ(200, res2->status);
  14159. // Verify Vary header is present when compression is applied
  14160. // (the exact behavior depends on server configuration)
  14161. svr.stop();
  14162. t.join();
  14163. }
  14164. TEST(ETagTest, IfRangeWithETag) {
  14165. using namespace httplib;
  14166. // Create a test file with known content
  14167. const char *fname = "if_range_testfile.txt";
  14168. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14169. {
  14170. std::ofstream ofs(fname);
  14171. ofs << content;
  14172. ASSERT_TRUE(ofs.good());
  14173. }
  14174. Server svr;
  14175. svr.set_mount_point("/static", ".");
  14176. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14177. svr.wait_until_ready();
  14178. Client cli(HOST, PORT);
  14179. // First request: get ETag
  14180. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14181. ASSERT_TRUE(res1);
  14182. ASSERT_EQ(200, res1->status);
  14183. ASSERT_TRUE(res1->has_header("ETag"));
  14184. std::string etag = res1->get_header_value("ETag");
  14185. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14186. // Since our server generates weak ETags (W/"..."), If-Range with our
  14187. // ETag should NOT result in partial content - it should return full content.
  14188. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14189. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14190. ASSERT_TRUE(res2);
  14191. // Weak ETag in If-Range -> full content (200), not partial (206)
  14192. EXPECT_EQ(200, res2->status);
  14193. EXPECT_EQ(content, res2->body);
  14194. EXPECT_FALSE(res2->has_header("Content-Range"));
  14195. // Range request with non-matching If-Range (ETag): should get 200 (full
  14196. // content)
  14197. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14198. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14199. ASSERT_TRUE(res3);
  14200. EXPECT_EQ(200, res3->status);
  14201. EXPECT_EQ(content, res3->body);
  14202. EXPECT_FALSE(res3->has_header("Content-Range"));
  14203. // Range request with strong ETag (hypothetical - our server doesn't generate
  14204. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14205. // should return full content)
  14206. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14207. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14208. ASSERT_TRUE(res4);
  14209. EXPECT_EQ(200, res4->status);
  14210. EXPECT_EQ(content, res4->body);
  14211. EXPECT_FALSE(res4->has_header("Content-Range"));
  14212. svr.stop();
  14213. t.join();
  14214. std::remove(fname);
  14215. }
  14216. TEST(ETagTest, IfRangeWithDate) {
  14217. using namespace httplib;
  14218. // Create a test file
  14219. const char *fname = "if_range_date_testfile.txt";
  14220. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14221. {
  14222. std::ofstream ofs(fname);
  14223. ofs << content;
  14224. ASSERT_TRUE(ofs.good());
  14225. }
  14226. Server svr;
  14227. svr.set_mount_point("/static", ".");
  14228. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14229. svr.wait_until_ready();
  14230. Client cli(HOST, PORT);
  14231. // First request: get Last-Modified
  14232. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14233. ASSERT_TRUE(res1);
  14234. ASSERT_EQ(200, res1->status);
  14235. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14236. std::string last_modified = res1->get_header_value("Last-Modified");
  14237. // Range request with matching If-Range (date): should get 206
  14238. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14239. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14240. ASSERT_TRUE(res2);
  14241. EXPECT_EQ(206, res2->status);
  14242. EXPECT_EQ("FGHIJ", res2->body);
  14243. // Range request with old If-Range date: should get 200 (full content)
  14244. Headers h3 = {{"Range", "bytes=5-9"},
  14245. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14246. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14247. ASSERT_TRUE(res3);
  14248. EXPECT_EQ(200, res3->status);
  14249. EXPECT_EQ(content, res3->body);
  14250. // Range request with future If-Range date: should get 206
  14251. Headers h4 = {{"Range", "bytes=0-4"},
  14252. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14253. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14254. ASSERT_TRUE(res4);
  14255. EXPECT_EQ(206, res4->status);
  14256. EXPECT_EQ("ABCDE", res4->body);
  14257. svr.stop();
  14258. t.join();
  14259. std::remove(fname);
  14260. }
  14261. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14262. using namespace httplib;
  14263. const char *fname = "etag_malformed.txt";
  14264. const char *content = "malformed-etag";
  14265. {
  14266. std::ofstream ofs(fname);
  14267. ofs << content;
  14268. ASSERT_TRUE(ofs.good());
  14269. }
  14270. Server svr;
  14271. svr.set_mount_point("/static", ".");
  14272. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14273. svr.wait_until_ready();
  14274. Client cli(HOST, PORT);
  14275. // baseline: should get 200 and an ETag
  14276. auto res1 = cli.Get("/static/etag_malformed.txt");
  14277. ASSERT_TRUE(res1);
  14278. ASSERT_EQ(200, res1->status);
  14279. ASSERT_TRUE(res1->has_header("ETag"));
  14280. // Malformed ETag value (missing quotes) should be treated as non-matching
  14281. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14282. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14283. ASSERT_TRUE(res_bad);
  14284. EXPECT_EQ(200, res_bad->status);
  14285. // Whitespace-only header value should be considered invalid / non-matching
  14286. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14287. "Host: localhost\r\n"
  14288. "If-None-Match: \r\n"
  14289. "Connection: close\r\n"
  14290. "\r\n";
  14291. std::string out;
  14292. ASSERT_TRUE(send_request(5, raw_req, &out));
  14293. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14294. svr.stop();
  14295. t.join();
  14296. std::remove(fname);
  14297. }
  14298. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14299. using namespace httplib;
  14300. const char *fname = "ims_invalid_format.txt";
  14301. const char *content = "ims-bad-format";
  14302. {
  14303. std::ofstream ofs(fname);
  14304. ofs << content;
  14305. ASSERT_TRUE(ofs.good());
  14306. }
  14307. Server svr;
  14308. svr.set_mount_point("/static", ".");
  14309. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14310. svr.wait_until_ready();
  14311. Client cli(HOST, PORT);
  14312. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14313. ASSERT_TRUE(res1);
  14314. ASSERT_EQ(200, res1->status);
  14315. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14316. // If-Modified-Since with invalid format should not result in 304
  14317. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14318. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14319. ASSERT_TRUE(res_bad);
  14320. EXPECT_EQ(200, res_bad->status);
  14321. // If-Range with invalid date format should be treated as mismatch -> full
  14322. // content (200)
  14323. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14324. {"If-Range", "invalid-date"}};
  14325. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14326. ASSERT_TRUE(res_ifrange);
  14327. EXPECT_EQ(200, res_ifrange->status);
  14328. svr.stop();
  14329. t.join();
  14330. std::remove(fname);
  14331. }
  14332. TEST(ETagTest, IfRangeWithMalformedETag) {
  14333. using namespace httplib;
  14334. const char *fname = "ifrange_malformed.txt";
  14335. const std::string content = "0123456789";
  14336. {
  14337. std::ofstream ofs(fname);
  14338. ofs << content;
  14339. ASSERT_TRUE(ofs.good());
  14340. }
  14341. Server svr;
  14342. svr.set_mount_point("/static", ".");
  14343. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14344. svr.wait_until_ready();
  14345. Client cli(HOST, PORT);
  14346. // First request: get ETag
  14347. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14348. ASSERT_TRUE(res1);
  14349. ASSERT_EQ(200, res1->status);
  14350. ASSERT_TRUE(res1->has_header("ETag"));
  14351. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14352. // full content (200)
  14353. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14354. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14355. ASSERT_TRUE(res2);
  14356. EXPECT_EQ(200, res2->status);
  14357. EXPECT_EQ(content, res2->body);
  14358. svr.stop();
  14359. t.join();
  14360. std::remove(fname);
  14361. }
  14362. TEST(ETagTest, ExtremeLargeDateValues) {
  14363. using namespace httplib;
  14364. const char *fname = "ims_extreme_date.txt";
  14365. const char *content = "ims-extreme-date";
  14366. {
  14367. std::ofstream ofs(fname);
  14368. ofs << content;
  14369. ASSERT_TRUE(ofs.good());
  14370. }
  14371. Server svr;
  14372. svr.set_mount_point("/static", ".");
  14373. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14374. svr.wait_until_ready();
  14375. Client cli(HOST, PORT);
  14376. auto res1 = cli.Get(std::string("/static/") + fname);
  14377. ASSERT_TRUE(res1);
  14378. ASSERT_EQ(200, res1->status);
  14379. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14380. // Extremely large year that may overflow date parsing routines.
  14381. Headers h_large_date = {
  14382. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14383. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14384. ASSERT_TRUE(res_bad);
  14385. // Expect server to treat this as invalid/mismatch and return full content
  14386. EXPECT_EQ(200, res_bad->status);
  14387. // If-Range with extremely large date should be treated as mismatch -> full
  14388. // content (200)
  14389. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14390. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14391. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14392. ASSERT_TRUE(res_ifrange);
  14393. EXPECT_EQ(200, res_ifrange->status);
  14394. svr.stop();
  14395. t.join();
  14396. std::remove(fname);
  14397. }
  14398. TEST(ETagTest, NegativeFileModificationTime) {
  14399. using namespace httplib;
  14400. const char *fname = "ims_negative_mtime.txt";
  14401. const std::string content = "negative-mtime";
  14402. {
  14403. std::ofstream ofs(fname);
  14404. ofs << content;
  14405. ASSERT_TRUE(ofs.good());
  14406. }
  14407. // Try to set file mtime to a negative value. This may fail on some
  14408. // platforms/filesystems; if it fails, the test will still verify server
  14409. // behaves safely by performing a regular conditional request.
  14410. #if defined(__APPLE__) || defined(__linux__)
  14411. bool set_negative = false;
  14412. do {
  14413. struct timeval times[2];
  14414. // access time: now
  14415. times[0].tv_sec = time(nullptr);
  14416. times[0].tv_usec = 0;
  14417. // modification time: negative (e.g., -1)
  14418. times[1].tv_sec = -1;
  14419. times[1].tv_usec = 0;
  14420. if (utimes(fname, times) == 0) { set_negative = true; }
  14421. } while (0);
  14422. #else
  14423. bool set_negative = false;
  14424. #endif
  14425. Server svr;
  14426. svr.set_mount_point("/static", ".");
  14427. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14428. svr.wait_until_ready();
  14429. Client cli(HOST, PORT);
  14430. auto res1 = cli.Get(std::string("/static/") + fname);
  14431. ASSERT_TRUE(res1);
  14432. ASSERT_EQ(200, res1->status);
  14433. bool has_last_modified = res1->has_header("Last-Modified");
  14434. std::string last_modified;
  14435. if (has_last_modified) {
  14436. last_modified = res1->get_header_value("Last-Modified");
  14437. }
  14438. if (set_negative) {
  14439. // If we successfully set a negative mtime, ensure server returns a
  14440. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14441. // with an old date and ensure server handles it without crash.
  14442. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14443. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14444. ASSERT_TRUE(res2);
  14445. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14446. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14447. } else {
  14448. // Could not set negative mtime on this platform; fall back to verifying
  14449. // that normal invalid/malformed dates are treated safely (non-304).
  14450. Headers h_bad_date = {
  14451. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14452. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14453. ASSERT_TRUE(res_bad);
  14454. EXPECT_EQ(200, res_bad->status);
  14455. }
  14456. svr.stop();
  14457. t.join();
  14458. std::remove(fname);
  14459. }
  14460. //==============================================================================
  14461. // SSE Parsing Tests
  14462. //==============================================================================
  14463. class SSEParsingTest : public ::testing::Test {
  14464. protected:
  14465. // Test helper that mimics SSE parsing behavior
  14466. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14467. int &retry_ms) {
  14468. // Blank line signals end of event
  14469. if (line.empty() || line == "\r") { return true; }
  14470. // Lines starting with ':' are comments (ignored)
  14471. if (!line.empty() && line[0] == ':') { return false; }
  14472. // Find the colon separator
  14473. auto colon_pos = line.find(':');
  14474. if (colon_pos == std::string::npos) {
  14475. // Line with no colon is treated as field name with empty value
  14476. return false;
  14477. }
  14478. std::string field = line.substr(0, colon_pos);
  14479. std::string value;
  14480. // Value starts after colon, skip optional single space
  14481. if (colon_pos + 1 < line.size()) {
  14482. size_t value_start = colon_pos + 1;
  14483. if (line[value_start] == ' ') { value_start++; }
  14484. value = line.substr(value_start);
  14485. // Remove trailing \r if present
  14486. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14487. }
  14488. // Handle known fields
  14489. if (field == "event") {
  14490. msg.event = value;
  14491. } else if (field == "data") {
  14492. // Multiple data lines are concatenated with newlines
  14493. if (!msg.data.empty()) { msg.data += "\n"; }
  14494. msg.data += value;
  14495. } else if (field == "id") {
  14496. // Empty id is valid (clears the last event ID)
  14497. msg.id = value;
  14498. } else if (field == "retry") {
  14499. // Parse retry interval in milliseconds
  14500. {
  14501. int v = 0;
  14502. auto res =
  14503. detail::from_chars(value.data(), value.data() + value.size(), v);
  14504. if (res.ec == std::errc{}) { retry_ms = v; }
  14505. }
  14506. }
  14507. // Unknown fields are ignored per SSE spec
  14508. return false;
  14509. }
  14510. };
  14511. // Test: Single-line data
  14512. TEST_F(SSEParsingTest, SingleLineData) {
  14513. sse::SSEMessage msg;
  14514. int retry_ms = 3000;
  14515. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14516. EXPECT_EQ(msg.data, "hello");
  14517. EXPECT_EQ(msg.event, "message");
  14518. // Blank line ends event
  14519. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14520. }
  14521. // Test: Multi-line data
  14522. TEST_F(SSEParsingTest, MultiLineData) {
  14523. sse::SSEMessage msg;
  14524. int retry_ms = 3000;
  14525. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14526. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14527. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14528. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14529. }
  14530. // Test: Custom event types
  14531. TEST_F(SSEParsingTest, CustomEventType) {
  14532. sse::SSEMessage msg;
  14533. int retry_ms = 3000;
  14534. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14535. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14536. EXPECT_EQ(msg.event, "update");
  14537. EXPECT_EQ(msg.data, "payload");
  14538. }
  14539. // Test: Event ID handling
  14540. TEST_F(SSEParsingTest, EventIdHandling) {
  14541. sse::SSEMessage msg;
  14542. int retry_ms = 3000;
  14543. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14544. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14545. EXPECT_EQ(msg.id, "12345");
  14546. }
  14547. // Test: Empty event ID (clears last event ID)
  14548. TEST_F(SSEParsingTest, EmptyEventId) {
  14549. sse::SSEMessage msg;
  14550. msg.id = "previous";
  14551. int retry_ms = 3000;
  14552. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14553. EXPECT_EQ(msg.id, "");
  14554. }
  14555. // Test: Retry field parsing
  14556. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14557. sse::SSEMessage msg;
  14558. int retry_ms = 3000;
  14559. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14560. EXPECT_EQ(retry_ms, 5000);
  14561. }
  14562. // Test: Invalid retry value
  14563. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14564. sse::SSEMessage msg;
  14565. int retry_ms = 3000;
  14566. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14567. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14568. }
  14569. // Test: Comments (lines starting with :)
  14570. TEST_F(SSEParsingTest, CommentsIgnored) {
  14571. sse::SSEMessage msg;
  14572. int retry_ms = 3000;
  14573. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14574. EXPECT_EQ(msg.data, "");
  14575. EXPECT_EQ(msg.event, "message");
  14576. }
  14577. // Test: Colon in value
  14578. TEST_F(SSEParsingTest, ColonInValue) {
  14579. sse::SSEMessage msg;
  14580. int retry_ms = 3000;
  14581. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14582. EXPECT_EQ(msg.data, "hello:world:test");
  14583. }
  14584. // Test: Line with no colon (field name only)
  14585. TEST_F(SSEParsingTest, FieldNameOnly) {
  14586. sse::SSEMessage msg;
  14587. int retry_ms = 3000;
  14588. // According to SSE spec, this is treated as field name with empty value
  14589. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14590. // Since we don't recognize "data" without colon, data should be empty
  14591. EXPECT_EQ(msg.data, "");
  14592. }
  14593. // Test: Trailing \r handling
  14594. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14595. sse::SSEMessage msg;
  14596. int retry_ms = 3000;
  14597. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14598. EXPECT_EQ(msg.data, "hello");
  14599. }
  14600. // Test: Unknown fields ignored
  14601. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14602. sse::SSEMessage msg;
  14603. int retry_ms = 3000;
  14604. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14605. EXPECT_EQ(msg.data, "");
  14606. EXPECT_EQ(msg.event, "message");
  14607. }
  14608. // Test: Space after colon is optional
  14609. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14610. sse::SSEMessage msg1, msg2;
  14611. int retry_ms = 3000;
  14612. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14613. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14614. EXPECT_EQ(msg1.data, "hello");
  14615. EXPECT_EQ(msg2.data, "hello");
  14616. }
  14617. // Test: SSEMessage clear
  14618. TEST_F(SSEParsingTest, MessageClear) {
  14619. sse::SSEMessage msg;
  14620. msg.event = "custom";
  14621. msg.data = "some data";
  14622. msg.id = "123";
  14623. msg.clear();
  14624. EXPECT_EQ(msg.event, "message");
  14625. EXPECT_EQ(msg.data, "");
  14626. EXPECT_EQ(msg.id, "");
  14627. }
  14628. // Test: Complete event parsing
  14629. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14630. sse::SSEMessage msg;
  14631. int retry_ms = 3000;
  14632. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14633. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14634. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14635. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14636. // Blank line ends event
  14637. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14638. EXPECT_EQ(msg.event, "notification");
  14639. EXPECT_EQ(msg.id, "evt-42");
  14640. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14641. EXPECT_EQ(retry_ms, 1000);
  14642. }
  14643. //==============================================================================
  14644. // Integration Tests with Server
  14645. //==============================================================================
  14646. class SSEIntegrationTest : public ::testing::Test {
  14647. protected:
  14648. void SetUp() override {
  14649. stop_server_.store(false);
  14650. events_.clear();
  14651. server_ = httplib::detail::make_unique<Server>();
  14652. setup_server();
  14653. start_server();
  14654. }
  14655. void TearDown() override {
  14656. stop_server_.store(true);
  14657. event_cv_.notify_all();
  14658. server_->stop();
  14659. if (server_thread_.joinable()) { server_thread_.join(); }
  14660. }
  14661. void setup_server() {
  14662. // Simple SSE endpoint
  14663. server_->Get("/events", [this](const Request &req, Response &res) {
  14664. auto last_id = req.get_header_value("Last-Event-ID");
  14665. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14666. res.set_chunked_content_provider(
  14667. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14668. std::unique_lock<std::mutex> lock(event_mutex_);
  14669. if (event_cv_.wait_for(
  14670. lock, std::chrono::milliseconds(200), [this] {
  14671. return !events_.empty() || stop_server_.load();
  14672. })) {
  14673. if (stop_server_.load()) { return false; }
  14674. if (!events_.empty()) {
  14675. std::string event = events_.front();
  14676. events_.erase(events_.begin());
  14677. sink.write(event.data(), event.size());
  14678. return true;
  14679. }
  14680. }
  14681. return !stop_server_.load();
  14682. });
  14683. });
  14684. // Endpoint that returns error
  14685. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14686. res.status = 500;
  14687. res.set_content("Internal Server Error", "text/plain");
  14688. });
  14689. // Endpoint for custom event types
  14690. server_->Get("/custom-events", [](const Request &, Response &res) {
  14691. res.set_chunked_content_provider(
  14692. "text/event-stream", [](size_t offset, DataSink &sink) {
  14693. if (offset == 0) {
  14694. std::string event = "event: update\ndata: updated\n\n"
  14695. "event: delete\ndata: deleted\n\n";
  14696. sink.write(event.data(), event.size());
  14697. }
  14698. return false; // End stream after sending
  14699. });
  14700. });
  14701. }
  14702. void start_server() {
  14703. port_ = server_->bind_to_any_port(HOST);
  14704. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14705. // Wait for server to start
  14706. while (!server_->is_running()) {
  14707. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14708. }
  14709. }
  14710. int get_port() const { return port_; }
  14711. void send_event(const std::string &event) {
  14712. std::lock_guard<std::mutex> lock(event_mutex_);
  14713. events_.push_back(event);
  14714. event_cv_.notify_all();
  14715. }
  14716. std::unique_ptr<Server> server_;
  14717. std::thread server_thread_;
  14718. std::mutex event_mutex_;
  14719. std::condition_variable event_cv_;
  14720. std::vector<std::string> events_;
  14721. std::atomic<bool> stop_server_{false};
  14722. std::string last_received_event_id_;
  14723. int port_ = 0;
  14724. };
  14725. // Test: Successful connection and on_open callback
  14726. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14727. // Add a simple endpoint that sends one event and closes
  14728. server_->Get("/simple-event", [](const Request &, Response &res) {
  14729. res.set_chunked_content_provider(
  14730. "text/event-stream", [](size_t offset, DataSink &sink) {
  14731. if (offset == 0) {
  14732. std::string event = "data: hello\n\n";
  14733. sink.write(event.data(), event.size());
  14734. }
  14735. return false; // Close stream after sending
  14736. });
  14737. });
  14738. Client client("localhost", get_port());
  14739. sse::SSEClient sse(client, "/simple-event");
  14740. std::atomic<bool> open_called{false};
  14741. std::atomic<bool> message_received{false};
  14742. sse.on_open([&open_called]() { open_called.store(true); });
  14743. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14744. if (msg.data == "hello") { message_received.store(true); }
  14745. });
  14746. sse.set_reconnect_interval(100);
  14747. sse.set_max_reconnect_attempts(1);
  14748. // Start async
  14749. sse.start_async();
  14750. // Wait for message to be processed
  14751. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14752. sse.stop();
  14753. EXPECT_TRUE(open_called.load());
  14754. EXPECT_TRUE(message_received.load());
  14755. }
  14756. // Test: on_message callback
  14757. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14758. // Endpoint that sends multiple events then closes
  14759. server_->Get("/multi-event", [](const Request &, Response &res) {
  14760. res.set_chunked_content_provider(
  14761. "text/event-stream", [](size_t offset, DataSink &sink) {
  14762. if (offset == 0) {
  14763. std::string events = "data: message1\n\ndata: message2\n\n";
  14764. sink.write(events.data(), events.size());
  14765. }
  14766. return false;
  14767. });
  14768. });
  14769. Client client("localhost", get_port());
  14770. sse::SSEClient sse(client, "/multi-event");
  14771. std::vector<std::string> received_messages;
  14772. std::mutex messages_mutex;
  14773. sse.on_message([&](const sse::SSEMessage &msg) {
  14774. std::lock_guard<std::mutex> lock(messages_mutex);
  14775. received_messages.push_back(msg.data);
  14776. });
  14777. sse.set_reconnect_interval(100);
  14778. sse.set_max_reconnect_attempts(1);
  14779. sse.start_async();
  14780. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14781. sse.stop();
  14782. std::lock_guard<std::mutex> lock(messages_mutex);
  14783. EXPECT_GE(received_messages.size(), 2u);
  14784. if (received_messages.size() >= 2) {
  14785. EXPECT_EQ(received_messages[0], "message1");
  14786. EXPECT_EQ(received_messages[1], "message2");
  14787. }
  14788. }
  14789. // Test: on_event for specific types
  14790. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14791. Client client("localhost", get_port());
  14792. sse::SSEClient sse(client, "/custom-events");
  14793. std::atomic<bool> update_received{false};
  14794. std::atomic<bool> delete_received{false};
  14795. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14796. if (msg.data == "updated") { update_received.store(true); }
  14797. });
  14798. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14799. if (msg.data == "deleted") { delete_received.store(true); }
  14800. });
  14801. sse.set_max_reconnect_attempts(1);
  14802. sse.start_async();
  14803. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14804. sse.stop();
  14805. EXPECT_TRUE(update_received.load());
  14806. EXPECT_TRUE(delete_received.load());
  14807. }
  14808. // Test: on_error callback on connection failure
  14809. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14810. // Connect to a non-existent port
  14811. Client client("localhost", 59999);
  14812. sse::SSEClient sse(client, "/events");
  14813. std::atomic<bool> error_called{false};
  14814. Error received_error = Error::Success;
  14815. sse.on_error([&](Error err) {
  14816. error_called.store(true);
  14817. received_error = err;
  14818. });
  14819. sse.set_reconnect_interval(50);
  14820. sse.set_max_reconnect_attempts(1);
  14821. sse.start_async();
  14822. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14823. sse.stop();
  14824. EXPECT_TRUE(error_called.load());
  14825. EXPECT_NE(received_error, Error::Success);
  14826. }
  14827. // Test: Last-Event-ID header sent on reconnect
  14828. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14829. // Endpoint that sends event with ID
  14830. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14831. res.set_chunked_content_provider(
  14832. "text/event-stream", [](size_t offset, DataSink &sink) {
  14833. if (offset == 0) {
  14834. std::string event = "id: evt-123\ndata: test\n\n";
  14835. sink.write(event.data(), event.size());
  14836. }
  14837. return false;
  14838. });
  14839. });
  14840. Client client("localhost", get_port());
  14841. sse::SSEClient sse(client, "/event-with-id");
  14842. std::atomic<bool> id_received{false};
  14843. sse.on_message([&](const sse::SSEMessage &msg) {
  14844. if (!msg.id.empty()) { id_received.store(true); }
  14845. });
  14846. sse.set_reconnect_interval(100);
  14847. sse.set_max_reconnect_attempts(1);
  14848. sse.start_async();
  14849. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14850. sse.stop();
  14851. EXPECT_TRUE(id_received.load());
  14852. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14853. }
  14854. // Test: Manual stop
  14855. TEST_F(SSEIntegrationTest, ManualStop) {
  14856. // Endpoint that sends one event and stays open briefly
  14857. std::atomic<bool> handler_running{true};
  14858. server_->Get("/stay-open", [&handler_running](const Request &,
  14859. Response &res) {
  14860. res.set_chunked_content_provider(
  14861. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14862. if (offset == 0) {
  14863. std::string event = "data: connected\n\n";
  14864. sink.write(event.data(), event.size());
  14865. }
  14866. // Keep connection open while handler_running is true
  14867. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14868. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14869. }
  14870. return false;
  14871. });
  14872. });
  14873. Client client("localhost", get_port());
  14874. sse::SSEClient sse(client, "/stay-open");
  14875. std::atomic<bool> connected{false};
  14876. sse.on_open([&connected]() { connected.store(true); });
  14877. sse.set_reconnect_interval(100);
  14878. sse.set_max_reconnect_attempts(1);
  14879. sse.start_async();
  14880. // Wait for connection to establish
  14881. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14882. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14883. }
  14884. EXPECT_TRUE(connected.load());
  14885. EXPECT_TRUE(sse.is_connected());
  14886. // Signal handler to stop
  14887. handler_running.store(false);
  14888. // Stop SSE client
  14889. sse.stop();
  14890. EXPECT_FALSE(sse.is_connected());
  14891. }
  14892. // Test: SSEClient with custom headers
  14893. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14894. // Setup a server endpoint that checks for custom header
  14895. std::atomic<bool> header_received{false};
  14896. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14897. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14898. header_received.store(true);
  14899. }
  14900. res.set_chunked_content_provider("text/event-stream",
  14901. [](size_t, DataSink &) { return false; });
  14902. });
  14903. Client client("localhost", get_port());
  14904. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14905. sse::SSEClient sse(client, "/header-check", headers);
  14906. sse.set_max_reconnect_attempts(1);
  14907. sse.start_async();
  14908. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14909. sse.stop();
  14910. EXPECT_TRUE(header_received.load());
  14911. }
  14912. // Test: Reconnect interval configuration
  14913. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14914. Client client("localhost", get_port());
  14915. sse::SSEClient sse(client, "/events");
  14916. auto &result = sse.set_reconnect_interval(500);
  14917. // Builder pattern should return reference to self
  14918. EXPECT_EQ(&result, &sse);
  14919. }
  14920. // Test: Max reconnect attempts
  14921. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14922. // Connect to non-existent port to force reconnects
  14923. Client client("localhost", 59998);
  14924. sse::SSEClient sse(client, "/events");
  14925. std::atomic<int> error_count{0};
  14926. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14927. sse.set_reconnect_interval(50);
  14928. sse.set_max_reconnect_attempts(2);
  14929. auto start = std::chrono::steady_clock::now();
  14930. sse.start(); // Blocking call
  14931. auto end = std::chrono::steady_clock::now();
  14932. // Should have stopped after 2 failed attempts
  14933. EXPECT_GE(error_count.load(), 2);
  14934. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14935. auto duration =
  14936. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14937. #ifdef _WIN32
  14938. // Windows is much slower for socket connection failures
  14939. EXPECT_LT(duration.count(), 7000);
  14940. #else
  14941. EXPECT_LT(duration.count(), 1000);
  14942. #endif
  14943. }
  14944. // Test: Multi-line data in integration
  14945. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14946. // Endpoint with multi-line data
  14947. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14948. res.set_chunked_content_provider(
  14949. "text/event-stream", [](size_t offset, DataSink &sink) {
  14950. if (offset == 0) {
  14951. std::string event = "data: line1\ndata: line2\ndata: line3\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, "/multiline-data");
  14959. std::string received_data;
  14960. std::mutex data_mutex;
  14961. sse.on_message([&](const sse::SSEMessage &msg) {
  14962. std::lock_guard<std::mutex> lock(data_mutex);
  14963. received_data = msg.data;
  14964. });
  14965. sse.set_reconnect_interval(100);
  14966. sse.set_max_reconnect_attempts(1);
  14967. sse.start_async();
  14968. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14969. sse.stop();
  14970. std::lock_guard<std::mutex> lock(data_mutex);
  14971. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14972. }
  14973. // Test: Auto-reconnect after server disconnection
  14974. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14975. std::atomic<int> connection_count{0};
  14976. std::atomic<int> message_count{0};
  14977. // Endpoint that sends one event and closes, forcing reconnect
  14978. server_->Get("/reconnect-test",
  14979. [&connection_count](const Request &, Response &res) {
  14980. connection_count.fetch_add(1);
  14981. res.set_chunked_content_provider(
  14982. "text/event-stream", [](size_t offset, DataSink &sink) {
  14983. if (offset == 0) {
  14984. std::string event = "data: hello\n\n";
  14985. sink.write(event.data(), event.size());
  14986. }
  14987. return false; // Close connection after sending
  14988. });
  14989. });
  14990. Client client("localhost", get_port());
  14991. sse::SSEClient sse(client, "/reconnect-test");
  14992. sse.on_message([&message_count](const sse::SSEMessage &) {
  14993. message_count.fetch_add(1);
  14994. });
  14995. sse.set_reconnect_interval(100);
  14996. sse.set_max_reconnect_attempts(3);
  14997. sse.start_async();
  14998. // Wait long enough for multiple reconnects
  14999. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15000. sse.stop();
  15001. // Should have connected multiple times (initial + reconnects)
  15002. EXPECT_GE(connection_count.load(), 2);
  15003. // Should have received messages from multiple connections
  15004. EXPECT_GE(message_count.load(), 2);
  15005. }
  15006. // Test: Last-Event-ID sent on reconnect
  15007. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15008. std::atomic<int> connection_count{0};
  15009. std::vector<std::string> received_last_event_ids;
  15010. std::mutex id_mutex;
  15011. // Endpoint that checks Last-Event-ID header and sends event with ID
  15012. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15013. int conn = connection_count.fetch_add(1);
  15014. // Capture the Last-Event-ID header from each connection
  15015. {
  15016. std::lock_guard<std::mutex> lock(id_mutex);
  15017. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15018. }
  15019. res.set_chunked_content_provider(
  15020. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15021. if (offset == 0) {
  15022. std::string event =
  15023. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15024. sink.write(event.data(), event.size());
  15025. }
  15026. return false;
  15027. });
  15028. });
  15029. Client client("localhost", get_port());
  15030. sse::SSEClient sse(client, "/reconnect-with-id");
  15031. sse.set_reconnect_interval(100);
  15032. sse.set_max_reconnect_attempts(3);
  15033. sse.start_async();
  15034. // Wait for at least 2 connections
  15035. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15036. sse.stop();
  15037. // Verify behavior
  15038. std::lock_guard<std::mutex> lock(id_mutex);
  15039. EXPECT_GE(received_last_event_ids.size(), 2u);
  15040. // First connection should have no Last-Event-ID
  15041. if (!received_last_event_ids.empty()) {
  15042. EXPECT_EQ(received_last_event_ids[0], "");
  15043. }
  15044. // Second connection should have Last-Event-ID from first connection
  15045. if (received_last_event_ids.size() >= 2) {
  15046. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15047. }
  15048. }
  15049. // Test: set_headers updates headers used on reconnect
  15050. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15051. std::vector<std::string> received_tokens;
  15052. std::mutex token_mutex;
  15053. // Endpoint that captures Authorization header
  15054. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15055. {
  15056. std::lock_guard<std::mutex> lock(token_mutex);
  15057. received_tokens.push_back(req.get_header_value("Authorization"));
  15058. }
  15059. res.set_chunked_content_provider(
  15060. "text/event-stream", [](size_t offset, DataSink &sink) {
  15061. if (offset == 0) {
  15062. std::string event = "data: hello\n\n";
  15063. sink.write(event.data(), event.size());
  15064. }
  15065. return false; // Close connection to trigger reconnect
  15066. });
  15067. });
  15068. Client client("localhost", get_port());
  15069. Headers headers = {{"Authorization", "Bearer old-token"}};
  15070. sse::SSEClient sse(client, "/auth-check", headers);
  15071. // Update headers on each successful connection
  15072. sse.on_open(
  15073. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15074. sse.set_reconnect_interval(100);
  15075. sse.set_max_reconnect_attempts(3);
  15076. sse.start_async();
  15077. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15078. sse.stop();
  15079. std::lock_guard<std::mutex> lock(token_mutex);
  15080. ASSERT_GE(received_tokens.size(), 2u);
  15081. // First connection uses original header
  15082. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15083. // Second connection uses updated header from set_headers
  15084. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15085. }
  15086. // Test: 401 allows reconnection (so on_error can refresh headers)
  15087. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15088. std::atomic<int> connection_count{0};
  15089. // Endpoint: returns 401 on first attempt, 200 on second
  15090. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15091. int conn = connection_count.fetch_add(1);
  15092. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15093. res.status = StatusCode::Unauthorized_401;
  15094. res.set_content("Unauthorized", "text/plain");
  15095. return;
  15096. }
  15097. res.set_chunked_content_provider(
  15098. "text/event-stream", [](size_t offset, DataSink &sink) {
  15099. if (offset == 0) {
  15100. std::string event = "data: authenticated\n\n";
  15101. sink.write(event.data(), event.size());
  15102. }
  15103. return false;
  15104. });
  15105. });
  15106. Client client("localhost", get_port());
  15107. Headers headers = {{"Authorization", "Bearer expired"}};
  15108. sse::SSEClient sse(client, "/auth-retry", headers);
  15109. std::atomic<bool> message_received{false};
  15110. // Refresh token on error
  15111. sse.on_error(
  15112. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15113. sse.on_message([&](const sse::SSEMessage &msg) {
  15114. if (msg.data == "authenticated") { message_received.store(true); }
  15115. });
  15116. sse.set_reconnect_interval(100);
  15117. sse.set_max_reconnect_attempts(3);
  15118. sse.start_async();
  15119. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15120. sse.stop();
  15121. // Should have reconnected after 401 and succeeded with new token
  15122. EXPECT_GE(connection_count.load(), 2);
  15123. EXPECT_TRUE(message_received.load());
  15124. }
  15125. TEST(Issue2318Test, EmptyHostString) {
  15126. {
  15127. httplib::Client cli_empty("", PORT);
  15128. auto res = cli_empty.Get("/");
  15129. ASSERT_FALSE(res);
  15130. EXPECT_EQ(httplib::Error::Connection, res.error());
  15131. }
  15132. {
  15133. httplib::Client cli(" ", PORT);
  15134. auto res = cli.Get("/");
  15135. ASSERT_FALSE(res);
  15136. EXPECT_EQ(httplib::Error::Connection, res.error());
  15137. }
  15138. }
  15139. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15140. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15141. Server svr;
  15142. // Set a small payload limit (1KB)
  15143. svr.set_payload_max_length(1024);
  15144. svr.Post("/test", [&](const Request &req, Response &res) {
  15145. res.set_content("Body size: " + std::to_string(req.body.size()),
  15146. "text/plain");
  15147. });
  15148. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15149. auto se = detail::scope_exit([&] {
  15150. svr.stop();
  15151. listen_thread.join();
  15152. });
  15153. svr.wait_until_ready();
  15154. // Create data that compresses well but exceeds limit when decompressed
  15155. // 8KB of repeated null bytes compresses to a very small size
  15156. std::string original_data(8 * 1024, '\0');
  15157. // Compress the data using gzip
  15158. std::string compressed_data;
  15159. detail::gzip_compressor compressor;
  15160. compressor.compress(original_data.data(), original_data.size(), true,
  15161. [&](const char *data, size_t size) {
  15162. compressed_data.append(data, size);
  15163. return true;
  15164. });
  15165. // Verify compression worked (compressed should be much smaller)
  15166. ASSERT_LT(compressed_data.size(), original_data.size());
  15167. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15168. // Send compressed data with Content-Encoding: gzip
  15169. Client cli(HOST, PORT);
  15170. Headers headers = {{"Content-Encoding", "gzip"}};
  15171. auto res =
  15172. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15173. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15174. ASSERT_TRUE(res);
  15175. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15176. }
  15177. #endif
  15178. // ============================================================================
  15179. // OpenSSL-Specific Tests
  15180. // ============================================================================
  15181. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15182. X509 *readCertificate(const std::string &strFileName) {
  15183. std::ifstream inStream(strFileName);
  15184. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15185. std::istreambuf_iterator<char>());
  15186. if (strCertPEM.empty()) return (nullptr);
  15187. BIO *pbCert = BIO_new(BIO_s_mem());
  15188. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15189. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15190. BIO_free(pbCert);
  15191. return (pCert);
  15192. }
  15193. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15194. std::ifstream inStream(strFileName);
  15195. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15196. std::istreambuf_iterator<char>());
  15197. if (strPrivateKeyPEM.empty()) return (nullptr);
  15198. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15199. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15200. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15201. BIO_free(pbPrivKey);
  15202. return (pPrivateKey);
  15203. }
  15204. TEST(BindServerTest, UpdateCerts) {
  15205. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15206. int port = svr.bind_to_any_port("0.0.0.0");
  15207. ASSERT_TRUE(svr.is_valid());
  15208. ASSERT_TRUE(port > 0);
  15209. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15210. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15211. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15212. ASSERT_TRUE(cert != nullptr);
  15213. ASSERT_TRUE(ca_cert != nullptr);
  15214. ASSERT_TRUE(key != nullptr);
  15215. X509_STORE *cert_store = X509_STORE_new();
  15216. X509_STORE_add_cert(cert_store, ca_cert);
  15217. // svr.update_certs(cert, key, cert_store); // deprecated
  15218. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15219. CLIENT_CA_CERT_FILE);
  15220. ASSERT_TRUE(svr.is_valid());
  15221. svr.stop();
  15222. X509_STORE_free(cert_store);
  15223. X509_free(cert);
  15224. X509_free(ca_cert);
  15225. EVP_PKEY_free(key);
  15226. }
  15227. // Test that update_certs() updates client CA list correctly
  15228. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15229. // Start with file-based constructor
  15230. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15231. ASSERT_TRUE(svr.is_valid());
  15232. // Initially no client CA list should be set
  15233. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15234. ASSERT_TRUE(ssl_ctx != nullptr);
  15235. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15236. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15237. EXPECT_EQ(0, count_before);
  15238. // Now update with client CA (PEM string)
  15239. std::string cert_pem, key_pem, ca_pem;
  15240. read_file(SERVER_CERT_FILE, cert_pem);
  15241. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15242. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15243. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15244. ASSERT_TRUE(svr.is_valid());
  15245. // Now client CA list should be set
  15246. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15247. ASSERT_TRUE(ca_list_after != nullptr);
  15248. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15249. }
  15250. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15251. // Test that the file-path SSLServer constructor properly sets the client CA
  15252. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15254. ASSERT_TRUE(svr.is_valid());
  15255. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15256. ASSERT_TRUE(ssl_ctx != nullptr);
  15257. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15258. ASSERT_TRUE(ca_list != nullptr);
  15259. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15260. }
  15261. #endif
  15262. // ============================================================================
  15263. // MbedTLS-Specific Tests
  15264. // ============================================================================
  15265. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15266. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15267. using namespace httplib::tls;
  15268. // Track if callback was invoked
  15269. bool callback_invoked = false;
  15270. // The callback receives void* ctx which is actually MbedTlsContext*
  15271. // We can access the mbedtls_ssl_config via the context
  15272. auto setup_callback = [&callback_invoked](void *ctx) {
  15273. callback_invoked = true;
  15274. // Cast to MbedTlsContext* to access the ssl config
  15275. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15276. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15277. // Use static variables to hold certificate data (simplified for test)
  15278. static mbedtls_x509_crt own_cert;
  15279. static mbedtls_pk_context own_key;
  15280. static mbedtls_x509_crt ca_chain;
  15281. static bool initialized = false;
  15282. if (!initialized) {
  15283. mbedtls_x509_crt_init(&own_cert);
  15284. mbedtls_pk_init(&own_key);
  15285. mbedtls_x509_crt_init(&ca_chain);
  15286. // Load server certificate
  15287. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15288. return false;
  15289. }
  15290. // Load server private key
  15291. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15292. #if MBEDTLS_VERSION_MAJOR >= 3
  15293. ,
  15294. mbedtls_ctr_drbg_random, nullptr
  15295. #endif
  15296. ) != 0) {
  15297. return false;
  15298. }
  15299. // Load CA chain for client verification
  15300. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15301. return false;
  15302. }
  15303. initialized = true;
  15304. }
  15305. // Configure the SSL config
  15306. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15307. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15308. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15309. // Set minimum TLS version using mbedTLS native API
  15310. #if MBEDTLS_VERSION_MAJOR >= 3
  15311. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15312. #else
  15313. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15314. MBEDTLS_SSL_MINOR_VERSION_3);
  15315. #endif
  15316. return true;
  15317. };
  15318. SSLServer svr(setup_callback);
  15319. ASSERT_TRUE(svr.is_valid());
  15320. ASSERT_TRUE(callback_invoked);
  15321. svr.Get("/test", [&](const Request &req, Response &res) {
  15322. res.set_content("test", "text/plain");
  15323. auto cert = req.peer_cert();
  15324. ASSERT_TRUE(static_cast<bool>(cert));
  15325. auto common_name = cert.subject_cn();
  15326. EXPECT_EQ("Common Name", common_name);
  15327. });
  15328. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15329. auto se = detail::scope_exit([&] {
  15330. svr.stop();
  15331. t.join();
  15332. ASSERT_FALSE(svr.is_running());
  15333. });
  15334. svr.wait_until_ready();
  15335. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15336. cli.enable_server_certificate_verification(false);
  15337. cli.set_connection_timeout(30);
  15338. auto res = cli.Get("/test");
  15339. ASSERT_TRUE(res);
  15340. ASSERT_EQ(StatusCode::OK_200, res->status);
  15341. }
  15342. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15343. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15344. // keep-alive SSL session, which reads through that config in
  15345. // mbedtls_ssl_close_notify.
  15346. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15348. ASSERT_TRUE(svr.is_valid());
  15349. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15350. res.set_content("test", "text/plain");
  15351. });
  15352. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15353. auto se = detail::scope_exit([&] {
  15354. svr.stop();
  15355. t.join();
  15356. ASSERT_FALSE(svr.is_running());
  15357. });
  15358. svr.wait_until_ready();
  15359. {
  15360. SSLClient cli(HOST, PORT);
  15361. cli.enable_server_certificate_verification(false);
  15362. cli.set_keep_alive(true);
  15363. auto res = cli.Get("/test");
  15364. ASSERT_TRUE(res);
  15365. ASSERT_EQ(StatusCode::OK_200, res->status);
  15366. // cli is destructed here with the keep-alive SSL session still open.
  15367. }
  15368. }
  15369. #endif
  15370. // WebSocket Tests
  15371. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15372. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15373. // defining the meaning of these bits has been negotiated.
  15374. auto make_frame = [](uint8_t first_byte) {
  15375. std::string frame;
  15376. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15377. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15378. frame += "Hello";
  15379. return frame;
  15380. };
  15381. // RSV1 set (0x40)
  15382. {
  15383. detail::BufferStream strm;
  15384. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15385. ws::Opcode opcode;
  15386. std::string payload;
  15387. bool fin;
  15388. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15389. false, 1024));
  15390. }
  15391. // RSV2 set (0x20)
  15392. {
  15393. detail::BufferStream strm;
  15394. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15395. ws::Opcode opcode;
  15396. std::string payload;
  15397. bool fin;
  15398. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15399. false, 1024));
  15400. }
  15401. // RSV3 set (0x10)
  15402. {
  15403. detail::BufferStream strm;
  15404. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15405. ws::Opcode opcode;
  15406. std::string payload;
  15407. bool fin;
  15408. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15409. false, 1024));
  15410. }
  15411. // No RSV bits set - should succeed
  15412. {
  15413. detail::BufferStream strm;
  15414. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15415. ws::Opcode opcode;
  15416. std::string payload;
  15417. bool fin;
  15418. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15419. false, 1024));
  15420. EXPECT_EQ(ws::Opcode::Text, opcode);
  15421. EXPECT_EQ("Hello", payload);
  15422. EXPECT_TRUE(fin);
  15423. }
  15424. }
  15425. TEST(WebSocketTest, ControlFrameValidation) {
  15426. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15427. // payload length <= 125.
  15428. // Ping with FIN=0 - must be rejected
  15429. {
  15430. detail::BufferStream strm;
  15431. std::string frame;
  15432. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15433. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15434. strm.write(frame.data(), frame.size());
  15435. ws::Opcode opcode;
  15436. std::string payload;
  15437. bool fin;
  15438. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15439. false, 1024));
  15440. }
  15441. // Close with FIN=0 - must be rejected
  15442. {
  15443. detail::BufferStream strm;
  15444. std::string frame;
  15445. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15446. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15447. strm.write(frame.data(), frame.size());
  15448. ws::Opcode opcode;
  15449. std::string payload;
  15450. bool fin;
  15451. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15452. false, 1024));
  15453. }
  15454. // Ping with payload_len=126 (extended length) - must be rejected
  15455. {
  15456. detail::BufferStream strm;
  15457. std::string frame;
  15458. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15459. frame += static_cast<char>(126); // payload_len=126 (>125)
  15460. frame += static_cast<char>(0x00); // extended length high byte
  15461. frame += static_cast<char>(126); // extended length low byte
  15462. frame += std::string(126, 'x');
  15463. strm.write(frame.data(), frame.size());
  15464. ws::Opcode opcode;
  15465. std::string payload;
  15466. bool fin;
  15467. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15468. false, 1024));
  15469. }
  15470. // Ping with FIN=1 and payload_len=125 - should succeed
  15471. {
  15472. detail::BufferStream strm;
  15473. std::string frame;
  15474. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15475. frame += static_cast<char>(125); // payload_len=125
  15476. frame += std::string(125, 'x');
  15477. strm.write(frame.data(), frame.size());
  15478. ws::Opcode opcode;
  15479. std::string payload;
  15480. bool fin;
  15481. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15482. false, 1024));
  15483. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15484. EXPECT_EQ(125u, payload.size());
  15485. EXPECT_TRUE(fin);
  15486. }
  15487. }
  15488. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15489. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15490. // length MUST be 0.
  15491. // MSB set - must be rejected
  15492. {
  15493. detail::BufferStream strm;
  15494. std::string frame;
  15495. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15496. frame += static_cast<char>(127); // 64-bit extended length
  15497. frame += static_cast<char>(0x80); // MSB set (invalid)
  15498. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15499. strm.write(frame.data(), frame.size());
  15500. ws::Opcode opcode;
  15501. std::string payload;
  15502. bool fin;
  15503. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15504. false, 1024));
  15505. }
  15506. // MSB clear - should pass length parsing (will be rejected by max_len,
  15507. // but that's a different check; use a small length to verify)
  15508. {
  15509. detail::BufferStream strm;
  15510. std::string frame;
  15511. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15512. frame += static_cast<char>(127); // 64-bit extended length
  15513. frame += std::string(7, '\0'); // high bytes = 0
  15514. frame += static_cast<char>(0x03); // length = 3
  15515. frame += "abc";
  15516. strm.write(frame.data(), frame.size());
  15517. ws::Opcode opcode;
  15518. std::string payload;
  15519. bool fin;
  15520. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15521. false, 1024));
  15522. EXPECT_EQ(ws::Opcode::Text, opcode);
  15523. EXPECT_EQ("abc", payload);
  15524. }
  15525. }
  15526. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15527. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15528. // Valid UTF-8
  15529. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15530. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15531. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15532. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15533. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15534. // Invalid UTF-8
  15535. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15536. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15537. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15538. EXPECT_FALSE(
  15539. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15540. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15541. }
  15542. TEST(WebSocketTest, ConnectAndDisconnect) {
  15543. Server svr;
  15544. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15545. std::string msg;
  15546. while (ws.read(msg)) {}
  15547. });
  15548. auto port = svr.bind_to_any_port(HOST);
  15549. std::thread t([&]() { svr.listen_after_bind(); });
  15550. svr.wait_until_ready();
  15551. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15552. ASSERT_TRUE(client.connect());
  15553. EXPECT_TRUE(client.is_open());
  15554. client.close();
  15555. EXPECT_FALSE(client.is_open());
  15556. svr.stop();
  15557. t.join();
  15558. }
  15559. TEST(WebSocketTest, ValidURL) {
  15560. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15561. EXPECT_TRUE(ws1.is_valid());
  15562. ws::WebSocketClient ws2("ws://example.com/path");
  15563. EXPECT_TRUE(ws2.is_valid());
  15564. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15565. EXPECT_TRUE(ws3.is_valid());
  15566. #ifdef CPPHTTPLIB_SSL_ENABLED
  15567. ws::WebSocketClient wss1("wss://example.com/path");
  15568. EXPECT_TRUE(wss1.is_valid());
  15569. ws::WebSocketClient wss2("wss://example.com:443/path");
  15570. EXPECT_TRUE(wss2.is_valid());
  15571. #endif
  15572. }
  15573. TEST(WebSocketTest, InvalidURL) {
  15574. // No scheme
  15575. ws::WebSocketClient ws1("localhost:8080/path");
  15576. EXPECT_FALSE(ws1.is_valid());
  15577. // No path
  15578. ws::WebSocketClient ws2("ws://localhost:8080");
  15579. EXPECT_FALSE(ws2.is_valid());
  15580. // Empty string
  15581. ws::WebSocketClient ws3("");
  15582. EXPECT_FALSE(ws3.is_valid());
  15583. // Missing host
  15584. ws::WebSocketClient ws4("ws://:8080/path");
  15585. EXPECT_FALSE(ws4.is_valid());
  15586. // Port number overflow — should not crash
  15587. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15588. EXPECT_FALSE(ws5.is_valid());
  15589. // Port out of range
  15590. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15591. EXPECT_FALSE(ws6.is_valid());
  15592. }
  15593. TEST(WebSocketTest, UnsupportedScheme) {
  15594. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15595. ws::WebSocketClient ws1("http://localhost:8080/path");
  15596. EXPECT_FALSE(ws1.is_valid());
  15597. ws::WebSocketClient ws2("https://localhost:8080/path");
  15598. EXPECT_FALSE(ws2.is_valid());
  15599. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15600. EXPECT_FALSE(ws3.is_valid());
  15601. #else
  15602. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15603. std::invalid_argument);
  15604. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15605. std::invalid_argument);
  15606. #endif
  15607. }
  15608. TEST(WebSocketTest, ConnectWhenInvalid) {
  15609. ws::WebSocketClient ws("not a valid url");
  15610. EXPECT_FALSE(ws.is_valid());
  15611. EXPECT_FALSE(ws.connect());
  15612. }
  15613. TEST(WebSocketTest, DefaultPort) {
  15614. ws::WebSocketClient ws1("ws://example.com/path");
  15615. EXPECT_TRUE(ws1.is_valid());
  15616. // ws:// defaults to port 80 (verified by successful parse)
  15617. #ifdef CPPHTTPLIB_SSL_ENABLED
  15618. ws::WebSocketClient ws2("wss://example.com/path");
  15619. EXPECT_TRUE(ws2.is_valid());
  15620. // wss:// defaults to port 443 (verified by successful parse)
  15621. #endif
  15622. }
  15623. TEST(WebSocketTest, IPv6LiteralAddress) {
  15624. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15625. EXPECT_TRUE(ws1.is_valid());
  15626. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15627. EXPECT_TRUE(ws2.is_valid());
  15628. }
  15629. TEST(WebSocketTest, ComplexPath) {
  15630. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15631. EXPECT_TRUE(ws1.is_valid());
  15632. ws::WebSocketClient ws2("ws://localhost:8080/");
  15633. EXPECT_TRUE(ws2.is_valid());
  15634. }
  15635. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15636. Server svr;
  15637. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15638. std::string msg;
  15639. while (ws.read(msg)) {}
  15640. });
  15641. auto port = svr.bind_to_any_port(HOST);
  15642. std::thread t([&]() { svr.listen_after_bind(); });
  15643. svr.wait_until_ready();
  15644. auto another_host = "example.com";
  15645. auto wrong_ip = "192.0.2.1";
  15646. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15647. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15648. ASSERT_TRUE(client.connect());
  15649. EXPECT_TRUE(client.is_open());
  15650. client.close();
  15651. svr.stop();
  15652. t.join();
  15653. }
  15654. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15655. Server svr;
  15656. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15657. std::string msg;
  15658. while (ws.read(msg)) {}
  15659. });
  15660. auto port = svr.bind_to_any_port(HOST);
  15661. std::thread t([&]() { svr.listen_after_bind(); });
  15662. svr.wait_until_ready();
  15663. auto wrong_ip = "192.0.2.1";
  15664. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15665. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15666. client.set_connection_timeout(1);
  15667. client.set_read_timeout(1);
  15668. client.set_write_timeout(1);
  15669. EXPECT_FALSE(client.connect());
  15670. EXPECT_FALSE(client.is_open());
  15671. svr.stop();
  15672. t.join();
  15673. }
  15674. class WebSocketIntegrationTest : public ::testing::Test {
  15675. protected:
  15676. void SetUp() override {
  15677. server_ = httplib::detail::make_unique<Server>();
  15678. setup_server();
  15679. start_server();
  15680. }
  15681. void TearDown() override {
  15682. server_->stop();
  15683. if (server_thread_.joinable()) { server_thread_.join(); }
  15684. }
  15685. void setup_server() {
  15686. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15687. std::string msg;
  15688. ws::ReadResult ret;
  15689. while ((ret = ws.read(msg))) {
  15690. if (ret == ws::Binary) {
  15691. ws.send(msg.data(), msg.size());
  15692. } else {
  15693. ws.send(msg);
  15694. }
  15695. }
  15696. });
  15697. server_->WebSocket("/ws-echo-string",
  15698. [](const Request &, ws::WebSocket &ws) {
  15699. std::string msg;
  15700. while (ws.read(msg)) {
  15701. ws.send("echo: " + msg);
  15702. }
  15703. });
  15704. server_->WebSocket(
  15705. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15706. // Echo back request metadata
  15707. ws.send("path:" + req.path);
  15708. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15709. std::string msg;
  15710. while (ws.read(msg)) {}
  15711. });
  15712. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15713. std::string msg;
  15714. ws.read(msg); // wait for a message
  15715. ws.close();
  15716. });
  15717. server_->WebSocket("/ws-close-status",
  15718. [](const Request &, ws::WebSocket &ws) {
  15719. std::string msg;
  15720. ws.read(msg); // wait for a message
  15721. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15722. });
  15723. server_->WebSocket(
  15724. "/ws-subprotocol",
  15725. [](const Request &, ws::WebSocket &ws) {
  15726. std::string msg;
  15727. while (ws.read(msg)) {
  15728. ws.send(msg);
  15729. }
  15730. },
  15731. [](const std::vector<std::string> &protocols) -> std::string {
  15732. for (const auto &p : protocols) {
  15733. if (p == "graphql-ws") { return p; }
  15734. }
  15735. return "";
  15736. });
  15737. }
  15738. void start_server() {
  15739. port_ = server_->bind_to_any_port(HOST);
  15740. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15741. server_->wait_until_ready();
  15742. }
  15743. std::unique_ptr<Server> server_;
  15744. std::thread server_thread_;
  15745. int port_ = 0;
  15746. };
  15747. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15748. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15749. "/ws-echo");
  15750. ASSERT_TRUE(client.connect());
  15751. ASSERT_TRUE(client.is_open());
  15752. ASSERT_TRUE(client.send("Hello WebSocket"));
  15753. std::string msg;
  15754. EXPECT_EQ(ws::Text, client.read(msg));
  15755. EXPECT_EQ("Hello WebSocket", msg);
  15756. client.close();
  15757. }
  15758. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15760. "/ws-echo");
  15761. ASSERT_TRUE(client.connect());
  15762. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15763. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15764. std::string msg;
  15765. EXPECT_EQ(ws::Binary, client.read(msg));
  15766. EXPECT_EQ(binary_data, msg);
  15767. client.close();
  15768. }
  15769. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15770. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15771. "/ws-echo");
  15772. ASSERT_TRUE(client.connect());
  15773. for (int i = 0; i < 10; i++) {
  15774. auto text = "message " + std::to_string(i);
  15775. ASSERT_TRUE(client.send(text));
  15776. std::string msg;
  15777. ASSERT_TRUE(client.read(msg));
  15778. EXPECT_EQ(text, msg);
  15779. }
  15780. client.close();
  15781. }
  15782. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15783. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15784. "/ws-close");
  15785. ASSERT_TRUE(client.connect());
  15786. // Send a message to trigger the server to close
  15787. ASSERT_TRUE(client.send("trigger close"));
  15788. // The server will close, so read should return false
  15789. std::string msg;
  15790. EXPECT_FALSE(client.read(msg));
  15791. EXPECT_FALSE(client.is_open());
  15792. }
  15793. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15794. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15795. "/ws-echo");
  15796. ASSERT_TRUE(client.connect());
  15797. // 128KB message
  15798. std::string large_data(128 * 1024, 'X');
  15799. ASSERT_TRUE(client.send(large_data));
  15800. std::string msg;
  15801. ASSERT_TRUE(client.read(msg));
  15802. EXPECT_EQ(large_data, msg);
  15803. client.close();
  15804. }
  15805. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15807. "/ws-echo");
  15808. ASSERT_TRUE(client.connect());
  15809. const int num_threads = 4;
  15810. std::vector<std::thread> threads;
  15811. std::atomic<int> send_count{0};
  15812. for (int t = 0; t < num_threads; t++) {
  15813. threads.emplace_back([&client, &send_count, t]() {
  15814. for (int i = 0; i < 5; i++) {
  15815. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15816. if (client.send(text)) { send_count++; }
  15817. }
  15818. });
  15819. }
  15820. for (auto &th : threads) {
  15821. th.join();
  15822. }
  15823. int received = 0;
  15824. std::string msg;
  15825. while (received < send_count.load()) {
  15826. if (!client.read(msg)) { break; }
  15827. received++;
  15828. }
  15829. EXPECT_EQ(send_count.load(), received);
  15830. client.close();
  15831. }
  15832. TEST_F(WebSocketIntegrationTest, ReadString) {
  15833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15834. "/ws-echo-string");
  15835. ASSERT_TRUE(client.connect());
  15836. ASSERT_TRUE(client.send("hello"));
  15837. std::string msg;
  15838. ASSERT_TRUE(client.read(msg));
  15839. EXPECT_EQ("echo: hello", msg);
  15840. ASSERT_TRUE(client.send("world"));
  15841. ASSERT_TRUE(client.read(msg));
  15842. EXPECT_EQ("echo: world", msg);
  15843. client.close();
  15844. }
  15845. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15846. Headers headers = {{"X-Test-Header", "test-value"}};
  15847. ws::WebSocketClient client(
  15848. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15849. ASSERT_TRUE(client.connect());
  15850. std::string msg;
  15851. ASSERT_TRUE(client.read(msg));
  15852. EXPECT_EQ("path:/ws-request-info", msg);
  15853. ASSERT_TRUE(client.read(msg));
  15854. EXPECT_EQ("header:test-value", msg);
  15855. client.close();
  15856. }
  15857. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15858. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15859. "/ws-echo");
  15860. client.set_read_timeout(1, 0); // 1 second
  15861. ASSERT_TRUE(client.connect());
  15862. // Don't send anything — server echo handler waits for a message,
  15863. // so read() should time out and return false.
  15864. std::string msg;
  15865. EXPECT_FALSE(client.read(msg));
  15866. }
  15867. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15868. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15869. "/ws-echo");
  15870. client.set_read_timeout(5, 0);
  15871. ASSERT_TRUE(client.connect());
  15872. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15873. // The server should reject it and close the connection.
  15874. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15875. client.send(oversized);
  15876. // The server's read() should have failed due to payload limit,
  15877. // so our read() should return false (connection closed).
  15878. std::string msg;
  15879. EXPECT_FALSE(client.read(msg));
  15880. }
  15881. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15883. "/ws-echo");
  15884. client.set_read_timeout(10, 0);
  15885. ASSERT_TRUE(client.connect());
  15886. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15887. // This should succeed.
  15888. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15889. ASSERT_TRUE(client.send(at_limit));
  15890. std::string msg;
  15891. ASSERT_TRUE(client.read(msg));
  15892. EXPECT_EQ(at_limit.size(), msg.size());
  15893. client.close();
  15894. }
  15895. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15897. "/nonexistent");
  15898. EXPECT_FALSE(client.connect());
  15899. EXPECT_FALSE(client.is_open());
  15900. }
  15901. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15902. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15903. "/ws-echo");
  15904. ASSERT_TRUE(client.connect());
  15905. ASSERT_TRUE(client.send(""));
  15906. std::string msg;
  15907. EXPECT_EQ(ws::Text, client.read(msg));
  15908. EXPECT_EQ("", msg);
  15909. client.close();
  15910. }
  15911. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15912. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15913. "/ws-echo");
  15914. // First connection
  15915. ASSERT_TRUE(client.connect());
  15916. ASSERT_TRUE(client.send("first"));
  15917. std::string msg;
  15918. ASSERT_TRUE(client.read(msg));
  15919. EXPECT_EQ("first", msg);
  15920. client.close();
  15921. EXPECT_FALSE(client.is_open());
  15922. // Reconnect using the same client object
  15923. ASSERT_TRUE(client.connect());
  15924. ASSERT_TRUE(client.is_open());
  15925. ASSERT_TRUE(client.send("second"));
  15926. ASSERT_TRUE(client.read(msg));
  15927. EXPECT_EQ("second", msg);
  15928. client.close();
  15929. }
  15930. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15932. "/ws-close-status");
  15933. ASSERT_TRUE(client.connect());
  15934. // Trigger the server to close with GoingAway status
  15935. ASSERT_TRUE(client.send("trigger"));
  15936. // read() should return false after receiving the close frame
  15937. std::string msg;
  15938. EXPECT_FALSE(client.read(msg));
  15939. EXPECT_FALSE(client.is_open());
  15940. }
  15941. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15942. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15943. "/ws-echo");
  15944. ASSERT_TRUE(client.connect());
  15945. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15946. EXPECT_FALSE(client.is_open());
  15947. }
  15948. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15949. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15950. ws::WebSocketClient client(
  15951. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15952. ASSERT_TRUE(client.connect());
  15953. // Server should have selected graphql-ws
  15954. EXPECT_EQ("graphql-ws", client.subprotocol());
  15955. client.close();
  15956. }
  15957. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15958. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15959. ws::WebSocketClient client(
  15960. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15961. ASSERT_TRUE(client.connect());
  15962. // Server should not have selected any subprotocol
  15963. EXPECT_TRUE(client.subprotocol().empty());
  15964. client.close();
  15965. }
  15966. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15967. // Connect without requesting any subprotocol
  15968. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15969. "/ws-subprotocol");
  15970. ASSERT_TRUE(client.connect());
  15971. EXPECT_TRUE(client.subprotocol().empty());
  15972. client.close();
  15973. }
  15974. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15976. "/ws-echo");
  15977. client.set_tcp_nodelay(true);
  15978. client.set_connection_timeout(3, 0);
  15979. bool socket_options_called = false;
  15980. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15981. ASSERT_TRUE(client.connect());
  15982. ASSERT_TRUE(client.is_open());
  15983. EXPECT_TRUE(socket_options_called);
  15984. ASSERT_TRUE(client.send("hello"));
  15985. std::string msg;
  15986. auto result = client.read(msg);
  15987. EXPECT_EQ(result, ws::ReadResult::Text);
  15988. EXPECT_EQ(msg, "hello");
  15989. client.close();
  15990. }
  15991. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15992. Server svr;
  15993. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15994. if (!req.has_header("Authorization")) {
  15995. res.status = StatusCode::Unauthorized_401;
  15996. res.set_content("Unauthorized", "text/plain");
  15997. return Server::HandlerResponse::Handled;
  15998. }
  15999. return Server::HandlerResponse::Unhandled;
  16000. });
  16001. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16002. std::string msg;
  16003. while (ws.read(msg)) {
  16004. ws.send(msg);
  16005. }
  16006. });
  16007. auto port = svr.bind_to_any_port("localhost");
  16008. std::thread t([&]() { svr.listen_after_bind(); });
  16009. svr.wait_until_ready();
  16010. // Without Authorization header - should be rejected before upgrade
  16011. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16012. EXPECT_FALSE(client1.connect());
  16013. // With Authorization header - should succeed
  16014. Headers headers = {{"Authorization", "Bearer token123"}};
  16015. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16016. headers);
  16017. ASSERT_TRUE(client2.connect());
  16018. ASSERT_TRUE(client2.send("hello"));
  16019. std::string msg;
  16020. ASSERT_TRUE(client2.read(msg));
  16021. EXPECT_EQ("hello", msg);
  16022. client2.close();
  16023. svr.stop();
  16024. t.join();
  16025. }
  16026. TEST(WebSocketTest, QueryStringInHandshake) {
  16027. Server svr;
  16028. std::mutex mtx;
  16029. std::string received_target;
  16030. std::string received_token;
  16031. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16032. {
  16033. std::lock_guard<std::mutex> lock(mtx);
  16034. received_target = req.target;
  16035. if (req.has_param("token")) {
  16036. received_token = req.get_param_value("token");
  16037. }
  16038. }
  16039. std::string msg;
  16040. while (ws.read(msg)) {
  16041. ws.send(msg);
  16042. }
  16043. });
  16044. auto port = svr.bind_to_any_port("localhost");
  16045. std::thread t([&]() { svr.listen_after_bind(); });
  16046. svr.wait_until_ready();
  16047. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16048. "/ws?token=ABC&session=123");
  16049. ASSERT_TRUE(client.connect());
  16050. // Round-trip ensures the handler has run and captured the request.
  16051. ASSERT_TRUE(client.send("hello"));
  16052. std::string msg;
  16053. ASSERT_TRUE(client.read(msg));
  16054. EXPECT_EQ("hello", msg);
  16055. client.close();
  16056. {
  16057. std::lock_guard<std::mutex> lock(mtx);
  16058. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16059. EXPECT_EQ("ABC", received_token);
  16060. }
  16061. svr.stop();
  16062. t.join();
  16063. }
  16064. TEST(WebSocketTest, HostHeaderInHandshake) {
  16065. Server svr;
  16066. std::mutex mtx;
  16067. std::string received_host;
  16068. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16069. {
  16070. std::lock_guard<std::mutex> lock(mtx);
  16071. received_host = req.get_header_value("Host");
  16072. }
  16073. std::string msg;
  16074. while (ws.read(msg)) {
  16075. ws.send(msg);
  16076. }
  16077. });
  16078. auto port = svr.bind_to_any_port("localhost");
  16079. std::thread t([&]() { svr.listen_after_bind(); });
  16080. svr.wait_until_ready();
  16081. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16082. ASSERT_TRUE(client.connect());
  16083. // Round-trip ensures the handler has run and captured the request.
  16084. ASSERT_TRUE(client.send("hello"));
  16085. std::string msg;
  16086. ASSERT_TRUE(client.read(msg));
  16087. client.close();
  16088. {
  16089. std::lock_guard<std::mutex> lock(mtx);
  16090. // Non-default port must be present in the Host header. Default ports
  16091. // (80/443) are omitted; that logic is covered by
  16092. // MakeHostAndPortStringTest.
  16093. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16094. }
  16095. svr.stop();
  16096. t.join();
  16097. }
  16098. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16099. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16100. protected:
  16101. void SetUp() override {
  16102. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16103. SERVER_PRIVATE_KEY_FILE);
  16104. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16105. std::string msg;
  16106. ws::ReadResult ret;
  16107. while ((ret = ws.read(msg))) {
  16108. if (ret == ws::Binary) {
  16109. ws.send(msg.data(), msg.size());
  16110. } else {
  16111. ws.send(msg);
  16112. }
  16113. }
  16114. });
  16115. port_ = server_->bind_to_any_port(HOST);
  16116. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16117. server_->wait_until_ready();
  16118. }
  16119. void TearDown() override {
  16120. server_->stop();
  16121. if (server_thread_.joinable()) { server_thread_.join(); }
  16122. }
  16123. std::unique_ptr<SSLServer> server_;
  16124. std::thread server_thread_;
  16125. int port_ = 0;
  16126. };
  16127. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16128. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16129. "/ws-echo");
  16130. client.enable_server_certificate_verification(false);
  16131. ASSERT_TRUE(client.connect());
  16132. ASSERT_TRUE(client.is_open());
  16133. ASSERT_TRUE(client.send("Hello WSS"));
  16134. std::string msg;
  16135. EXPECT_EQ(ws::Text, client.read(msg));
  16136. EXPECT_EQ("Hello WSS", msg);
  16137. client.close();
  16138. }
  16139. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16140. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16141. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16142. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16143. // client (without calling close() first) is the only path that runs
  16144. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16145. // bug exactly.
  16146. //
  16147. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16148. // when linked against an instrumented libssl; run under Valgrind to catch it
  16149. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16150. // suite (the freed session otherwise stalls on the close handshake) — this test
  16151. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16152. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16153. {
  16154. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16155. "/ws-echo");
  16156. client.enable_server_certificate_verification(false);
  16157. client.set_read_timeout(2, 0);
  16158. client.set_write_timeout(2, 0);
  16159. ASSERT_TRUE(client.connect());
  16160. ASSERT_TRUE(client.is_open());
  16161. ASSERT_TRUE(client.send("still open"));
  16162. // Intentionally do NOT call client.close(): leaving scope runs
  16163. // shutdown_and_close() with the WebSocket still open, which must send the
  16164. // close frame while the TLS session is still alive.
  16165. }
  16166. }
  16167. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16168. // shutdown_and_close() at the start of connect(), reproducing the same
  16169. // use-after-free within the test body rather than at scope exit. The second
  16170. // connect must succeed and echo, proving the close handshake ran over a live
  16171. // session. See the note above about memory-tool requirements.
  16172. TEST_F(WebSocketSSLIntegrationTest,
  16173. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16174. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16175. "/ws-echo");
  16176. client.enable_server_certificate_verification(false);
  16177. client.set_read_timeout(2, 0);
  16178. client.set_write_timeout(2, 0);
  16179. ASSERT_TRUE(client.connect());
  16180. ASSERT_TRUE(client.is_open());
  16181. ASSERT_TRUE(client.send("still open"));
  16182. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16183. // the still-open connection, which must not touch a freed TLS session.
  16184. ASSERT_TRUE(client.connect());
  16185. ASSERT_TRUE(client.is_open());
  16186. ASSERT_TRUE(client.send("after reconnect"));
  16187. std::string msg;
  16188. EXPECT_EQ(ws::Text, client.read(msg));
  16189. EXPECT_EQ("after reconnect", msg);
  16190. client.close();
  16191. }
  16192. #endif
  16193. #ifdef CPPHTTPLIB_SSL_ENABLED
  16194. class WebSocketSSLCATest : public ::testing::Test {
  16195. protected:
  16196. void SetUp() override {
  16197. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16198. SERVER_PRIVATE_KEY_FILE);
  16199. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16200. std::string msg;
  16201. while (ws.read(msg)) {
  16202. ws.send(msg);
  16203. }
  16204. });
  16205. port_ = server_->bind_to_any_port("127.0.0.1");
  16206. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16207. server_->wait_until_ready();
  16208. }
  16209. void TearDown() override {
  16210. server_->stop();
  16211. if (server_thread_.joinable()) { server_thread_.join(); }
  16212. }
  16213. std::string url() const {
  16214. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16215. }
  16216. std::unique_ptr<SSLServer> server_;
  16217. std::thread server_thread_;
  16218. int port_ = 0;
  16219. };
  16220. // A custom CA loaded as PEM verifies the server with full certificate
  16221. // verification enabled
  16222. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16223. ws::WebSocketClient client(url());
  16224. std::string cert;
  16225. read_file(SERVER_CERT2_FILE, cert);
  16226. client.load_ca_cert_store(cert.c_str(), cert.size());
  16227. ASSERT_TRUE(client.connect());
  16228. ASSERT_TRUE(client.send("hello"));
  16229. std::string msg;
  16230. EXPECT_EQ(ws::Text, client.read(msg));
  16231. EXPECT_EQ("hello", msg);
  16232. client.close();
  16233. }
  16234. // A custom CA that does not cover the server must fail verification (the
  16235. // custom CA is exclusive; system certs are not loaded alongside it)
  16236. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16237. ws::WebSocketClient client(url());
  16238. std::string cert;
  16239. read_file(CLIENT_CA_CERT_FILE, cert);
  16240. client.load_ca_cert_store(cert.c_str(), cert.size());
  16241. ASSERT_FALSE(client.connect());
  16242. }
  16243. // Regression test: reconnecting with a native custom CA store used to reuse
  16244. // a store handle the previous TLS context had already freed (use-after-free
  16245. // under the OpenSSL backend). The context now lives as long as the client.
  16246. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16247. ws::WebSocketClient client(url());
  16248. std::string cert;
  16249. read_file(SERVER_CERT2_FILE, cert);
  16250. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16251. ASSERT_TRUE(client.connect());
  16252. client.close();
  16253. ASSERT_TRUE(client.connect());
  16254. ASSERT_TRUE(client.send("again"));
  16255. std::string msg;
  16256. EXPECT_EQ(ws::Text, client.read(msg));
  16257. EXPECT_EQ("again", msg);
  16258. client.close();
  16259. }
  16260. // Regression test: a certificate with a trusted chain but no identity match
  16261. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16262. // verification entirely for IP hosts, so this connection succeeded there.
  16263. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16264. // chain verification while the identity check must still fail.
  16265. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16267. ASSERT_TRUE(svr.is_valid());
  16268. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16269. std::string msg;
  16270. while (ws.read(msg)) {
  16271. ws.send(msg);
  16272. }
  16273. });
  16274. auto port = svr.bind_to_any_port("127.0.0.1");
  16275. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16276. auto se = detail::scope_exit([&] {
  16277. svr.stop();
  16278. t.join();
  16279. });
  16280. svr.wait_until_ready();
  16281. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16282. "/echo");
  16283. std::string cert;
  16284. read_file(SERVER_CERT_FILE, cert);
  16285. client.load_ca_cert_store(cert.c_str(), cert.size());
  16286. ASSERT_FALSE(client.connect());
  16287. }
  16288. #endif
  16289. #if !defined(_WIN32)
  16290. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16291. auto secret_dir = std::string("./symlink_test_secret");
  16292. auto served_dir = std::string("./symlink_test_served");
  16293. auto secret_file = secret_dir + "/secret.txt";
  16294. auto symlink_path = served_dir + "/escape";
  16295. // Setup: create directories and files
  16296. mkdir(secret_dir.c_str(), 0755);
  16297. mkdir(served_dir.c_str(), 0755);
  16298. {
  16299. std::ofstream ofs(secret_file);
  16300. ofs << "SECRET_DATA";
  16301. }
  16302. // Create symlink using absolute path so it resolves correctly
  16303. #ifdef PATH_MAX
  16304. char abs_secret[PATH_MAX];
  16305. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16306. #else
  16307. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16308. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16309. ASSERT_NE(nullptr, abs_secret);
  16310. #endif
  16311. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16312. auto se = detail::scope_exit([&] {
  16313. unlink(symlink_path.c_str());
  16314. unlink(secret_file.c_str());
  16315. rmdir(served_dir.c_str());
  16316. rmdir(secret_dir.c_str());
  16317. });
  16318. Server svr;
  16319. svr.set_mount_point("/", served_dir);
  16320. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16321. auto se2 = detail::scope_exit([&] {
  16322. svr.stop();
  16323. listen_thread.join();
  16324. });
  16325. svr.wait_until_ready();
  16326. Client cli("localhost", PORT);
  16327. // Symlink pointing outside base dir should be blocked
  16328. auto res = cli.Get("/escape/secret.txt");
  16329. ASSERT_TRUE(res);
  16330. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16331. }
  16332. #endif
  16333. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16334. // A GET request with Content-Length to a static file handler must have its
  16335. // body drained before the keep-alive connection is reused. Otherwise the
  16336. // unread body bytes are interpreted as the next HTTP request.
  16337. //
  16338. // The body is sent AFTER receiving the first response (as in the original
  16339. // PoC) so that the stream_line_reader cannot buffer it together with the
  16340. // headers of the first request.
  16341. Server svr;
  16342. svr.set_mount_point("/", "./www");
  16343. std::atomic<int> smuggled_count(0);
  16344. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16345. smuggled_count++;
  16346. res.set_content("oops", "text/plain");
  16347. });
  16348. auto port = svr.bind_to_any_port("localhost");
  16349. thread t = thread([&] { svr.listen_after_bind(); });
  16350. auto se = detail::scope_exit([&] {
  16351. svr.stop();
  16352. t.join();
  16353. });
  16354. svr.wait_until_ready();
  16355. auto error = Error::Success;
  16356. auto sock = detail::create_client_socket(
  16357. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16358. /*connection_timeout_sec=*/2, 0,
  16359. /*read_timeout_sec=*/2, 0,
  16360. /*write_timeout_sec=*/2, 0, std::string(), error);
  16361. ASSERT_NE(INVALID_SOCKET, sock);
  16362. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16363. // The "smuggled" request will be sent as the body of the outer GET
  16364. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16365. "Host: localhost\r\n"
  16366. "Connection: close\r\n"
  16367. "\r\n";
  16368. // Step 1: Send only the outer request headers (no body yet)
  16369. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16370. "Host: localhost\r\n"
  16371. "Content-Length: " +
  16372. std::to_string(smuggled.size()) +
  16373. "\r\n"
  16374. "\r\n";
  16375. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16376. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16377. // Step 2: Read the first response (server serves file without reading body)
  16378. std::string first_response;
  16379. char buf[4096];
  16380. for (;;) {
  16381. auto n = recv(sock, buf, sizeof(buf), 0);
  16382. if (n <= 0) break;
  16383. first_response.append(buf, static_cast<size_t>(n));
  16384. // Stop once we have a complete response (headers + body)
  16385. auto hdr_end = first_response.find("\r\n\r\n");
  16386. if (hdr_end != std::string::npos) {
  16387. // Check for Content-Length to know when the body is complete
  16388. auto cl_pos = first_response.find("Content-Length:");
  16389. if (cl_pos != std::string::npos) {
  16390. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16391. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16392. auto cl = std::stoul(
  16393. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16394. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16395. } else {
  16396. break; // No Content-Length, assume headers-only response
  16397. }
  16398. }
  16399. }
  16400. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16401. // Step 3: Now send the body, which looks like a new HTTP request.
  16402. // On a vulnerable server the keep-alive loop reads this as a second request.
  16403. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16404. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16405. // Step 4: Try to read a second response (should NOT exist after fix)
  16406. std::string second_response;
  16407. for (;;) {
  16408. auto n = recv(sock, buf, sizeof(buf), 0);
  16409. if (n <= 0) break;
  16410. second_response.append(buf, static_cast<size_t>(n));
  16411. }
  16412. // The smuggled request must NOT have been processed
  16413. EXPECT_EQ(0, smuggled_count.load());
  16414. }
  16415. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16416. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16417. // must be rejected with 400 Bad Request.
  16418. Server svr;
  16419. svr.Post("/test", [&](const Request &, Response &res) {
  16420. res.set_content("ok", "text/plain");
  16421. });
  16422. thread t = thread([&] { svr.listen(HOST, PORT); });
  16423. auto se = detail::scope_exit([&] {
  16424. svr.stop();
  16425. t.join();
  16426. ASSERT_FALSE(svr.is_running());
  16427. });
  16428. svr.wait_until_ready();
  16429. // Exact "chunked"
  16430. {
  16431. auto req = "POST /test HTTP/1.1\r\n"
  16432. "Host: localhost\r\n"
  16433. "Content-Length: 5\r\n"
  16434. "Transfer-Encoding: chunked\r\n"
  16435. "Connection: close\r\n"
  16436. "\r\n"
  16437. "hello";
  16438. std::string response;
  16439. ASSERT_TRUE(send_request(1, req, &response));
  16440. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16441. response.substr(0, response.find("\r\n")));
  16442. }
  16443. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16444. {
  16445. auto req = "POST /test HTTP/1.1\r\n"
  16446. "Host: localhost\r\n"
  16447. "Content-Length: 5\r\n"
  16448. "Transfer-Encoding: gzip, chunked\r\n"
  16449. "Connection: close\r\n"
  16450. "\r\n"
  16451. "hello";
  16452. std::string response;
  16453. ASSERT_TRUE(send_request(1, req, &response));
  16454. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16455. response.substr(0, response.find("\r\n")));
  16456. }
  16457. }
  16458. // Regression for issue #2450: a DELETE without Content-Length on a
  16459. // keep-alive connection must not let the post-response drain consume the
  16460. // next request's bytes.
  16461. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16462. Server svr;
  16463. std::atomic<int> delete_count(0);
  16464. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16465. delete_count++;
  16466. res.status = StatusCode::NoContent_204;
  16467. });
  16468. auto port = svr.bind_to_any_port(HOST);
  16469. thread t = thread([&] { svr.listen_after_bind(); });
  16470. auto se = detail::scope_exit([&] {
  16471. svr.stop();
  16472. t.join();
  16473. });
  16474. svr.wait_until_ready();
  16475. auto error = Error::Success;
  16476. auto sock = detail::create_client_socket(
  16477. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16478. /*connection_timeout_sec=*/2, 0,
  16479. /*read_timeout_sec=*/2, 0,
  16480. /*write_timeout_sec=*/2, 0, std::string(), error);
  16481. ASSERT_NE(INVALID_SOCKET, sock);
  16482. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16483. auto send_request_and_read_response = [&](const std::string &req,
  16484. std::string &out) -> bool {
  16485. auto sent = send(sock, req.data(), req.size(), 0);
  16486. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16487. char buf[4096];
  16488. for (;;) {
  16489. auto n = recv(sock, buf, sizeof(buf), 0);
  16490. if (n <= 0) { return !out.empty(); }
  16491. out.append(buf, static_cast<size_t>(n));
  16492. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16493. }
  16494. };
  16495. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16496. "Host: localhost\r\n"
  16497. "\r\n";
  16498. std::string resp1;
  16499. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16500. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16501. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16502. "Host: localhost\r\n"
  16503. "Connection: close\r\n"
  16504. "\r\n";
  16505. std::string resp2;
  16506. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16507. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16508. EXPECT_EQ(2, delete_count.load());
  16509. }
  16510. namespace no_proxy_test {
  16511. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16512. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16513. // calling listen().
  16514. class ScopedServer {
  16515. public:
  16516. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16517. ~ScopedServer() {
  16518. svr_.stop();
  16519. if (th_.joinable()) { th_.join(); }
  16520. }
  16521. Server &svr() { return svr_; }
  16522. int port() const { return port_; }
  16523. void listen() {
  16524. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16525. svr_.wait_until_ready();
  16526. }
  16527. private:
  16528. Server svr_;
  16529. std::thread th_;
  16530. int port_ = 0;
  16531. };
  16532. class ProxyAndTargetServers {
  16533. public:
  16534. ProxyAndTargetServers() {
  16535. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16536. proxy_hits_++;
  16537. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16538. res.set_content("via-proxy", "text/plain");
  16539. });
  16540. target_.Get(".*", [this](const Request &req, Response &res) {
  16541. target_hits_++;
  16542. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16543. res.set_content("direct", "text/plain");
  16544. });
  16545. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16546. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16547. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16548. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16549. proxy_mock_.wait_until_ready();
  16550. target_.wait_until_ready();
  16551. }
  16552. ~ProxyAndTargetServers() {
  16553. proxy_mock_.stop();
  16554. target_.stop();
  16555. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16556. if (target_thread_.joinable()) { target_thread_.join(); }
  16557. }
  16558. Server &proxy_mock() { return proxy_mock_; }
  16559. Server &target() { return target_; }
  16560. int proxy_port() const { return proxy_port_; }
  16561. int target_port() const { return target_port_; }
  16562. int proxy_hits() const { return proxy_hits_.load(); }
  16563. int target_hits() const { return target_hits_.load(); }
  16564. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16565. void reset_counters() {
  16566. proxy_hits_ = 0;
  16567. target_hits_ = 0;
  16568. last_had_proxy_authz_ = false;
  16569. }
  16570. private:
  16571. Server proxy_mock_;
  16572. Server target_;
  16573. std::thread proxy_thread_;
  16574. std::thread target_thread_;
  16575. int proxy_port_ = 0;
  16576. int target_port_ = 0;
  16577. std::atomic<int> proxy_hits_{0};
  16578. std::atomic<int> target_hits_{0};
  16579. std::atomic<bool> last_had_proxy_authz_{false};
  16580. };
  16581. inline std::unique_ptr<Client> make_client(const std::string &host,
  16582. ProxyAndTargetServers &s) {
  16583. auto cli = detail::make_unique<Client>(host, s.target_port());
  16584. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16585. cli->set_proxy("127.0.0.1", s.proxy_port());
  16586. return cli;
  16587. }
  16588. } // namespace no_proxy_test
  16589. using no_proxy_test::make_client;
  16590. using no_proxy_test::ProxyAndTargetServers;
  16591. TEST(NoProxyTest, ExactHostnameBypasses) {
  16592. ProxyAndTargetServers s;
  16593. auto cli = make_client("example.com", s);
  16594. cli->set_no_proxy({"example.com"});
  16595. auto res = cli->Get("/");
  16596. ASSERT_TRUE(res);
  16597. EXPECT_EQ(0, s.proxy_hits());
  16598. EXPECT_EQ(1, s.target_hits());
  16599. }
  16600. TEST(NoProxyTest, SubdomainBypasses) {
  16601. ProxyAndTargetServers s;
  16602. auto cli = make_client("foo.example.com", s);
  16603. cli->set_no_proxy({"example.com"});
  16604. auto res = cli->Get("/");
  16605. ASSERT_TRUE(res);
  16606. EXPECT_EQ(0, s.proxy_hits());
  16607. EXPECT_EQ(1, s.target_hits());
  16608. }
  16609. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16610. // Regression guard: "evilexample.com" must not be considered a subdomain
  16611. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16612. // check would let traffic bypass the proxy and leak credentials direct
  16613. // to the attacker host.
  16614. ProxyAndTargetServers s;
  16615. auto cli = make_client("evilexample.com", s);
  16616. cli->set_no_proxy({"example.com"});
  16617. auto res = cli->Get("/");
  16618. ASSERT_TRUE(res);
  16619. EXPECT_GE(s.proxy_hits(), 1);
  16620. EXPECT_EQ(0, s.target_hits());
  16621. }
  16622. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16623. ProxyAndTargetServers s;
  16624. auto cli = make_client("example.com.evil.com", s);
  16625. cli->set_no_proxy({"example.com"});
  16626. auto res = cli->Get("/");
  16627. ASSERT_TRUE(res);
  16628. EXPECT_GE(s.proxy_hits(), 1);
  16629. EXPECT_EQ(0, s.target_hits());
  16630. }
  16631. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16632. ProxyAndTargetServers s;
  16633. auto cli = make_client("example.com", s);
  16634. cli->set_no_proxy({".example.com"});
  16635. auto res = cli->Get("/");
  16636. ASSERT_TRUE(res);
  16637. EXPECT_EQ(0, s.proxy_hits());
  16638. EXPECT_EQ(1, s.target_hits());
  16639. }
  16640. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16641. ProxyAndTargetServers s;
  16642. auto cli = make_client("Example.COM", s);
  16643. cli->set_no_proxy({"EXAMPLE.com"});
  16644. auto res = cli->Get("/");
  16645. ASSERT_TRUE(res);
  16646. EXPECT_EQ(0, s.proxy_hits());
  16647. EXPECT_EQ(1, s.target_hits());
  16648. }
  16649. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16650. ProxyAndTargetServers s;
  16651. auto cli = make_client("example.com.", s);
  16652. cli->set_no_proxy({"example.com"});
  16653. auto res = cli->Get("/");
  16654. ASSERT_TRUE(res);
  16655. EXPECT_EQ(0, s.proxy_hits());
  16656. EXPECT_EQ(1, s.target_hits());
  16657. }
  16658. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16659. // Trailing dots must be normalized on BOTH sides — host and entry.
  16660. // An implementation that only strips the host-side trailing dot would
  16661. // fail to match host "example.com" against entry "example.com." because
  16662. // a literal substring search would compare 11 chars against 12.
  16663. ProxyAndTargetServers s;
  16664. auto cli = make_client("example.com", s);
  16665. cli->set_no_proxy({"example.com."});
  16666. auto res = cli->Get("/");
  16667. ASSERT_TRUE(res);
  16668. EXPECT_EQ(0, s.proxy_hits());
  16669. EXPECT_EQ(1, s.target_hits());
  16670. }
  16671. TEST(NoProxyTest, WildcardBypassesEverything) {
  16672. ProxyAndTargetServers s;
  16673. auto cli = make_client("anything.invalid.test", s);
  16674. cli->set_no_proxy({"*"});
  16675. auto res = cli->Get("/");
  16676. ASSERT_TRUE(res);
  16677. EXPECT_EQ(0, s.proxy_hits());
  16678. EXPECT_EQ(1, s.target_hits());
  16679. }
  16680. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  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_EQ(0, s.proxy_hits());
  16688. EXPECT_EQ(1, s.target_hits());
  16689. }
  16690. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16691. ProxyAndTargetServers s;
  16692. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16693. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16694. cli.set_proxy("127.0.0.1", s.proxy_port());
  16695. cli.set_no_proxy({"::1"});
  16696. auto res = cli.Get("/");
  16697. ASSERT_TRUE(res);
  16698. EXPECT_EQ(0, s.proxy_hits());
  16699. EXPECT_EQ(1, s.target_hits());
  16700. }
  16701. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16702. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16703. // must still be recognized as IPv6 for CIDR matching. Implementations
  16704. // that detect IPv6 only when the host begins with '[' would parse the
  16705. // host as a hostname and miss the match.
  16706. ProxyAndTargetServers s;
  16707. Client cli("fe80::1", s.target_port());
  16708. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16709. cli.set_proxy("127.0.0.1", s.proxy_port());
  16710. cli.set_no_proxy({"fe80::/10"});
  16711. auto res = cli.Get("/");
  16712. ASSERT_TRUE(res);
  16713. EXPECT_EQ(0, s.proxy_hits());
  16714. EXPECT_EQ(1, s.target_hits());
  16715. }
  16716. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16717. ProxyAndTargetServers s;
  16718. Client cli("::1", s.target_port());
  16719. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16720. cli.set_proxy("127.0.0.1", s.proxy_port());
  16721. cli.set_no_proxy({"[::1]"});
  16722. auto res = cli.Get("/");
  16723. ASSERT_TRUE(res);
  16724. EXPECT_EQ(0, s.proxy_hits());
  16725. EXPECT_EQ(1, s.target_hits());
  16726. }
  16727. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16728. ProxyAndTargetServers s;
  16729. Client cli("fe80::1", s.target_port());
  16730. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16731. cli.set_proxy("127.0.0.1", s.proxy_port());
  16732. cli.set_no_proxy({"[fe80::]/10"});
  16733. auto res = cli.Get("/");
  16734. ASSERT_TRUE(res);
  16735. EXPECT_EQ(0, s.proxy_hits());
  16736. EXPECT_EQ(1, s.target_hits());
  16737. }
  16738. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16739. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16740. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16741. // tricks via address-family conversion.
  16742. ProxyAndTargetServers s;
  16743. Client cli("::ffff:127.0.0.1", s.target_port());
  16744. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16745. cli.set_proxy("127.0.0.1", s.proxy_port());
  16746. cli.set_no_proxy({"127.0.0.1"});
  16747. auto res = cli.Get("/");
  16748. ASSERT_TRUE(res);
  16749. EXPECT_GE(s.proxy_hits(), 1);
  16750. EXPECT_EQ(0, s.target_hits());
  16751. }
  16752. TEST(NoProxyTest, IPv4CidrMatch) {
  16753. ProxyAndTargetServers s;
  16754. Client cli("127.0.0.1", s.target_port());
  16755. cli.set_proxy("127.0.0.1", s.proxy_port());
  16756. cli.set_no_proxy({"127.0.0.0/8"});
  16757. auto res = cli.Get("/");
  16758. ASSERT_TRUE(res);
  16759. EXPECT_EQ(0, s.proxy_hits());
  16760. EXPECT_EQ(1, s.target_hits());
  16761. }
  16762. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16763. ProxyAndTargetServers s;
  16764. Client cli("127.0.0.1", s.target_port());
  16765. cli.set_proxy("127.0.0.1", s.proxy_port());
  16766. cli.set_no_proxy({"10.0.0.0/8"});
  16767. auto res = cli.Get("/");
  16768. ASSERT_TRUE(res);
  16769. EXPECT_GE(s.proxy_hits(), 1);
  16770. EXPECT_EQ(0, s.target_hits());
  16771. }
  16772. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16773. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16774. // IPv4 target matches.
  16775. ProxyAndTargetServers s;
  16776. Client cli("127.0.0.1", s.target_port());
  16777. cli.set_proxy("127.0.0.1", s.proxy_port());
  16778. cli.set_no_proxy({"0.0.0.0/0"});
  16779. auto res = cli.Get("/");
  16780. ASSERT_TRUE(res);
  16781. EXPECT_EQ(0, s.proxy_hits());
  16782. EXPECT_EQ(1, s.target_hits());
  16783. }
  16784. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16785. ProxyAndTargetServers s;
  16786. Client cli("127.0.0.1", s.target_port());
  16787. cli.set_proxy("127.0.0.1", s.proxy_port());
  16788. cli.set_no_proxy({"127.0.0.1"});
  16789. auto res = cli.Get("/");
  16790. ASSERT_TRUE(res);
  16791. EXPECT_EQ(0, s.proxy_hits());
  16792. EXPECT_EQ(1, s.target_hits());
  16793. }
  16794. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16795. ProxyAndTargetServers s;
  16796. Client cli("127.0.0.1", s.target_port());
  16797. cli.set_proxy("127.0.0.1", s.proxy_port());
  16798. cli.set_no_proxy({"127.0.0.0/33"});
  16799. auto res = cli.Get("/");
  16800. ASSERT_TRUE(res);
  16801. EXPECT_GE(s.proxy_hits(), 1);
  16802. EXPECT_EQ(0, s.target_hits());
  16803. }
  16804. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16805. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16806. ProxyAndTargetServers s;
  16807. Client cli("127.0.0.1", s.target_port());
  16808. cli.set_proxy("127.0.0.1", s.proxy_port());
  16809. cli.set_no_proxy({"127.0.0.1/"});
  16810. auto res = cli.Get("/");
  16811. ASSERT_TRUE(res);
  16812. EXPECT_GE(s.proxy_hits(), 1);
  16813. EXPECT_EQ(0, s.target_hits());
  16814. }
  16815. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16816. ProxyAndTargetServers s;
  16817. auto cli = make_client("internal.corp", s);
  16818. cli->set_proxy_basic_auth("u", "p");
  16819. cli->set_no_proxy({"internal.corp"});
  16820. auto res = cli->Get("/");
  16821. ASSERT_TRUE(res);
  16822. EXPECT_EQ(1, s.target_hits());
  16823. EXPECT_EQ(0, s.proxy_hits());
  16824. EXPECT_FALSE(s.last_had_proxy_authz())
  16825. << "Proxy-Authorization must not be sent direct to the target";
  16826. }
  16827. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16828. ProxyAndTargetServers s;
  16829. auto cli = make_client("public.example", s);
  16830. cli->set_proxy_basic_auth("u", "p");
  16831. cli->set_no_proxy({"internal.corp"}); // does not match
  16832. auto res = cli->Get("/");
  16833. ASSERT_TRUE(res);
  16834. EXPECT_GE(s.proxy_hits(), 1);
  16835. EXPECT_TRUE(s.last_had_proxy_authz());
  16836. }
  16837. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16838. ProxyAndTargetServers s;
  16839. auto cli = make_client("anything.test", s);
  16840. auto res = cli->Get("/");
  16841. ASSERT_TRUE(res);
  16842. EXPECT_GE(s.proxy_hits(), 1);
  16843. EXPECT_EQ(0, s.target_hits());
  16844. }
  16845. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16846. ProxyAndTargetServers s;
  16847. auto cli = make_client("example.com", s);
  16848. cli->set_no_proxy({"example.com:8080"});
  16849. auto res = cli->Get("/");
  16850. ASSERT_TRUE(res);
  16851. EXPECT_GE(s.proxy_hits(), 1);
  16852. EXPECT_EQ(0, s.target_hits());
  16853. }
  16854. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16855. ProxyAndTargetServers s;
  16856. auto cli = make_client("anything.test", s);
  16857. cli->set_no_proxy({"", " ", "\t"});
  16858. auto res = cli->Get("/");
  16859. ASSERT_TRUE(res);
  16860. EXPECT_GE(s.proxy_hits(), 1);
  16861. EXPECT_EQ(0, s.target_hits());
  16862. }
  16863. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16864. // An entry with leading/trailing whitespace must still match — env-style
  16865. // values are commonly pasted with stray spaces and an implementation
  16866. // that feeds the raw token directly to inet_pton would fail to match
  16867. // valid CIDRs because of the spaces.
  16868. ProxyAndTargetServers s;
  16869. Client cli("127.0.0.1", s.target_port());
  16870. cli.set_proxy("127.0.0.1", s.proxy_port());
  16871. cli.set_no_proxy({" 127.0.0.0/8 "});
  16872. auto res = cli.Get("/");
  16873. ASSERT_TRUE(res);
  16874. EXPECT_EQ(0, s.proxy_hits());
  16875. EXPECT_EQ(1, s.target_hits());
  16876. }
  16877. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16878. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16879. // go direct and must NOT carry Proxy-Authorization.
  16880. std::atomic<int> proxy_hits{0};
  16881. std::atomic<int> target_hits{0};
  16882. std::atomic<bool> target_saw_authz{false};
  16883. no_proxy_test::ScopedServer proxy_mock, target;
  16884. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16885. proxy_hits++;
  16886. res.status = 302;
  16887. res.set_header("Location", "http://127.0.0.1:" +
  16888. std::to_string(target.port()) + "/landed");
  16889. });
  16890. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16891. target_hits++;
  16892. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16893. res.set_content("direct", "text/plain");
  16894. });
  16895. proxy_mock.listen();
  16896. target.listen();
  16897. Client cli("public.example", target.port());
  16898. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16899. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16900. cli.set_proxy_basic_auth("u", "p");
  16901. cli.set_no_proxy({"127.0.0.1"});
  16902. cli.set_follow_location(true);
  16903. auto res = cli.Get("/redir");
  16904. ASSERT_TRUE(res);
  16905. EXPECT_GE(proxy_hits.load(), 1);
  16906. EXPECT_GE(target_hits.load(), 1);
  16907. EXPECT_FALSE(target_saw_authz.load());
  16908. }
  16909. #ifdef CPPHTTPLIB_SSL_ENABLED
  16910. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16911. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16912. // proxy creds would be sent to the (possibly hostile) origin.
  16913. std::atomic<int> target_hits{0};
  16914. std::atomic<bool> target_saw_proxy_authz{false};
  16915. no_proxy_test::ScopedServer target;
  16916. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16917. target_hits++;
  16918. if (req.has_header("Proxy-Authorization")) {
  16919. target_saw_proxy_authz = true;
  16920. }
  16921. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16922. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16923. "nonce=\"abc\", algorithm=MD5");
  16924. });
  16925. target.listen();
  16926. // The proxy address is set to the target's port: the bypass MUST kick in;
  16927. // if it doesn't, the test still routes "via proxy" to the same server and
  16928. // the Proxy-Authorization assertion below catches the leak.
  16929. Client cli("evil.example", target.port());
  16930. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16931. cli.set_proxy("127.0.0.1", target.port());
  16932. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16933. cli.set_no_proxy({"evil.example"});
  16934. auto res = cli.Get("/x");
  16935. ASSERT_TRUE(res);
  16936. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16937. EXPECT_EQ(1, target_hits.load());
  16938. EXPECT_FALSE(target_saw_proxy_authz.load());
  16939. }
  16940. #endif
  16941. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16942. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16943. std::atomic<int> proxy_hits{0};
  16944. std::atomic<int> bypass_hits{0};
  16945. std::atomic<bool> proxy_saw_c_url{false};
  16946. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16947. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16948. proxy_hits++;
  16949. if (req.path.find("/start") != std::string::npos) {
  16950. res.status = 302;
  16951. res.set_header("Location", "http://127.0.0.1:" +
  16952. std::to_string(bypass_server.port()) +
  16953. "/middle");
  16954. return;
  16955. }
  16956. if (req.path.find("/end") != std::string::npos) {
  16957. proxy_saw_c_url = true;
  16958. res.set_content("c-via-proxy", "text/plain");
  16959. return;
  16960. }
  16961. res.set_content("unexpected", "text/plain");
  16962. });
  16963. // public.example's "advertised" port is arbitrary (the request never lands
  16964. // there — it goes through the proxy), but use a dynamic value to stay
  16965. // friendly with sharded parallel runs.
  16966. int public_port = bypass_server.port();
  16967. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16968. bypass_hits++;
  16969. res.status = 302;
  16970. res.set_header("Location", "http://public.example:" +
  16971. std::to_string(public_port) + "/end");
  16972. });
  16973. proxy_mock.listen();
  16974. bypass_server.listen();
  16975. Client cli("public.example", public_port);
  16976. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16977. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16978. cli.set_no_proxy({"127.0.0.1"});
  16979. cli.set_follow_location(true);
  16980. auto res = cli.Get("/start");
  16981. ASSERT_TRUE(res);
  16982. EXPECT_EQ(StatusCode::OK_200, res->status);
  16983. EXPECT_EQ("c-via-proxy", res->body);
  16984. EXPECT_GE(proxy_hits.load(), 2);
  16985. EXPECT_GE(bypass_hits.load(), 1);
  16986. EXPECT_TRUE(proxy_saw_c_url.load());
  16987. }
  16988. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16989. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16990. // request reconnects to the correct endpoint.
  16991. std::atomic<int> proxy_hits{0};
  16992. std::atomic<int> target_hits{0};
  16993. no_proxy_test::ScopedServer proxy_mock, target;
  16994. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16995. proxy_hits++;
  16996. res.set_content("via-proxy", "text/plain");
  16997. });
  16998. target.svr().Get(".*", [&](const Request &, Response &res) {
  16999. target_hits++;
  17000. res.set_content("direct", "text/plain");
  17001. });
  17002. proxy_mock.listen();
  17003. target.listen();
  17004. Client cli("public.example", target.port());
  17005. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17006. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17007. cli.set_keep_alive(true);
  17008. auto res1 = cli.Get("/a");
  17009. ASSERT_TRUE(res1);
  17010. EXPECT_EQ("via-proxy", res1->body);
  17011. EXPECT_EQ(1, proxy_hits.load());
  17012. EXPECT_EQ(0, target_hits.load());
  17013. cli.set_no_proxy({"public.example"});
  17014. auto res2 = cli.Get("/b");
  17015. ASSERT_TRUE(res2);
  17016. EXPECT_EQ("direct", res2->body);
  17017. EXPECT_EQ(1, proxy_hits.load());
  17018. EXPECT_EQ(1, target_hits.load());
  17019. }
  17020. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17021. namespace proxy_tunnel_test {
  17022. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17023. class ScopedSSLServer {
  17024. public:
  17025. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17026. port_ = svr_.bind_to_any_port("127.0.0.1");
  17027. }
  17028. ~ScopedSSLServer() {
  17029. svr_.stop();
  17030. if (th_.joinable()) { th_.join(); }
  17031. }
  17032. SSLServer &svr() { return svr_; }
  17033. int port() const { return port_; }
  17034. void listen() {
  17035. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17036. svr_.wait_until_ready();
  17037. }
  17038. private:
  17039. SSLServer svr_;
  17040. std::thread th_;
  17041. int port_ = 0;
  17042. };
  17043. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17044. class ScopedConnectProxy {
  17045. public:
  17046. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17047. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17048. if (listen_fd_ < 0) { return; }
  17049. int yes = 1;
  17050. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17051. sockaddr_in a{};
  17052. a.sin_family = AF_INET;
  17053. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17054. a.sin_port = 0;
  17055. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17056. return;
  17057. }
  17058. socklen_t alen = sizeof(a);
  17059. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17060. 0) {
  17061. return;
  17062. }
  17063. port_ = ntohs(a.sin_port);
  17064. if (::listen(listen_fd_, 1) != 0) { return; }
  17065. th_ = std::thread([this] { run(); });
  17066. }
  17067. ~ScopedConnectProxy() {
  17068. stop_ = true;
  17069. if (listen_fd_ >= 0) {
  17070. ::shutdown(listen_fd_, SHUT_RDWR);
  17071. ::close(listen_fd_);
  17072. }
  17073. if (th_.joinable()) { th_.join(); }
  17074. }
  17075. int port() const { return port_; }
  17076. int connect_hits() const { return connect_hits_.load(); }
  17077. private:
  17078. void run() {
  17079. while (!stop_.load()) {
  17080. fd_set rfds;
  17081. FD_ZERO(&rfds);
  17082. FD_SET(listen_fd_, &rfds);
  17083. timeval tv{0, 100 * 1000};
  17084. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17085. if (sel <= 0) { continue; }
  17086. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17087. if (client_fd < 0) { continue; }
  17088. std::string req;
  17089. char buf[2048];
  17090. while (req.find("\r\n\r\n") == std::string::npos) {
  17091. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17092. if (n <= 0) { break; }
  17093. req.append(buf, static_cast<size_t>(n));
  17094. }
  17095. if (req.compare(0, 7, "CONNECT") != 0) {
  17096. ::close(client_fd);
  17097. continue;
  17098. }
  17099. connect_hits_++;
  17100. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17101. ::send(client_fd, ok, std::strlen(ok), 0);
  17102. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17103. sockaddr_in o{};
  17104. o.sin_family = AF_INET;
  17105. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17106. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17107. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17108. 0) {
  17109. ::close(client_fd);
  17110. ::close(origin_fd);
  17111. continue;
  17112. }
  17113. auto forward = [](int from, int to) {
  17114. char b[8192];
  17115. for (;;) {
  17116. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17117. if (n <= 0) { break; }
  17118. ssize_t off = 0;
  17119. while (off < n) {
  17120. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17121. if (s <= 0) {
  17122. off = n;
  17123. break;
  17124. }
  17125. off += s;
  17126. }
  17127. }
  17128. ::shutdown(to, SHUT_WR);
  17129. };
  17130. std::thread t1([&] { forward(client_fd, origin_fd); });
  17131. std::thread t2([&] { forward(origin_fd, client_fd); });
  17132. t1.join();
  17133. t2.join();
  17134. ::close(client_fd);
  17135. ::close(origin_fd);
  17136. }
  17137. }
  17138. int forward_port_ = -1;
  17139. int listen_fd_ = -1;
  17140. int port_ = 0;
  17141. std::thread th_;
  17142. std::atomic<bool> stop_{false};
  17143. std::atomic<int> connect_hits_{0};
  17144. };
  17145. } // namespace proxy_tunnel_test
  17146. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17147. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17148. // retry; otherwise proxy creds would be sent to the origin.
  17149. std::atomic<int> origin_hits{0};
  17150. std::atomic<bool> origin_saw_proxy_authz{false};
  17151. proxy_tunnel_test::ScopedSSLServer origin;
  17152. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17153. origin_hits++;
  17154. if (req.has_header("Proxy-Authorization")) {
  17155. origin_saw_proxy_authz = true;
  17156. }
  17157. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17158. res.set_header("Proxy-Authenticate",
  17159. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17160. "algorithm=MD5");
  17161. });
  17162. origin.listen();
  17163. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17164. ASSERT_NE(0, proxy.port());
  17165. SSLClient cli(HOST, origin.port());
  17166. cli.enable_server_certificate_verification(false);
  17167. cli.set_proxy(HOST, proxy.port());
  17168. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17169. auto res = cli.Get("/x");
  17170. ASSERT_TRUE(res);
  17171. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17172. EXPECT_EQ(1, origin_hits.load());
  17173. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17174. EXPECT_EQ(1, proxy.connect_hits());
  17175. }
  17176. #endif