test.cc 627 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  47. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  48. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  49. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  50. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  51. #ifdef CPPHTTPLIB_SSL_ENABLED
  52. namespace httplib {
  53. namespace tls {
  54. // Declared here for the split build, where the TLS abstraction declarations
  55. // live below the split border; the definition is linked from httplib.cc.
  56. ca_store_t create_ca_store(const char *pem, size_t len);
  57. } // namespace tls
  58. } // namespace httplib
  59. #endif
  60. using namespace std;
  61. using namespace httplib;
  62. const char *HOST = "localhost";
  63. static int get_base_port() {
  64. const char *shard = getenv("GTEST_SHARD_INDEX");
  65. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  66. }
  67. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  68. // New standalone tests MUST use svr.bind_to_any_port() instead.
  69. const int PORT = get_base_port();
  70. const string LONG_QUERY_VALUE = string(25000, '@');
  71. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  72. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  73. const string TOO_LONG_QUERY_URL =
  74. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  75. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  76. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  77. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  78. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  79. return file.name == key;
  80. });
  81. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  82. return *it;
  83. #else
  84. if (it != items.end()) { return *it; }
  85. throw std::runtime_error("invalid multipart form data name error");
  86. #endif
  87. }
  88. static void read_file(const std::string &path, std::string &out) {
  89. std::ifstream fs(path, std::ios_base::binary);
  90. if (!fs) {
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return;
  93. #else
  94. throw std::runtime_error("File not found: " + path);
  95. #endif
  96. }
  97. fs.seekg(0, std::ios_base::end);
  98. auto size = fs.tellg();
  99. fs.seekg(0);
  100. out.resize(static_cast<size_t>(size));
  101. fs.read(&out[0], static_cast<std::streamsize>(size));
  102. }
  103. class UnixSocketTest : public ::testing::Test {
  104. protected:
  105. void TearDown() override { std::remove(pathname_.c_str()); }
  106. void client_GET(const std::string &addr) {
  107. httplib::Client cli{addr};
  108. cli.set_address_family(AF_UNIX);
  109. ASSERT_TRUE(cli.is_valid());
  110. const auto &result = cli.Get(pattern_);
  111. ASSERT_TRUE(result) << "error: " << result.error();
  112. const auto &resp = result.value();
  113. EXPECT_EQ(resp.status, StatusCode::OK_200);
  114. EXPECT_EQ(resp.body, content_);
  115. }
  116. static std::string make_sock_path() {
  117. const char *shard = getenv("GTEST_SHARD_INDEX");
  118. return shard ? std::string("./httplib-server-") + shard + ".sock"
  119. : "./httplib-server.sock";
  120. }
  121. const std::string pathname_{make_sock_path()};
  122. const std::string pattern_{"/hi"};
  123. const std::string content_{"Hello World!"};
  124. };
  125. TEST_F(UnixSocketTest, pathname) {
  126. httplib::Server svr;
  127. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  128. res.set_content(content_, "text/plain");
  129. });
  130. std::thread t{[&] {
  131. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  132. }};
  133. auto se = detail::scope_exit([&] {
  134. svr.stop();
  135. t.join();
  136. ASSERT_FALSE(svr.is_running());
  137. });
  138. svr.wait_until_ready();
  139. ASSERT_TRUE(svr.is_running());
  140. client_GET(pathname_);
  141. }
  142. #if defined(__linux__) || \
  143. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  144. TEST_F(UnixSocketTest, PeerPid) {
  145. httplib::Server svr;
  146. std::string remote_port_val;
  147. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  148. res.set_content(content_, "text/plain");
  149. remote_port_val = std::to_string(req.remote_port);
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  163. }
  164. #endif
  165. #ifdef __linux__
  166. TEST_F(UnixSocketTest, abstract) {
  167. constexpr char svr_path[]{"\x00httplib-server.sock"};
  168. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  169. httplib::Server svr;
  170. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  171. res.set_content(content_, "text/plain");
  172. });
  173. std::thread t{[&] {
  174. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  175. }};
  176. auto se = detail::scope_exit([&] {
  177. svr.stop();
  178. t.join();
  179. ASSERT_FALSE(svr.is_running());
  180. });
  181. svr.wait_until_ready();
  182. ASSERT_TRUE(svr.is_running());
  183. client_GET(abstract_addr);
  184. }
  185. #endif
  186. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  187. httplib::Server svr;
  188. std::string received_host_header;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. // Capture the Host header sent by the client
  191. auto host_iter = req.headers.find("Host");
  192. if (host_iter != req.headers.end()) {
  193. received_host_header = host_iter->second;
  194. }
  195. res.set_content(content_, "text/plain");
  196. });
  197. std::thread t{[&] {
  198. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  199. }};
  200. auto se = detail::scope_exit([&] {
  201. svr.stop();
  202. t.join();
  203. ASSERT_FALSE(svr.is_running());
  204. });
  205. svr.wait_until_ready();
  206. ASSERT_TRUE(svr.is_running());
  207. // Test that Host header is automatically set to "localhost" for Unix socket
  208. // connections
  209. httplib::Client cli{pathname_};
  210. cli.set_address_family(AF_UNIX);
  211. ASSERT_TRUE(cli.is_valid());
  212. const auto &result = cli.Get(pattern_);
  213. ASSERT_TRUE(result) << "error: " << result.error();
  214. const auto &resp = result.value();
  215. EXPECT_EQ(resp.status, StatusCode::OK_200);
  216. EXPECT_EQ(resp.body, content_);
  217. // Verify that Host header was automatically set to "localhost"
  218. EXPECT_EQ(received_host_header, "localhost");
  219. }
  220. #ifndef _WIN32
  221. TEST(SocketStream, wait_writable_UNIX) {
  222. int fds[2];
  223. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  224. const auto asSocketStream = [&](socket_t fd,
  225. std::function<bool(Stream &)> func) {
  226. return detail::process_client_socket(
  227. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  228. };
  229. asSocketStream(fds[0], [&](Stream &s0) {
  230. EXPECT_EQ(s0.socket(), fds[0]);
  231. EXPECT_TRUE(s0.wait_writable());
  232. EXPECT_TRUE(s0.is_peer_alive());
  233. EXPECT_EQ(0, close(fds[1]));
  234. EXPECT_FALSE(s0.is_peer_alive());
  235. return true;
  236. });
  237. EXPECT_EQ(0, close(fds[0]));
  238. }
  239. TEST(SocketStream, wait_writable_INET) {
  240. sockaddr_in addr;
  241. memset(&addr, 0, sizeof(addr));
  242. addr.sin_family = AF_INET;
  243. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  244. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  245. int disconnected_svr_sock = -1;
  246. std::thread svr{[&] {
  247. const int s = socket(AF_INET, SOCK_STREAM, 0);
  248. ASSERT_LE(0, s);
  249. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  250. ASSERT_EQ(0, listen(s, 1));
  251. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  252. ASSERT_EQ(0, close(s));
  253. }};
  254. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  255. std::thread cli{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  259. ASSERT_EQ(0, close(s));
  260. }};
  261. cli.join();
  262. svr.join();
  263. ASSERT_NE(disconnected_svr_sock, -1);
  264. const auto asSocketStream = [&](socket_t fd,
  265. std::function<bool(Stream &)> func) {
  266. return detail::process_client_socket(
  267. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  268. };
  269. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  270. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  271. // wait_writable() returns true because select_write() only checks if the
  272. // send buffer has space. Peer disconnection is detected later by send().
  273. EXPECT_TRUE(ss.wait_writable());
  274. return true;
  275. });
  276. ASSERT_EQ(0, close(disconnected_svr_sock));
  277. }
  278. #endif // #ifndef _WIN32
  279. TEST(SetSocketOptTest, TcpNoDelay) {
  280. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  281. ASSERT_NE(sock, INVALID_SOCKET);
  282. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  283. int val = 0;
  284. socklen_t len = sizeof(val);
  285. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  286. reinterpret_cast<char *>(&val), &len));
  287. EXPECT_NE(val, 0);
  288. detail::close_socket(sock);
  289. }
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. U8("descrip=Gastos áéíóúñÑ 6"));
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(DecodePathTest, UnicodeEncoding) {
  319. // %u0041 = 'A' (1-byte UTF-8)
  320. EXPECT_EQ("A", decode_path_component("%u0041"));
  321. // %u00E9 = 'é' (2-byte UTF-8)
  322. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  323. // %u3042 = 'あ' (3-byte UTF-8)
  324. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  325. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  326. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  327. // %uD800 = surrogate (invalid, silently dropped)
  328. EXPECT_EQ("", decode_path_component("%uD800"));
  329. }
  330. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  331. // A sign or whitespace inside the two-character escape window must not be
  332. // accepted as a valid percent-encoding; the sequence is passed through
  333. // literally, matching decode_uri_component / decode_path_component.
  334. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  335. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  336. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  337. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  338. // Well-formed escapes still decode.
  339. EXPECT_EQ("-", decode_query_component("%2D", false));
  340. EXPECT_EQ("A", decode_query_component("%41", false));
  341. }
  342. TEST(SanitizeFilenameTest, VariousPatterns) {
  343. // Path traversal
  344. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  345. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  346. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  347. // Normal and edge cases
  348. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  349. EXPECT_EQ("filename.txt",
  350. httplib::sanitize_filename("/path/to/filename.txt"));
  351. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  352. EXPECT_EQ("", httplib::sanitize_filename(".."));
  353. EXPECT_EQ("", httplib::sanitize_filename(""));
  354. // Null bytes stripped
  355. EXPECT_EQ("safe.txt",
  356. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  357. // Whitespace-only rejected
  358. EXPECT_EQ("", httplib::sanitize_filename(" "));
  359. }
  360. // Forward declaration: in split builds split.py strips `inline` and moves the
  361. // definition into httplib.cc, so detail::base64_encode is not visible from the
  362. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  363. // in both header-only and split builds.
  364. namespace httplib {
  365. namespace detail {
  366. std::string base64_encode(const std::string &in);
  367. } // namespace detail
  368. } // namespace httplib
  369. TEST(Base64EncodeTest, KnownAnswers) {
  370. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  371. // where the accumulator's top bit is already set before the next shift.
  372. EXPECT_EQ("", detail::base64_encode(""));
  373. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  374. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  375. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  376. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  377. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  378. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  379. // High bytes keep the top bit set across several rounds.
  380. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  381. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  382. }
  383. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  384. string unescapedCharacters = "-_.!~*'()";
  385. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  386. }
  387. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  388. string reservedCharacters = ";,/?:@&=+$";
  389. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  390. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  391. }
  392. TEST(ClientQueryOrder, PreserveOrder) {
  393. // This test reproduces Issue #2259: client may reorder query parameters
  394. // when sending a GET request. The expected behavior is that the client
  395. // preserves the original query string order when the caller supplied it
  396. // as part of the path.
  397. Server svr;
  398. svr.Get("/", [&](const Request &req, Response &res) {
  399. // Echo back the raw target so the test can assert ordering
  400. res.set_content(req.target, "text/plain");
  401. });
  402. std::thread t{[&] { svr.listen(HOST, PORT); }};
  403. auto se = detail::scope_exit([&] {
  404. svr.stop();
  405. t.join();
  406. ASSERT_FALSE(svr.is_running());
  407. });
  408. svr.wait_until_ready();
  409. Client cli(HOST, PORT);
  410. ASSERT_TRUE(cli.is_valid());
  411. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  412. auto res = cli.Get(original);
  413. ASSERT_TRUE(res);
  414. // Expect the echoed target to exactly match the original path (order
  415. // preserved)
  416. EXPECT_EQ(res->body, original);
  417. }
  418. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  425. "%D0%B4%D0%BE%D0%BC");
  426. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  427. }
  428. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  429. string unescapedCharacters = "-_.!~*'()";
  430. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  431. }
  432. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  433. string reservedCharacters = ";,/?:@&=+$";
  434. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  435. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  436. }
  437. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  438. string chineseCharacters = U8("中国語");
  439. string russianCharacters = U8("дом");
  440. string brazilianCharacters = U8("óculos");
  441. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  442. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  443. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  444. "%D0%B4%D0%BE%D0%BC");
  445. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  446. }
  447. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  448. // Issue #2082 use case: encoding path component with ampersand
  449. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  450. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  451. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  452. }
  453. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  454. string unescapedCharacters = "-_.!~*'()";
  455. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  456. }
  457. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  458. string reservedCharacters = ";,/?:@&=+$#";
  459. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  460. }
  461. TEST(EncodeUriTest, TestUTF8Characters) {
  462. string chineseCharacters = U8("中国語");
  463. string russianCharacters = U8("дом");
  464. string brazilianCharacters = U8("óculos");
  465. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  466. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  467. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  468. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  469. }
  470. TEST(EncodeUriTest, TestCompleteUri) {
  471. string uri =
  472. "https://example.com/path/to/resource?query=value&param=test#fragment";
  473. EXPECT_EQ(
  474. httplib::encode_uri(uri),
  475. "https://example.com/path/to/resource?query=value&param=test#fragment");
  476. }
  477. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  478. string uri =
  479. "https://example.com/path with spaces/file name.html?q=hello world";
  480. EXPECT_EQ(httplib::encode_uri(uri),
  481. "https://example.com/path%20with%20spaces/"
  482. "file%20name.html?q=hello%20world");
  483. }
  484. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  485. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  487. }
  488. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  489. string unescapedCharacters = "-_.!~*'()";
  490. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  491. }
  492. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  493. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  494. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  495. string encodedBrazilian = "%C3%B3culos";
  496. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  497. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  498. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  499. }
  500. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  501. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  502. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  503. "Piri Tommy Villiers - on & on");
  504. }
  505. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  506. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  507. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  508. }
  509. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  510. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  511. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  512. }
  513. TEST(DecodeUriTest, TestUTF8Characters) {
  514. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  515. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  516. string encodedBrazilian = "%C3%B3culos";
  517. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  518. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  519. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  520. }
  521. TEST(DecodeUriTest, TestCompleteUri) {
  522. string encodedUri = "https://example.com/path%20with%20spaces/"
  523. "file%20name.html?q=hello%20world";
  524. EXPECT_EQ(
  525. httplib::decode_uri(encodedUri),
  526. "https://example.com/path with spaces/file name.html?q=hello world");
  527. }
  528. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  529. string original =
  530. "https://example.com/path with spaces/file name.html?q=hello world";
  531. string encoded = httplib::encode_uri(original);
  532. string decoded = httplib::decode_uri(encoded);
  533. EXPECT_EQ(decoded, original);
  534. }
  535. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  536. string original = "Piri Tommy Villiers - on & on";
  537. string encoded = httplib::encode_uri_component(original);
  538. string decoded = httplib::decode_uri_component(encoded);
  539. EXPECT_EQ(decoded, original);
  540. }
  541. TEST(TrimTests, TrimStringTests) {
  542. EXPECT_EQ("abc", detail::trim_copy("abc"));
  543. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  544. EXPECT_TRUE(detail::trim_copy("").empty());
  545. }
  546. TEST(AsciiTest, LocaleIndependentClassification) {
  547. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  548. // which consult the global C locale: std::isalnum(0xC5) can return true
  549. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  550. // helpers must classify every byte by the ASCII grammar alone.
  551. for (int i = 0; i < 256; i++) {
  552. auto c = static_cast<char>(i);
  553. auto is_digit = i >= '0' && i <= '9';
  554. auto is_upper = i >= 'A' && i <= 'Z';
  555. auto is_lower = i >= 'a' && i <= 'z';
  556. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  557. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  558. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  559. << "byte " << i;
  560. }
  561. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  562. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  563. // Non-ASCII bytes must be percent-encoded, never passed through as
  564. // alphanumeric.
  565. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  566. }
  567. TEST(FromCharsTest, Double) {
  568. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  569. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  570. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  571. auto parse = [](const std::string &s, double &v) {
  572. return detail::from_chars(s.data(), s.data() + s.size(), v);
  573. };
  574. double v = -1.0;
  575. // Representative quality values.
  576. EXPECT_EQ(parse("0", v).ec, std::errc{});
  577. EXPECT_DOUBLE_EQ(v, 0.0);
  578. EXPECT_EQ(parse("1", v).ec, std::errc{});
  579. EXPECT_DOUBLE_EQ(v, 1.0);
  580. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  581. EXPECT_DOUBLE_EQ(v, 0.8);
  582. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  583. EXPECT_DOUBLE_EQ(v, 0.001);
  584. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  585. EXPECT_DOUBLE_EQ(v, 1.0);
  586. // A missing integer or fractional part is tolerated.
  587. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  588. EXPECT_DOUBLE_EQ(v, 0.5);
  589. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  590. EXPECT_DOUBLE_EQ(v, 5.0);
  591. // Values outside [0, 1] still parse; the caller range-checks them.
  592. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  593. EXPECT_DOUBLE_EQ(v, 123.456);
  594. // Stops at the first byte that is not part of the number and reports where.
  595. std::string trailing = "0.9, text/html";
  596. auto r = parse(trailing, v);
  597. EXPECT_EQ(r.ec, std::errc{});
  598. EXPECT_DOUBLE_EQ(v, 0.9);
  599. EXPECT_EQ(*r.ptr, ',');
  600. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  601. // outright, and an 'e'/'E' simply ends the number.
  602. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  603. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  604. std::string exp_input = "1.5e3";
  605. r = parse(exp_input, v);
  606. EXPECT_EQ(r.ec, std::errc{});
  607. EXPECT_DOUBLE_EQ(v, 1.5);
  608. EXPECT_EQ(*r.ptr, 'e');
  609. // Invalid inputs.
  610. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  611. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  612. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  613. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  614. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  615. // Pathological but well-formed inputs must stay bounded (no overflow, no
  616. // out-of-bounds table access) and stay within [0, 1] for the caller.
  617. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  618. std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.0);
  620. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  621. std::errc{});
  622. EXPECT_GE(v, 0.0);
  623. EXPECT_LE(v, 1.0);
  624. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  625. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  626. }
  627. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  628. // Simple case without quality values
  629. std::vector<std::string> result1;
  630. EXPECT_TRUE(detail::parse_accept_header(
  631. "text/html,application/json,text/plain", result1));
  632. EXPECT_EQ(result1.size(), 3U);
  633. EXPECT_EQ(result1[0], "text/html");
  634. EXPECT_EQ(result1[1], "application/json");
  635. EXPECT_EQ(result1[2], "text/plain");
  636. // With quality values
  637. std::vector<std::string> result2;
  638. EXPECT_TRUE(detail::parse_accept_header(
  639. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  640. EXPECT_EQ(result2.size(), 3U);
  641. EXPECT_EQ(result2[0], "application/json"); // highest q value
  642. EXPECT_EQ(result2[1], "text/html");
  643. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  644. }
  645. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  646. // Mixed with and without quality values
  647. std::vector<std::string> result;
  648. EXPECT_TRUE(detail::parse_accept_header(
  649. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  650. EXPECT_EQ(result.size(), 3U);
  651. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  652. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  653. EXPECT_EQ(result[2], "application/json"); // q=0.5
  654. }
  655. TEST(ParseAcceptHeaderTest, EdgeCases) {
  656. // Empty header
  657. std::vector<std::string> empty_result;
  658. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  659. EXPECT_TRUE(empty_result.empty());
  660. // Single type
  661. std::vector<std::string> single_result;
  662. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  663. EXPECT_EQ(single_result.size(), 1U);
  664. EXPECT_EQ(single_result[0], "application/json");
  665. // Wildcard types
  666. std::vector<std::string> wildcard_result;
  667. EXPECT_TRUE(detail::parse_accept_header(
  668. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  669. EXPECT_EQ(wildcard_result.size(), 3U);
  670. EXPECT_EQ(wildcard_result[0], "application/json");
  671. EXPECT_EQ(wildcard_result[1], "text/*");
  672. EXPECT_EQ(wildcard_result[2], "*/*");
  673. }
  674. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  675. // Common browser Accept header
  676. std::vector<std::string> browser_result;
  677. EXPECT_TRUE(
  678. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  679. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  680. browser_result));
  681. EXPECT_EQ(browser_result.size(), 6U);
  682. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  683. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  684. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  685. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  686. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  687. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  688. // API client header
  689. std::vector<std::string> api_result;
  690. EXPECT_TRUE(detail::parse_accept_header(
  691. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  692. api_result));
  693. EXPECT_EQ(api_result.size(), 3U);
  694. EXPECT_EQ(api_result[0], "application/json");
  695. EXPECT_EQ(api_result[1], "application/xml");
  696. EXPECT_EQ(api_result[2], "text/plain");
  697. }
  698. TEST(ParseAcceptHeaderTest, SpecialCases) {
  699. // Quality value with 3 decimal places
  700. std::vector<std::string> decimal_result;
  701. EXPECT_TRUE(detail::parse_accept_header(
  702. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  703. EXPECT_EQ(decimal_result.size(), 2U);
  704. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  705. EXPECT_EQ(decimal_result[1], "text/html");
  706. // Zero quality (should still be included but with lowest priority)
  707. std::vector<std::string> zero_q_result;
  708. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  709. zero_q_result));
  710. EXPECT_EQ(zero_q_result.size(), 2U);
  711. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  712. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  713. // No spaces around commas
  714. std::vector<std::string> no_space_result;
  715. EXPECT_TRUE(detail::parse_accept_header(
  716. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  717. no_space_result));
  718. EXPECT_EQ(no_space_result.size(), 3U);
  719. EXPECT_EQ(no_space_result[0], "text/html");
  720. EXPECT_EQ(no_space_result[1], "application/json");
  721. EXPECT_EQ(no_space_result[2], "text/plain");
  722. }
  723. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  724. // Quality values always use '.' as the decimal separator, so parsing must
  725. // not depend on the process locale. An embedding application may have
  726. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  727. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  728. std::string saved = cur ? cur : "C";
  729. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  730. "fr_FR.UTF-8"};
  731. bool switched = false;
  732. for (const auto loc : comma_locales) {
  733. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  734. std::localeconv()->decimal_point[0] == ',') {
  735. switched = true;
  736. break;
  737. }
  738. }
  739. if (!switched) {
  740. std::setlocale(LC_NUMERIC, saved.c_str());
  741. GTEST_SKIP() << "no comma-decimal locale available on this host";
  742. }
  743. // The higher-weighted type appears later in the list, so a correct parse
  744. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  745. // sensitive parse reads both weights as 0 and leaves the original order.
  746. std::vector<std::string> result;
  747. EXPECT_TRUE(detail::parse_accept_header(
  748. "application/json;q=0.1,text/html;q=0.9", result));
  749. ASSERT_EQ(result.size(), 2U);
  750. EXPECT_EQ(result[0], "text/html");
  751. EXPECT_EQ(result[1], "application/json");
  752. std::setlocale(LC_NUMERIC, saved.c_str());
  753. }
  754. TEST(ParseAcceptHeaderTest, InvalidCases) {
  755. std::vector<std::string> result;
  756. // Invalid quality value (> 1.0)
  757. EXPECT_FALSE(
  758. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  759. // Invalid quality value (< 0.0)
  760. EXPECT_FALSE(
  761. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  762. // Invalid quality value (not a number)
  763. EXPECT_FALSE(detail::parse_accept_header(
  764. "text/html;q=invalid,application/json", result));
  765. // Empty quality value
  766. EXPECT_FALSE(
  767. detail::parse_accept_header("text/html;q=,application/json", result));
  768. // Invalid media type format (no slash and not wildcard)
  769. EXPECT_FALSE(
  770. detail::parse_accept_header("invalidtype,application/json", result));
  771. // Empty media type
  772. result.clear();
  773. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  774. // Only commas
  775. result.clear();
  776. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  777. // Valid cases should still work
  778. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  779. EXPECT_EQ(result.size(), 1U);
  780. EXPECT_EQ(result[0], "*/*");
  781. EXPECT_TRUE(detail::parse_accept_header("*", result));
  782. EXPECT_EQ(result.size(), 1U);
  783. EXPECT_EQ(result[0], "*");
  784. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  785. EXPECT_EQ(result.size(), 1U);
  786. EXPECT_EQ(result[0], "text/*");
  787. }
  788. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  789. Server svr;
  790. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  791. EXPECT_EQ(req.accept_content_types.size(), 3U);
  792. EXPECT_EQ(req.accept_content_types[0], "application/json");
  793. EXPECT_EQ(req.accept_content_types[1], "text/html");
  794. EXPECT_EQ(req.accept_content_types[2], "*/*");
  795. res.set_content("ok", "text/plain");
  796. });
  797. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  798. EXPECT_TRUE(false);
  799. res.set_content("bad request", "text/plain");
  800. });
  801. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  802. auto se = detail::scope_exit([&] {
  803. svr.stop();
  804. listen_thread.join();
  805. ASSERT_FALSE(svr.is_running());
  806. });
  807. svr.wait_until_ready();
  808. Client cli("localhost", PORT);
  809. {
  810. auto res = cli.Get(
  811. "/accept_ok",
  812. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  813. ASSERT_TRUE(res);
  814. EXPECT_EQ(StatusCode::OK_200, res->status);
  815. }
  816. {
  817. auto res = cli.Get("/accept_bad_request",
  818. Headers{{"Accept", "text/html;q=abc,application/json"}});
  819. ASSERT_TRUE(res);
  820. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  821. }
  822. }
  823. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  824. Server svr;
  825. svr.Get("/", [](const Request & /*req*/, Response &res) {
  826. res.set_content("ok", "text/plain");
  827. });
  828. std::atomic<int> start_count{0};
  829. std::atomic<bool> running_when_called{false};
  830. svr.set_start_handler([&]() {
  831. running_when_called = svr.is_running();
  832. start_count++;
  833. });
  834. auto port = svr.bind_to_any_port(HOST);
  835. std::thread t([&]() { svr.listen_after_bind(); });
  836. auto se = detail::scope_exit([&] {
  837. svr.stop();
  838. t.join();
  839. ASSERT_FALSE(svr.is_running());
  840. });
  841. svr.wait_until_ready();
  842. // A successful request proves the accept loop is running, which the start
  843. // handler precedes; so by now the handler must have run exactly once.
  844. Client cli(HOST, port);
  845. cli.set_connection_timeout(std::chrono::seconds(5));
  846. auto res = cli.Get("/");
  847. ASSERT_TRUE(res);
  848. EXPECT_EQ(StatusCode::OK_200, res->status);
  849. EXPECT_EQ(1, start_count.load());
  850. EXPECT_TRUE(running_when_called.load());
  851. }
  852. TEST(DivideTest, DivideStringTests) {
  853. auto divide = [](const std::string &str, char d) {
  854. std::string lhs;
  855. std::string rhs;
  856. detail::divide(str, d,
  857. [&](const char *lhs_data, std::size_t lhs_size,
  858. const char *rhs_data, std::size_t rhs_size) {
  859. lhs.assign(lhs_data, lhs_size);
  860. rhs.assign(rhs_data, rhs_size);
  861. });
  862. return std::make_pair(std::move(lhs), std::move(rhs));
  863. };
  864. {
  865. const auto res = divide("", '=');
  866. EXPECT_EQ(res.first, "");
  867. EXPECT_EQ(res.second, "");
  868. }
  869. {
  870. const auto res = divide("=", '=');
  871. EXPECT_EQ(res.first, "");
  872. EXPECT_EQ(res.second, "");
  873. }
  874. {
  875. const auto res = divide(" ", '=');
  876. EXPECT_EQ(res.first, " ");
  877. EXPECT_EQ(res.second, "");
  878. }
  879. {
  880. const auto res = divide("a", '=');
  881. EXPECT_EQ(res.first, "a");
  882. EXPECT_EQ(res.second, "");
  883. }
  884. {
  885. const auto res = divide("a=", '=');
  886. EXPECT_EQ(res.first, "a");
  887. EXPECT_EQ(res.second, "");
  888. }
  889. {
  890. const auto res = divide("=b", '=');
  891. EXPECT_EQ(res.first, "");
  892. EXPECT_EQ(res.second, "b");
  893. }
  894. {
  895. const auto res = divide("a=b", '=');
  896. EXPECT_EQ(res.first, "a");
  897. EXPECT_EQ(res.second, "b");
  898. }
  899. {
  900. const auto res = divide("a=b=", '=');
  901. EXPECT_EQ(res.first, "a");
  902. EXPECT_EQ(res.second, "b=");
  903. }
  904. {
  905. const auto res = divide("a=b=c", '=');
  906. EXPECT_EQ(res.first, "a");
  907. EXPECT_EQ(res.second, "b=c");
  908. }
  909. }
  910. TEST(SplitTest, ParseQueryString) {
  911. string s = "key1=val1&key2=val2&key3=val3";
  912. Params dic;
  913. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  914. [&](const char *b, const char *e) {
  915. string key, val;
  916. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  917. if (key.empty()) {
  918. key.assign(b2, e2);
  919. } else {
  920. val.assign(b2, e2);
  921. }
  922. });
  923. dic.emplace(key, val);
  924. });
  925. EXPECT_EQ("val1", dic.find("key1")->second);
  926. EXPECT_EQ("val2", dic.find("key2")->second);
  927. EXPECT_EQ("val3", dic.find("key3")->second);
  928. }
  929. TEST(SplitTest, ParseInvalidQueryTests) {
  930. {
  931. string s = " ";
  932. Params dict;
  933. detail::parse_query_text(s, dict);
  934. EXPECT_TRUE(dict.empty());
  935. }
  936. {
  937. string s = " = =";
  938. Params dict;
  939. detail::parse_query_text(s, dict);
  940. EXPECT_TRUE(dict.empty());
  941. }
  942. }
  943. TEST(ParseQueryTest, ParseQueryString) {
  944. {
  945. std::string s = "key1=val1&key2=val2&key3=val3";
  946. Params dic;
  947. detail::parse_query_text(s, dic);
  948. EXPECT_EQ("val1", dic.find("key1")->second);
  949. EXPECT_EQ("val2", dic.find("key2")->second);
  950. EXPECT_EQ("val3", dic.find("key3")->second);
  951. }
  952. {
  953. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  954. Params dic;
  955. detail::parse_query_text(s, dic);
  956. EXPECT_EQ("", dic.find("key1")->second);
  957. EXPECT_EQ("val1", dic.find("key2")->second);
  958. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  959. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  960. }
  961. }
  962. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  963. Params dic;
  964. EXPECT_EQ(detail::params_to_query_str(dic), "");
  965. dic.emplace("key1", "val1");
  966. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  967. dic.emplace("key2", "val2");
  968. dic.emplace("key3", "val3");
  969. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  970. }
  971. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  972. string content_type = "multipart/form-data; boundary=something";
  973. string boundary;
  974. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  975. EXPECT_TRUE(ret);
  976. EXPECT_EQ(boundary, "something");
  977. }
  978. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  979. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  980. string boundary;
  981. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  982. EXPECT_TRUE(ret);
  983. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  984. }
  985. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  986. string content_type =
  987. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  988. string boundary;
  989. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  990. EXPECT_TRUE(ret);
  991. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  992. }
  993. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  994. string content_type =
  995. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  996. string boundary;
  997. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  998. EXPECT_TRUE(ret);
  999. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1000. }
  1001. TEST(GetHeaderValueTest, DefaultValue) {
  1002. Headers headers = {{"Dummy", "Dummy"}};
  1003. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1004. EXPECT_STREQ("text/plain", val);
  1005. }
  1006. TEST(GetHeaderValueTest, DefaultValueInt) {
  1007. Headers headers = {{"Dummy", "Dummy"}};
  1008. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1009. EXPECT_EQ(100ull, val);
  1010. }
  1011. TEST(GetHeaderValueTest, RegularValue) {
  1012. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1013. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1014. EXPECT_STREQ("text/html", val);
  1015. }
  1016. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1017. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1018. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1019. EXPECT_STREQ("text/html", val);
  1020. }
  1021. TEST(GetHeaderValueTest, SetContent) {
  1022. Response res;
  1023. res.set_content("html", "text/html");
  1024. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1025. res.set_content("text", "text/plain");
  1026. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1027. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1028. }
  1029. TEST(GetHeaderValueTest, RegularValueInt) {
  1030. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1031. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1032. EXPECT_EQ(100ull, val);
  1033. }
  1034. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1035. Headers headers = {{"Content-Length", "x"}};
  1036. auto is_invalid_value = false;
  1037. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1038. is_invalid_value);
  1039. EXPECT_EQ(0ull, val);
  1040. EXPECT_TRUE(is_invalid_value);
  1041. }
  1042. TEST(GetHeaderValueTest, Range) {
  1043. {
  1044. Headers headers = {make_range_header({{1, -1}})};
  1045. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1046. EXPECT_STREQ("bytes=1-", val);
  1047. }
  1048. {
  1049. Headers headers = {make_range_header({{-1, 1}})};
  1050. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1051. EXPECT_STREQ("bytes=-1", val);
  1052. }
  1053. {
  1054. Headers headers = {make_range_header({{1, 10}})};
  1055. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1056. EXPECT_STREQ("bytes=1-10", val);
  1057. }
  1058. {
  1059. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1060. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1061. EXPECT_STREQ("bytes=1-10, 100-", val);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1065. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1066. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1067. }
  1068. {
  1069. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1070. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1071. EXPECT_STREQ("bytes=0-0, -1", val);
  1072. }
  1073. }
  1074. TEST(ParseHeaderValueTest, Range) {
  1075. {
  1076. Ranges ranges;
  1077. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1078. EXPECT_TRUE(ret);
  1079. EXPECT_EQ(1u, ranges.size());
  1080. EXPECT_EQ(1u, ranges[0].first);
  1081. EXPECT_EQ(-1, ranges[0].second);
  1082. }
  1083. {
  1084. Ranges ranges;
  1085. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1086. EXPECT_TRUE(ret);
  1087. EXPECT_EQ(1u, ranges.size());
  1088. EXPECT_EQ(-1, ranges[0].first);
  1089. EXPECT_EQ(1u, ranges[0].second);
  1090. }
  1091. {
  1092. Ranges ranges;
  1093. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1094. EXPECT_TRUE(ret);
  1095. EXPECT_EQ(1u, ranges.size());
  1096. EXPECT_EQ(1u, ranges[0].first);
  1097. EXPECT_EQ(10u, ranges[0].second);
  1098. }
  1099. {
  1100. Ranges ranges;
  1101. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1102. EXPECT_FALSE(ret);
  1103. }
  1104. {
  1105. Ranges ranges;
  1106. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1107. EXPECT_TRUE(ret);
  1108. EXPECT_EQ(2u, ranges.size());
  1109. EXPECT_EQ(1u, ranges[0].first);
  1110. EXPECT_EQ(10u, ranges[0].second);
  1111. EXPECT_EQ(100u, ranges[1].first);
  1112. EXPECT_EQ(-1, ranges[1].second);
  1113. }
  1114. {
  1115. Ranges ranges;
  1116. auto ret =
  1117. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1118. EXPECT_TRUE(ret);
  1119. EXPECT_EQ(3u, ranges.size());
  1120. EXPECT_EQ(1u, ranges[0].first);
  1121. EXPECT_EQ(10u, ranges[0].second);
  1122. EXPECT_EQ(100u, ranges[1].first);
  1123. EXPECT_EQ(200u, ranges[1].second);
  1124. EXPECT_EQ(300u, ranges[2].first);
  1125. EXPECT_EQ(400u, ranges[2].second);
  1126. }
  1127. {
  1128. Ranges ranges;
  1129. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1130. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1131. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1132. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1133. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1134. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1135. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1136. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1137. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1138. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1139. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1140. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1141. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1142. EXPECT_TRUE(ranges.empty());
  1143. }
  1144. }
  1145. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1146. Request req;
  1147. req.set_header("Accept-Encoding", "gzip");
  1148. Response res;
  1149. res.set_header("Content-Type", "text/plain");
  1150. auto ret = detail::encoding_type(req, res);
  1151. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1152. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1153. #else
  1154. EXPECT_TRUE(ret == detail::EncodingType::None);
  1155. #endif
  1156. }
  1157. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1158. Request req;
  1159. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1160. Response res;
  1161. res.set_header("Content-Type", "text/plain");
  1162. auto ret = detail::encoding_type(req, res);
  1163. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1164. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1165. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1166. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1167. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1168. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1169. #else
  1170. EXPECT_TRUE(ret == detail::EncodingType::None);
  1171. #endif
  1172. }
  1173. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1174. Request req;
  1175. req.set_header("Accept-Encoding",
  1176. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1177. Response res;
  1178. res.set_header("Content-Type", "text/plain");
  1179. auto ret = detail::encoding_type(req, res);
  1180. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1181. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1182. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1183. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1184. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1185. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1186. #else
  1187. EXPECT_TRUE(ret == detail::EncodingType::None);
  1188. #endif
  1189. }
  1190. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1191. // All supported encodings rejected with q=0 should return None
  1192. Request req;
  1193. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1194. Response res;
  1195. res.set_header("Content-Type", "text/plain");
  1196. auto ret = detail::encoding_type(req, res);
  1197. EXPECT_TRUE(ret == detail::EncodingType::None);
  1198. }
  1199. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1200. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1201. Request req;
  1202. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1203. Response res;
  1204. res.set_header("Content-Type", "text/plain");
  1205. auto ret = detail::encoding_type(req, res);
  1206. EXPECT_TRUE(ret == detail::EncodingType::None);
  1207. }
  1208. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1209. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1210. Request req;
  1211. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1212. Response res;
  1213. res.set_header("Content-Type", "text/plain");
  1214. auto ret = detail::encoding_type(req, res);
  1215. EXPECT_TRUE(ret == detail::EncodingType::None);
  1216. }
  1217. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1218. // RFC 7231: Accept-Encoding values are case-insensitive
  1219. Request req;
  1220. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1221. Response res;
  1222. res.set_header("Content-Type", "text/plain");
  1223. auto ret = detail::encoding_type(req, res);
  1224. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1225. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1226. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1227. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1228. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1229. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1230. #else
  1231. EXPECT_TRUE(ret == detail::EncodingType::None);
  1232. #endif
  1233. }
  1234. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1235. // q value should determine priority, not hardcoded order
  1236. Request req;
  1237. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1238. Response res;
  1239. res.set_header("Content-Type", "text/plain");
  1240. auto ret = detail::encoding_type(req, res);
  1241. // gzip has highest q=1.0, so it should be selected even though
  1242. // br and zstd are also supported
  1243. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1244. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1245. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1246. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1247. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1248. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1249. #else
  1250. EXPECT_TRUE(ret == detail::EncodingType::None);
  1251. #endif
  1252. }
  1253. TEST(BufferStreamTest, read) {
  1254. detail::BufferStream strm1;
  1255. Stream &strm = strm1;
  1256. EXPECT_EQ(5, strm.write("hello"));
  1257. char buf[512];
  1258. EXPECT_EQ(2, strm.read(buf, 2));
  1259. EXPECT_EQ('h', buf[0]);
  1260. EXPECT_EQ('e', buf[1]);
  1261. EXPECT_EQ(2, strm.read(buf, 2));
  1262. EXPECT_EQ('l', buf[0]);
  1263. EXPECT_EQ('l', buf[1]);
  1264. EXPECT_EQ(1, strm.read(buf, 1));
  1265. EXPECT_EQ('o', buf[0]);
  1266. EXPECT_EQ(0, strm.read(buf, 1));
  1267. }
  1268. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1269. auto host = "www.httpwatch.com";
  1270. auto ip = hosted_at(host);
  1271. EXPECT_EQ("23.96.13.243", ip);
  1272. std::vector<std::string> addrs;
  1273. hosted_at(host, addrs);
  1274. EXPECT_EQ(1u, addrs.size());
  1275. }
  1276. #if 0 // It depends on each test environment...
  1277. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1278. auto host = "www.youtube.com";
  1279. std::vector<std::string> addrs;
  1280. hosted_at(host, addrs);
  1281. EXPECT_EQ(20u, addrs.size());
  1282. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1283. EXPECT_TRUE(it != addrs.end());
  1284. }
  1285. #endif
  1286. class ChunkedEncodingTest : public ::testing::Test {
  1287. protected:
  1288. ChunkedEncodingTest()
  1289. : cli_(HOST, PORT)
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. ,
  1292. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1293. #endif
  1294. {
  1295. cli_.set_connection_timeout(2);
  1296. #ifdef CPPHTTPLIB_SSL_ENABLED
  1297. cli_.enable_server_certificate_verification(false);
  1298. #endif
  1299. }
  1300. virtual void SetUp() {
  1301. read_file("./image.jpg", image_data_);
  1302. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1303. res.set_content("Hello World!", "text/plain");
  1304. });
  1305. svr_.Get(
  1306. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1307. res.set_chunked_content_provider(
  1308. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1309. size_t remaining = image_data_.size() - offset;
  1310. if (remaining == 0) {
  1311. sink.done();
  1312. } else {
  1313. constexpr size_t CHUNK_SIZE = 1024;
  1314. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1315. sink.write(&image_data_[offset], send_size);
  1316. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1317. }
  1318. return true;
  1319. });
  1320. });
  1321. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1322. svr_.wait_until_ready();
  1323. }
  1324. virtual void TearDown() {
  1325. svr_.stop();
  1326. if (!request_threads_.empty()) {
  1327. std::this_thread::sleep_for(std::chrono::seconds(1));
  1328. for (auto &t : request_threads_) {
  1329. t.join();
  1330. }
  1331. }
  1332. t_.join();
  1333. }
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. SSLClient cli_;
  1336. SSLServer svr_;
  1337. #else
  1338. Client cli_;
  1339. Server svr_;
  1340. #endif
  1341. thread t_;
  1342. std::vector<thread> request_threads_;
  1343. std::string image_data_;
  1344. };
  1345. TEST_F(ChunkedEncodingTest, NormalGet) {
  1346. auto res = cli_.Get("/chunked");
  1347. ASSERT_TRUE(res);
  1348. std::string out;
  1349. read_file("./image.jpg", out);
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. EXPECT_EQ(out, res->body);
  1352. }
  1353. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1354. std::string body;
  1355. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1356. body.append(data, data_length);
  1357. return true;
  1358. });
  1359. ASSERT_TRUE(res);
  1360. std::string out;
  1361. read_file("./image.jpg", out);
  1362. EXPECT_EQ(StatusCode::OK_200, res->status);
  1363. EXPECT_EQ(out, body);
  1364. }
  1365. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1366. std::string body;
  1367. auto res = cli_.Get(
  1368. "/chunked",
  1369. [&](const Response &response) {
  1370. EXPECT_EQ(StatusCode::OK_200, response.status);
  1371. return true;
  1372. },
  1373. [&](const char *data, size_t data_length) {
  1374. body.append(data, data_length);
  1375. return true;
  1376. });
  1377. ASSERT_TRUE(res);
  1378. std::string out;
  1379. read_file("./image.jpg", out);
  1380. EXPECT_EQ(StatusCode::OK_200, res->status);
  1381. EXPECT_EQ(out, body);
  1382. }
  1383. TEST(RangeTest, FromHTTPBin_Online) {
  1384. auto host = "httpbingo.org";
  1385. auto path = std::string{"/range/32"};
  1386. #ifdef CPPHTTPLIB_SSL_ENABLED
  1387. auto port = 443;
  1388. SSLClient cli(host, port);
  1389. #else
  1390. auto port = 80;
  1391. Client cli(host, port);
  1392. #endif
  1393. cli.set_connection_timeout(5);
  1394. {
  1395. auto res = cli.Get(path);
  1396. ASSERT_TRUE(res);
  1397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1398. EXPECT_EQ(StatusCode::OK_200, res->status);
  1399. }
  1400. {
  1401. Headers headers = {make_range_header({{1, -1}})};
  1402. auto res = cli.Get(path, headers);
  1403. ASSERT_TRUE(res);
  1404. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1406. }
  1407. {
  1408. Headers headers = {make_range_header({{1, 10}})};
  1409. auto res = cli.Get(path, headers);
  1410. ASSERT_TRUE(res);
  1411. EXPECT_EQ("bcdefghijk", res->body);
  1412. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1413. }
  1414. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1415. // entire resource, while the original httpbin returned 200. Both are
  1416. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1417. {
  1418. Headers headers = {make_range_header({{0, 31}})};
  1419. auto res = cli.Get(path, headers);
  1420. ASSERT_TRUE(res);
  1421. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1422. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1423. res->status == StatusCode::PartialContent_206);
  1424. }
  1425. {
  1426. Headers headers = {make_range_header({{0, -1}})};
  1427. auto res = cli.Get(path, headers);
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1430. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1431. res->status == StatusCode::PartialContent_206);
  1432. }
  1433. // go-httpbin returns 206 with clamped range for over-range requests,
  1434. // while the original httpbin returned 416. Both behaviors are observed
  1435. // in real servers, so we only verify the request succeeds.
  1436. {
  1437. Headers headers = {make_range_header({{0, 32}})};
  1438. auto res = cli.Get(path, headers);
  1439. ASSERT_TRUE(res);
  1440. }
  1441. }
  1442. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1443. auto host = "unresolvableaddress.local";
  1444. auto path = std::string{"/"};
  1445. #ifdef CPPHTTPLIB_SSL_ENABLED
  1446. auto port = 443;
  1447. SSLClient cli(host, port);
  1448. #else
  1449. auto port = 80;
  1450. Client cli(host, port);
  1451. #endif
  1452. cli.set_connection_timeout(1);
  1453. {
  1454. auto res = cli.Get(path);
  1455. ASSERT_FALSE(res);
  1456. }
  1457. std::this_thread::sleep_for(std::chrono::seconds(8));
  1458. }
  1459. #if defined(__linux__) && defined(__GLIBC__) && \
  1460. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1461. // Forward declaration: in split builds split.py strips `inline` and moves the
  1462. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1463. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1464. // against the symbol in both header-only and split builds.
  1465. namespace httplib {
  1466. namespace detail {
  1467. int getaddrinfo_with_timeout(const char *node, const char *service,
  1468. const struct addrinfo *hints,
  1469. struct addrinfo **res, time_t timeout_sec);
  1470. } // namespace detail
  1471. } // namespace httplib
  1472. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1473. //
  1474. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1475. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1476. // gai_suspend() call hits the connection timeout the function calls
  1477. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1478. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1479. // still alive and still references the now-destroyed stack frame.
  1480. //
  1481. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1482. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1483. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1484. // and runs them in a container.
  1485. namespace {
  1486. bool should_run_issue_2431_tests() {
  1487. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1488. return v && *v && std::string(v) != "0";
  1489. }
  1490. std::string unique_unresolvable_host(int n) {
  1491. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1492. // glibc still asks the configured nameserver — which is exactly the path
  1493. // we want to exercise. A unique label per call avoids the resolver cache.
  1494. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1495. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1496. std::to_string(n) + ".invalid";
  1497. }
  1498. } // namespace
  1499. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1500. if (!should_run_issue_2431_tests()) {
  1501. GTEST_SKIP()
  1502. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1503. }
  1504. for (int i = 0; i < 8; ++i) {
  1505. struct addrinfo hints;
  1506. memset(&hints, 0, sizeof(hints));
  1507. hints.ai_family = AF_UNSPEC;
  1508. hints.ai_socktype = SOCK_STREAM;
  1509. auto host = unique_unresolvable_host(i);
  1510. struct addrinfo *result = nullptr;
  1511. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1512. &result, /*timeout_sec=*/1);
  1513. if (rc == 0 && result) { freeaddrinfo(result); }
  1514. }
  1515. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1516. // stack region they still believe holds their gaicb.
  1517. std::this_thread::sleep_for(std::chrono::seconds(3));
  1518. }
  1519. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1520. if (!should_run_issue_2431_tests()) {
  1521. GTEST_SKIP()
  1522. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1523. }
  1524. std::atomic<bool> stop{false};
  1525. std::vector<std::thread> threads;
  1526. for (int t = 0; t < 8; ++t) {
  1527. threads.emplace_back([t, &stop] {
  1528. int i = 0;
  1529. while (!stop.load(std::memory_order_relaxed)) {
  1530. struct addrinfo hints;
  1531. memset(&hints, 0, sizeof(hints));
  1532. hints.ai_family = AF_UNSPEC;
  1533. hints.ai_socktype = SOCK_STREAM;
  1534. auto host = unique_unresolvable_host(t * 100000 + i++);
  1535. struct addrinfo *result = nullptr;
  1536. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1537. &result, /*timeout_sec=*/1);
  1538. if (rc == 0 && result) { freeaddrinfo(result); }
  1539. }
  1540. });
  1541. }
  1542. std::this_thread::sleep_for(std::chrono::seconds(8));
  1543. stop.store(true, std::memory_order_relaxed);
  1544. for (auto &th : threads) {
  1545. th.join();
  1546. }
  1547. std::this_thread::sleep_for(std::chrono::seconds(3));
  1548. }
  1549. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1550. if (!should_run_issue_2431_tests()) {
  1551. GTEST_SKIP()
  1552. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1553. }
  1554. std::atomic<bool> stop{false};
  1555. std::vector<std::thread> threads;
  1556. for (int t = 0; t < 8; ++t) {
  1557. threads.emplace_back([t, &stop] {
  1558. int i = 0;
  1559. while (!stop.load(std::memory_order_relaxed)) {
  1560. auto host = unique_unresolvable_host(t * 100000 + i++);
  1561. Client cli(host, 80);
  1562. cli.set_connection_timeout(1, 0);
  1563. cli.set_read_timeout(1, 0);
  1564. cli.set_write_timeout(1, 0);
  1565. (void)cli.Get("/");
  1566. }
  1567. });
  1568. }
  1569. std::this_thread::sleep_for(std::chrono::seconds(8));
  1570. stop.store(true, std::memory_order_relaxed);
  1571. for (auto &th : threads) {
  1572. th.join();
  1573. }
  1574. std::this_thread::sleep_for(std::chrono::seconds(3));
  1575. }
  1576. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1577. TEST(ConnectionErrorTest, InvalidHost) {
  1578. auto host = "-abcde.com";
  1579. #ifdef CPPHTTPLIB_SSL_ENABLED
  1580. auto port = 443;
  1581. SSLClient cli(host, port);
  1582. #else
  1583. auto port = 80;
  1584. Client cli(host, port);
  1585. #endif
  1586. cli.set_connection_timeout(std::chrono::seconds(2));
  1587. auto res = cli.Get("/");
  1588. ASSERT_TRUE(!res);
  1589. EXPECT_EQ(Error::Connection, res.error());
  1590. }
  1591. TEST(ConnectionErrorTest, InvalidHost2) {
  1592. auto host = "httpcan.org/";
  1593. #ifdef CPPHTTPLIB_SSL_ENABLED
  1594. SSLClient cli(host);
  1595. #else
  1596. Client cli(host);
  1597. #endif
  1598. cli.set_connection_timeout(std::chrono::seconds(2));
  1599. auto res = cli.Get("/");
  1600. ASSERT_TRUE(!res);
  1601. EXPECT_EQ(Error::Connection, res.error());
  1602. }
  1603. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1604. auto host = "httpcan.org/";
  1605. #ifdef CPPHTTPLIB_SSL_ENABLED
  1606. SSLClient cli(host);
  1607. #else
  1608. Client cli(host);
  1609. #endif
  1610. cli.set_connection_timeout(std::chrono::seconds(2));
  1611. auto res = cli.Get("/");
  1612. ASSERT_TRUE(!res);
  1613. stringstream s;
  1614. s << "error code: " << res.error();
  1615. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1616. }
  1617. TEST(ConnectionErrorTest, InvalidPort) {
  1618. auto host = "localhost";
  1619. auto port = 44380;
  1620. #ifdef CPPHTTPLIB_SSL_ENABLED
  1621. SSLClient cli(host, port);
  1622. #else
  1623. Client cli(host, port);
  1624. #endif
  1625. cli.set_connection_timeout(std::chrono::seconds(2));
  1626. auto res = cli.Get("/");
  1627. ASSERT_TRUE(!res);
  1628. EXPECT_TRUE(Error::Connection == res.error() ||
  1629. Error::ConnectionTimeout == res.error());
  1630. }
  1631. TEST(ConnectionErrorTest, Timeout_Online) {
  1632. auto host = "google.com";
  1633. #ifdef CPPHTTPLIB_SSL_ENABLED
  1634. auto port = 44380;
  1635. SSLClient cli(host, port);
  1636. #else
  1637. auto port = 8080;
  1638. Client cli(host, port);
  1639. #endif
  1640. cli.set_connection_timeout(std::chrono::seconds(2));
  1641. // only probe one address type so that the error reason
  1642. // correlates to the timed-out IPv4, not the unsupported
  1643. // IPv6 connection attempt
  1644. cli.set_address_family(AF_INET);
  1645. auto res = cli.Get("/");
  1646. ASSERT_TRUE(!res);
  1647. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1648. }
  1649. TEST(CancelTest, NoCancel_Online) {
  1650. auto host = "httpbingo.org";
  1651. auto path = std::string{"/range/32"};
  1652. #ifdef CPPHTTPLIB_SSL_ENABLED
  1653. auto port = 443;
  1654. SSLClient cli(host, port);
  1655. #else
  1656. auto port = 80;
  1657. Client cli(host, port);
  1658. #endif
  1659. cli.set_connection_timeout(std::chrono::seconds(5));
  1660. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1661. ASSERT_TRUE(res);
  1662. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1663. EXPECT_EQ(StatusCode::OK_200, res->status);
  1664. }
  1665. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1666. // Use /bytes with a large payload so that the DownloadProgress callback
  1667. // (which only fires for Content-Length responses) is invoked before the
  1668. // entire body is received, giving cancellation a chance to fire.
  1669. auto host = "httpbingo.org";
  1670. auto path = std::string{"/bytes/524288"};
  1671. #ifdef CPPHTTPLIB_SSL_ENABLED
  1672. auto port = 443;
  1673. SSLClient cli(host, port);
  1674. #else
  1675. auto port = 80;
  1676. Client cli(host, port);
  1677. #endif
  1678. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1679. cli.set_connection_timeout(std::chrono::seconds(5));
  1680. ASSERT_TRUE(!res);
  1681. EXPECT_EQ(Error::Canceled, res.error());
  1682. }
  1683. TEST(CancelTest, WithCancelLargePayload_Online) {
  1684. auto host = "httpbingo.org";
  1685. auto path = std::string{"/bytes/524288"};
  1686. #ifdef CPPHTTPLIB_SSL_ENABLED
  1687. auto port = 443;
  1688. SSLClient cli(host, port);
  1689. #else
  1690. auto port = 80;
  1691. Client cli(host, port);
  1692. #endif
  1693. cli.set_connection_timeout(std::chrono::seconds(5));
  1694. uint32_t count = 0;
  1695. auto res =
  1696. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1697. ASSERT_TRUE(!res);
  1698. EXPECT_EQ(Error::Canceled, res.error());
  1699. }
  1700. TEST(CancelTest, NoCancelPost) {
  1701. Server svr;
  1702. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1703. res.set_content("Hello World!", "text/plain");
  1704. });
  1705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1706. auto se = detail::scope_exit([&] {
  1707. svr.stop();
  1708. thread.join();
  1709. ASSERT_FALSE(svr.is_running());
  1710. });
  1711. svr.wait_until_ready();
  1712. Client cli(HOST, PORT);
  1713. cli.set_connection_timeout(std::chrono::seconds(5));
  1714. auto res =
  1715. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1716. "application/json", [](uint64_t, uint64_t) { return true; });
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ("Hello World!", res->body);
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. }
  1721. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1722. Server svr;
  1723. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1724. res.set_content("Hello World!", "text/plain");
  1725. });
  1726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. thread.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. Client cli(HOST, PORT);
  1734. cli.set_connection_timeout(std::chrono::seconds(5));
  1735. auto res =
  1736. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1737. "application/json", [](uint64_t, uint64_t) { return false; });
  1738. ASSERT_TRUE(!res);
  1739. EXPECT_EQ(Error::Canceled, res.error());
  1740. }
  1741. TEST(CancelTest, WithCancelLargePayloadPost) {
  1742. Server svr;
  1743. svr.set_payload_max_length(200 * 1024 * 1024);
  1744. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content(LARGE_DATA, "text/plain");
  1746. });
  1747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1748. auto se = detail::scope_exit([&] {
  1749. svr.stop();
  1750. thread.join();
  1751. ASSERT_FALSE(svr.is_running());
  1752. });
  1753. svr.wait_until_ready();
  1754. Client cli(HOST, PORT);
  1755. cli.set_payload_max_length(200 * 1024 * 1024);
  1756. cli.set_connection_timeout(std::chrono::seconds(5));
  1757. auto res =
  1758. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1759. "application/json", [](uint64_t, uint64_t) { return false; });
  1760. ASSERT_TRUE(!res);
  1761. EXPECT_EQ(Error::Canceled, res.error());
  1762. }
  1763. TEST(CancelTest, NoCancelPut) {
  1764. Server svr;
  1765. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1766. res.set_content("Hello World!", "text/plain");
  1767. });
  1768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1769. auto se = detail::scope_exit([&] {
  1770. svr.stop();
  1771. thread.join();
  1772. ASSERT_FALSE(svr.is_running());
  1773. });
  1774. svr.wait_until_ready();
  1775. Client cli(HOST, PORT);
  1776. cli.set_connection_timeout(std::chrono::seconds(5));
  1777. auto res =
  1778. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1779. "application/json", [](uint64_t, uint64_t) { return true; });
  1780. ASSERT_TRUE(res);
  1781. EXPECT_EQ("Hello World!", res->body);
  1782. EXPECT_EQ(StatusCode::OK_200, res->status);
  1783. }
  1784. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1785. Server svr;
  1786. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1787. res.set_content("Hello World!", "text/plain");
  1788. });
  1789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1790. auto se = detail::scope_exit([&] {
  1791. svr.stop();
  1792. thread.join();
  1793. ASSERT_FALSE(svr.is_running());
  1794. });
  1795. svr.wait_until_ready();
  1796. Client cli(HOST, PORT);
  1797. cli.set_connection_timeout(std::chrono::seconds(5));
  1798. auto res =
  1799. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1800. "application/json", [](uint64_t, uint64_t) { return false; });
  1801. ASSERT_TRUE(!res);
  1802. EXPECT_EQ(Error::Canceled, res.error());
  1803. }
  1804. TEST(CancelTest, WithCancelLargePayloadPut) {
  1805. Server svr;
  1806. svr.set_payload_max_length(200 * 1024 * 1024);
  1807. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1808. res.set_content(LARGE_DATA, "text/plain");
  1809. });
  1810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1811. auto se = detail::scope_exit([&] {
  1812. svr.stop();
  1813. thread.join();
  1814. ASSERT_FALSE(svr.is_running());
  1815. });
  1816. svr.wait_until_ready();
  1817. Client cli(HOST, PORT);
  1818. cli.set_payload_max_length(200 * 1024 * 1024);
  1819. cli.set_connection_timeout(std::chrono::seconds(5));
  1820. auto res =
  1821. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1822. "application/json", [](uint64_t, uint64_t) { return false; });
  1823. ASSERT_TRUE(!res);
  1824. EXPECT_EQ(Error::Canceled, res.error());
  1825. }
  1826. TEST(CancelTest, NoCancelPatch) {
  1827. Server svr;
  1828. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1829. res.set_content("Hello World!", "text/plain");
  1830. });
  1831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. Client cli(HOST, PORT);
  1839. cli.set_connection_timeout(std::chrono::seconds(5));
  1840. auto res =
  1841. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1842. "application/json", [](uint64_t, uint64_t) { return true; });
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ("Hello World!", res->body);
  1845. EXPECT_EQ(StatusCode::OK_200, res->status);
  1846. }
  1847. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1848. Server svr;
  1849. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1850. res.set_content("Hello World!", "text/plain");
  1851. });
  1852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1853. auto se = detail::scope_exit([&] {
  1854. svr.stop();
  1855. thread.join();
  1856. ASSERT_FALSE(svr.is_running());
  1857. });
  1858. svr.wait_until_ready();
  1859. Client cli(HOST, PORT);
  1860. cli.set_connection_timeout(std::chrono::seconds(5));
  1861. auto res =
  1862. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1863. "application/json", [](uint64_t, uint64_t) { return false; });
  1864. ASSERT_TRUE(!res);
  1865. EXPECT_EQ(Error::Canceled, res.error());
  1866. }
  1867. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1868. Server svr;
  1869. svr.set_payload_max_length(200 * 1024 * 1024);
  1870. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1871. res.set_content(LARGE_DATA, "text/plain");
  1872. });
  1873. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1874. auto se = detail::scope_exit([&] {
  1875. svr.stop();
  1876. thread.join();
  1877. ASSERT_FALSE(svr.is_running());
  1878. });
  1879. svr.wait_until_ready();
  1880. Client cli(HOST, PORT);
  1881. cli.set_payload_max_length(200 * 1024 * 1024);
  1882. cli.set_connection_timeout(std::chrono::seconds(5));
  1883. auto res =
  1884. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1885. "application/json", [](uint64_t, uint64_t) { return false; });
  1886. ASSERT_TRUE(!res);
  1887. EXPECT_EQ(Error::Canceled, res.error());
  1888. }
  1889. TEST(CancelTest, NoCancelDelete) {
  1890. Server svr;
  1891. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1892. res.set_content("Hello World!", "text/plain");
  1893. });
  1894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1895. auto se = detail::scope_exit([&] {
  1896. svr.stop();
  1897. thread.join();
  1898. ASSERT_FALSE(svr.is_running());
  1899. });
  1900. svr.wait_until_ready();
  1901. Client cli(HOST, PORT);
  1902. cli.set_connection_timeout(std::chrono::seconds(5));
  1903. auto res =
  1904. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1905. "application/json", [](uint64_t, uint64_t) { return true; });
  1906. ASSERT_TRUE(res);
  1907. EXPECT_EQ("Hello World!", res->body);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. }
  1910. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1911. Server svr;
  1912. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content("Hello World!", "text/plain");
  1914. });
  1915. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1916. auto se = detail::scope_exit([&] {
  1917. svr.stop();
  1918. thread.join();
  1919. ASSERT_FALSE(svr.is_running());
  1920. });
  1921. svr.wait_until_ready();
  1922. Client cli(HOST, PORT);
  1923. cli.set_connection_timeout(std::chrono::seconds(5));
  1924. auto res =
  1925. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1926. "application/json", [](uint64_t, uint64_t) { return false; });
  1927. ASSERT_TRUE(!res);
  1928. EXPECT_EQ(Error::Canceled, res.error());
  1929. }
  1930. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1931. Server svr;
  1932. svr.set_payload_max_length(200 * 1024 * 1024);
  1933. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1934. res.set_content(LARGE_DATA, "text/plain");
  1935. });
  1936. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1937. auto se = detail::scope_exit([&] {
  1938. svr.stop();
  1939. thread.join();
  1940. ASSERT_FALSE(svr.is_running());
  1941. });
  1942. svr.wait_until_ready();
  1943. Client cli(HOST, PORT);
  1944. cli.set_payload_max_length(200 * 1024 * 1024);
  1945. cli.set_connection_timeout(std::chrono::seconds(5));
  1946. auto res =
  1947. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1948. "application/json", [](uint64_t, uint64_t) { return false; });
  1949. ASSERT_TRUE(!res);
  1950. EXPECT_EQ(Error::Canceled, res.error());
  1951. }
  1952. static std::string remove_whitespace(const std::string &input) {
  1953. std::string output;
  1954. output.reserve(input.size());
  1955. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1956. [](unsigned char c) { return !std::isspace(c); });
  1957. return output;
  1958. }
  1959. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1960. auto host = "httpbingo.org";
  1961. auto path = std::string{"/basic-auth/hello/world"};
  1962. #ifdef CPPHTTPLIB_SSL_ENABLED
  1963. auto port = 443;
  1964. SSLClient cli(host, port);
  1965. #else
  1966. auto port = 80;
  1967. Client cli(host, port);
  1968. #endif
  1969. {
  1970. auto res = cli.Get(path);
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1973. }
  1974. {
  1975. auto res = cli.Get(
  1976. path, Headers{make_basic_authentication_header("hello", "world")});
  1977. ASSERT_TRUE(res);
  1978. auto body = remove_whitespace(res->body);
  1979. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1980. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. }
  1983. {
  1984. cli.set_basic_auth("hello", "world");
  1985. auto res = cli.Get(path);
  1986. ASSERT_TRUE(res);
  1987. auto body = remove_whitespace(res->body);
  1988. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1989. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1990. EXPECT_EQ(StatusCode::OK_200, res->status);
  1991. }
  1992. {
  1993. cli.set_basic_auth("hello", "bad");
  1994. auto res = cli.Get(path);
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1997. }
  1998. {
  1999. cli.set_basic_auth("bad", "world");
  2000. auto res = cli.Get(path);
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2003. }
  2004. }
  2005. #ifdef CPPHTTPLIB_SSL_ENABLED
  2006. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2007. auto host = "httpbingo.org";
  2008. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2009. auto paths = std::vector<std::string>{
  2010. "/digest-auth/auth/hello/world/MD5",
  2011. "/digest-auth/auth/hello/world/SHA-256",
  2012. };
  2013. auto port = 443;
  2014. SSLClient cli(host, port);
  2015. {
  2016. auto res = cli.Get(unauth_path);
  2017. ASSERT_TRUE(res);
  2018. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2019. }
  2020. {
  2021. cli.set_digest_auth("hello", "world");
  2022. for (const auto &path : paths) {
  2023. auto res = cli.Get(path.c_str());
  2024. ASSERT_TRUE(res);
  2025. auto body = remove_whitespace(res->body);
  2026. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2027. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. }
  2030. cli.set_digest_auth("hello", "bad");
  2031. for (const auto &path : paths) {
  2032. auto res = cli.Get(path.c_str());
  2033. ASSERT_TRUE(res);
  2034. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2035. }
  2036. }
  2037. }
  2038. #endif
  2039. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2040. auto host = "google.com";
  2041. auto another_host = "example.com";
  2042. auto wrong_ip = "0.0.0.0";
  2043. #ifdef CPPHTTPLIB_SSL_ENABLED
  2044. SSLClient cli(host);
  2045. #else
  2046. Client cli(host);
  2047. #endif
  2048. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2049. auto res = cli.Get("/");
  2050. ASSERT_TRUE(res);
  2051. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2052. }
  2053. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2054. auto host = "google.com";
  2055. auto wrong_ip = "0.0.0.0";
  2056. #ifdef CPPHTTPLIB_SSL_ENABLED
  2057. SSLClient cli(host);
  2058. #else
  2059. Client cli(host);
  2060. #endif
  2061. cli.set_hostname_addr_map({{host, wrong_ip}});
  2062. auto res = cli.Get("/");
  2063. ASSERT_TRUE(!res);
  2064. EXPECT_EQ(Error::Connection, res.error());
  2065. }
  2066. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2067. auto host = "httpbingo.org";
  2068. auto path = std::string{"/absolute-redirect/3"};
  2069. #ifdef CPPHTTPLIB_SSL_ENABLED
  2070. SSLClient cli(host);
  2071. #else
  2072. Client cli(host);
  2073. #endif
  2074. cli.set_follow_location(true);
  2075. auto res = cli.Get(path);
  2076. ASSERT_TRUE(res);
  2077. EXPECT_EQ(StatusCode::OK_200, res->status);
  2078. }
  2079. TEST(RedirectTest, Redirect_Online) {
  2080. auto host = "httpbingo.org";
  2081. auto path = std::string{"/redirect/3"};
  2082. #ifdef CPPHTTPLIB_SSL_ENABLED
  2083. SSLClient cli(host);
  2084. #else
  2085. Client cli(host);
  2086. #endif
  2087. cli.set_follow_location(true);
  2088. auto res = cli.Get(path);
  2089. ASSERT_TRUE(res);
  2090. EXPECT_EQ(StatusCode::OK_200, res->status);
  2091. }
  2092. TEST(RelativeRedirectTest, Redirect_Online) {
  2093. auto host = "httpbingo.org";
  2094. auto path = std::string{"/relative-redirect/3"};
  2095. #ifdef CPPHTTPLIB_SSL_ENABLED
  2096. SSLClient cli(host);
  2097. #else
  2098. Client cli(host);
  2099. #endif
  2100. cli.set_follow_location(true);
  2101. auto res = cli.Get(path);
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(StatusCode::OK_200, res->status);
  2104. }
  2105. TEST(TooManyRedirectTest, Redirect_Online) {
  2106. auto host = "httpbingo.org";
  2107. auto path = std::string{"/redirect/21"};
  2108. #ifdef CPPHTTPLIB_SSL_ENABLED
  2109. SSLClient cli(host);
  2110. #else
  2111. Client cli(host);
  2112. #endif
  2113. cli.set_follow_location(true);
  2114. auto res = cli.Get(path);
  2115. ASSERT_TRUE(!res);
  2116. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2117. }
  2118. #ifdef CPPHTTPLIB_SSL_ENABLED
  2119. TEST(YahooRedirectTest, Redirect_Online) {
  2120. Client cli("yahoo.com");
  2121. auto res = cli.Get("/");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2124. cli.set_follow_location(true);
  2125. res = cli.Get("/");
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2129. }
  2130. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2131. #define REDIR_HOST "httpbingo.org"
  2132. #define REDIR_PATH "/redirect-to"
  2133. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2134. SSLClient cli(REDIR_HOST);
  2135. cli.set_follow_location(true);
  2136. auto res =
  2137. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::OK_200, res->status);
  2140. }
  2141. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2142. SSLClient cli(REDIR_HOST);
  2143. cli.set_follow_location(true);
  2144. Params params;
  2145. params.emplace("url", "http://example.com");
  2146. params.emplace("status_code", "302");
  2147. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2148. ASSERT_TRUE(res);
  2149. EXPECT_EQ(StatusCode::OK_200, res->status);
  2150. }
  2151. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2152. SSLClient cli(REDIR_HOST);
  2153. cli.set_follow_location(true);
  2154. Params params;
  2155. params.emplace("url", "http://example.com");
  2156. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2157. ASSERT_TRUE(res);
  2158. EXPECT_EQ(StatusCode::OK_200, res->status);
  2159. }
  2160. TEST(UrlWithSpace, Redirect_Online) {
  2161. SSLClient cli("edge.forgecdn.net");
  2162. cli.set_follow_location(true);
  2163. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2167. }
  2168. #endif
  2169. #if !defined(_WIN32) && !defined(_WIN64)
  2170. TEST(ReceiveSignals, Signal) {
  2171. auto setupSignalHandlers = []() {
  2172. struct sigaction act;
  2173. sigemptyset(&act.sa_mask);
  2174. act.sa_flags = SA_SIGINFO;
  2175. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2176. switch (sig) {
  2177. case SIGINT:
  2178. default: break;
  2179. }
  2180. };
  2181. ::sigaction(SIGINT, &act, nullptr);
  2182. };
  2183. Server svr;
  2184. int port = 0;
  2185. auto thread = std::thread([&]() {
  2186. setupSignalHandlers();
  2187. port = svr.bind_to_any_port(HOST);
  2188. svr.listen_after_bind();
  2189. });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. ASSERT_TRUE(svr.is_running());
  2197. pthread_kill(thread.native_handle(), SIGINT);
  2198. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2199. ASSERT_TRUE(svr.is_running());
  2200. }
  2201. #endif
  2202. TEST(RedirectToDifferentPort, Redirect) {
  2203. Server svr1;
  2204. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2205. res.set_content("Hello World!", "text/plain");
  2206. });
  2207. int svr1_port = 0;
  2208. auto thread1 = std::thread([&]() {
  2209. svr1_port = svr1.bind_to_any_port(HOST);
  2210. svr1.listen_after_bind();
  2211. });
  2212. Server svr2;
  2213. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2214. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2215. });
  2216. int svr2_port = 0;
  2217. auto thread2 = std::thread([&]() {
  2218. svr2_port = svr2.bind_to_any_port(HOST);
  2219. svr2.listen_after_bind();
  2220. });
  2221. auto se = detail::scope_exit([&] {
  2222. svr2.stop();
  2223. thread2.join();
  2224. svr1.stop();
  2225. thread1.join();
  2226. ASSERT_FALSE(svr2.is_running());
  2227. ASSERT_FALSE(svr1.is_running());
  2228. });
  2229. svr1.wait_until_ready();
  2230. svr2.wait_until_ready();
  2231. Client cli("localhost", svr2_port);
  2232. cli.set_follow_location(true);
  2233. auto res = cli.Get("/2");
  2234. ASSERT_TRUE(res);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. EXPECT_EQ("Hello World!", res->body);
  2237. }
  2238. static void
  2239. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2240. Server svr1;
  2241. std::string captured_authorization;
  2242. svr1.Get("/target", [&](const Request &req, Response &res) {
  2243. captured_authorization = req.get_header_value("Authorization");
  2244. res.set_content("OK", "text/plain");
  2245. });
  2246. int svr1_port = 0;
  2247. auto thread1 = std::thread([&]() {
  2248. svr1_port = svr1.bind_to_any_port(HOST);
  2249. svr1.listen_after_bind();
  2250. });
  2251. Server svr2;
  2252. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2253. res.set_redirect(
  2254. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2255. });
  2256. int svr2_port = 0;
  2257. auto thread2 = std::thread([&]() {
  2258. svr2_port = svr2.bind_to_any_port(HOST);
  2259. svr2.listen_after_bind();
  2260. });
  2261. auto se = detail::scope_exit([&] {
  2262. svr2.stop();
  2263. thread2.join();
  2264. svr1.stop();
  2265. thread1.join();
  2266. ASSERT_FALSE(svr2.is_running());
  2267. ASSERT_FALSE(svr1.is_running());
  2268. });
  2269. svr1.wait_until_ready();
  2270. svr2.wait_until_ready();
  2271. Client cli("localhost", svr2_port);
  2272. cli.set_follow_location(true);
  2273. set_auth(cli);
  2274. auto res = cli.Get("/redir");
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(StatusCode::OK_200, res->status);
  2277. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2278. EXPECT_TRUE(captured_authorization.empty());
  2279. }
  2280. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2281. TestDoNotForwardCredentialsOnRedirect(
  2282. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2283. }
  2284. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2285. TestDoNotForwardCredentialsOnRedirect(
  2286. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2287. }
  2288. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2289. Server svr;
  2290. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2291. // Port number that overflows int — should not crash
  2292. res.set_redirect("http://localhost:99999999999999999999/target");
  2293. });
  2294. auto port = svr.bind_to_any_port(HOST);
  2295. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2296. auto se = detail::scope_exit([&] {
  2297. svr.stop();
  2298. thread.join();
  2299. ASSERT_FALSE(svr.is_running());
  2300. });
  2301. svr.wait_until_ready();
  2302. Client cli(HOST, port);
  2303. cli.set_follow_location(true);
  2304. auto res = cli.Get("/redir");
  2305. // Should fail gracefully, not crash (no valid response due to bad port)
  2306. EXPECT_FALSE(res);
  2307. }
  2308. TEST(RedirectFromPageWithContent, Redirect) {
  2309. Server svr;
  2310. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2311. res.set_content("___", "text/plain");
  2312. res.set_redirect("/2");
  2313. });
  2314. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2315. res.set_content("Hello World!", "text/plain");
  2316. });
  2317. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2318. auto se = detail::scope_exit([&] {
  2319. svr.stop();
  2320. th.join();
  2321. ASSERT_FALSE(svr.is_running());
  2322. });
  2323. svr.wait_until_ready();
  2324. {
  2325. Client cli("localhost", PORT);
  2326. cli.set_follow_location(true);
  2327. std::string body;
  2328. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2329. body.append(data, data_length);
  2330. return true;
  2331. });
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::OK_200, res->status);
  2334. EXPECT_EQ("Hello World!", body);
  2335. }
  2336. {
  2337. Client cli("localhost", PORT);
  2338. std::string body;
  2339. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2340. body.append(data, data_length);
  2341. return true;
  2342. });
  2343. ASSERT_TRUE(res);
  2344. EXPECT_EQ(StatusCode::Found_302, res->status);
  2345. EXPECT_EQ("___", body);
  2346. }
  2347. }
  2348. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2349. Server svr;
  2350. auto port_str = std::to_string(PORT);
  2351. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2352. auto expected_host = "[::1]:" + port_str;
  2353. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2354. res.set_content("___", "text/plain");
  2355. // res.set_redirect("/2");
  2356. res.set_redirect(redirect_url);
  2357. });
  2358. svr.Get("/2", [&](const Request &req, Response &res) {
  2359. auto host_header = req.headers.find("Host");
  2360. ASSERT_TRUE(host_header != req.headers.end());
  2361. EXPECT_EQ(expected_host, host_header->second);
  2362. res.set_content("Hello World!", "text/plain");
  2363. });
  2364. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2365. auto se = detail::scope_exit([&] {
  2366. svr.stop();
  2367. th.join();
  2368. ASSERT_FALSE(svr.is_running());
  2369. });
  2370. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2371. // actually starts anything, so the condition !svr.is_running() will
  2372. // always remain true, and the loop never stops.
  2373. // This basically counts how many milliseconds have passed since the
  2374. // call to svr.listen(), and if after 5 seconds nothing started yet
  2375. // aborts the test.
  2376. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2377. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2378. ASSERT_LT(milliseconds, 5000U);
  2379. }
  2380. {
  2381. Client cli("::1", PORT);
  2382. cli.set_follow_location(true);
  2383. std::string body;
  2384. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2385. body.append(data, data_length);
  2386. return true;
  2387. });
  2388. ASSERT_TRUE(res);
  2389. EXPECT_EQ(StatusCode::OK_200, res->status);
  2390. EXPECT_EQ("Hello World!", body);
  2391. }
  2392. {
  2393. Client cli("::1", PORT);
  2394. std::string body;
  2395. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2396. body.append(data, data_length);
  2397. return true;
  2398. });
  2399. ASSERT_TRUE(res);
  2400. EXPECT_EQ(StatusCode::Found_302, res->status);
  2401. EXPECT_EQ("___", body);
  2402. }
  2403. }
  2404. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2405. Server svr;
  2406. svr.Get("/foo", [](const Request &req, Response &res) {
  2407. auto a = req.params.find("a");
  2408. if (a != req.params.end()) {
  2409. res.set_content((*a).second, "text/plain");
  2410. res.status = StatusCode::OK_200;
  2411. } else {
  2412. res.status = StatusCode::BadRequest_400;
  2413. }
  2414. });
  2415. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2416. auto se = detail::scope_exit([&] {
  2417. svr.stop();
  2418. thread.join();
  2419. ASSERT_FALSE(svr.is_running());
  2420. });
  2421. svr.wait_until_ready();
  2422. {
  2423. Client cli(HOST, PORT);
  2424. cli.set_path_encode(false);
  2425. auto res = cli.Get("/foo?a=explicitly+encoded");
  2426. ASSERT_TRUE(res);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. // This expects it back with a space, as the `+` won't have been
  2429. // url-encoded, and server-side the params get decoded turning `+`
  2430. // into spaces.
  2431. EXPECT_EQ("explicitly encoded", res->body);
  2432. }
  2433. }
  2434. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2435. // When path encoding is disabled the client must transmit the supplied
  2436. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2437. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2438. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2439. // than a space (0x20). Assert on the raw wire target to catch this.
  2440. Server svr;
  2441. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2442. svr.Get("/foo", [&](const Request &req, Response &res) {
  2443. EXPECT_EQ(expected_target, req.target);
  2444. res.status = StatusCode::OK_200;
  2445. });
  2446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. {
  2454. Client cli(HOST, PORT);
  2455. cli.set_path_encode(false);
  2456. auto res = cli.Get(expected_target.c_str());
  2457. ASSERT_TRUE(res);
  2458. EXPECT_EQ(StatusCode::OK_200, res->status);
  2459. }
  2460. }
  2461. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2462. Server svr;
  2463. svr.Get("/", [](const Request &req, Response &) {
  2464. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2465. });
  2466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2467. auto se = detail::scope_exit([&] {
  2468. svr.stop();
  2469. thread.join();
  2470. ASSERT_FALSE(svr.is_running());
  2471. });
  2472. svr.wait_until_ready();
  2473. {
  2474. Client cli(HOST, PORT);
  2475. cli.set_path_encode(false);
  2476. auto res = cli.Get("/?something=%0A");
  2477. ASSERT_TRUE(res);
  2478. EXPECT_EQ(StatusCode::OK_200, res->status);
  2479. }
  2480. }
  2481. TEST(BindServerTest, BindDualStack) {
  2482. Server svr;
  2483. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2484. res.set_content("Hello World!", "text/plain");
  2485. });
  2486. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2487. auto se = detail::scope_exit([&] {
  2488. svr.stop();
  2489. thread.join();
  2490. ASSERT_FALSE(svr.is_running());
  2491. });
  2492. svr.wait_until_ready();
  2493. {
  2494. Client cli("127.0.0.1", PORT);
  2495. auto res = cli.Get("/1");
  2496. ASSERT_TRUE(res);
  2497. EXPECT_EQ(StatusCode::OK_200, res->status);
  2498. EXPECT_EQ("Hello World!", res->body);
  2499. }
  2500. {
  2501. Client cli("::1", PORT);
  2502. auto res = cli.Get("/1");
  2503. ASSERT_TRUE(res);
  2504. EXPECT_EQ(StatusCode::OK_200, res->status);
  2505. EXPECT_EQ("Hello World!", res->body);
  2506. }
  2507. }
  2508. TEST(BindServerTest, BindAndListenSeparately) {
  2509. Server svr;
  2510. int port = svr.bind_to_any_port("0.0.0.0");
  2511. ASSERT_TRUE(svr.is_valid());
  2512. ASSERT_TRUE(port > 0);
  2513. svr.stop();
  2514. }
  2515. #ifdef CPPHTTPLIB_SSL_ENABLED
  2516. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2518. CLIENT_CA_CERT_DIR);
  2519. int port = svr.bind_to_any_port("0.0.0.0");
  2520. ASSERT_TRUE(svr.is_valid());
  2521. ASSERT_TRUE(port > 0);
  2522. svr.stop();
  2523. }
  2524. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2525. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2526. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2527. int port = svr.bind_to_any_port("0.0.0.0");
  2528. ASSERT_TRUE(svr.is_valid());
  2529. ASSERT_TRUE(port > 0);
  2530. svr.stop();
  2531. }
  2532. TEST(BindServerTest, UpdateCertsPem) {
  2533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2534. int port = svr.bind_to_any_port("0.0.0.0");
  2535. ASSERT_TRUE(svr.is_valid());
  2536. ASSERT_TRUE(port > 0);
  2537. // Read PEM files
  2538. std::string cert_pem, key_pem, ca_pem;
  2539. read_file(SERVER_CERT_FILE, cert_pem);
  2540. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2541. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2542. // Update server certificates using PEM API
  2543. ASSERT_TRUE(
  2544. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2545. ASSERT_TRUE(svr.is_valid());
  2546. svr.stop();
  2547. }
  2548. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2549. // Start server with client CA (enables client auth)
  2550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2551. ASSERT_TRUE(svr.is_valid());
  2552. bool handler_called = false;
  2553. svr.Get("/test", [&](const Request &req, Response &res) {
  2554. handler_called = true;
  2555. // Verify client certificate is present
  2556. auto cert = req.peer_cert();
  2557. EXPECT_TRUE(static_cast<bool>(cert));
  2558. res.set_content("ok", "text/plain");
  2559. });
  2560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2561. auto se = detail::scope_exit([&] {
  2562. svr.stop();
  2563. t.join();
  2564. ASSERT_FALSE(svr.is_running());
  2565. });
  2566. svr.wait_until_ready();
  2567. // Read PEM files
  2568. std::string cert_pem, key_pem, ca_pem;
  2569. read_file(SERVER_CERT_FILE, cert_pem);
  2570. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2571. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2572. // Update server certificates and client CA using PEM API while server running
  2573. ASSERT_TRUE(
  2574. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2575. // Connect with client certificate
  2576. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2577. cli.enable_server_certificate_verification(false);
  2578. cli.set_connection_timeout(30);
  2579. auto res = cli.Get("/test");
  2580. ASSERT_TRUE(res);
  2581. ASSERT_EQ(StatusCode::OK_200, res->status);
  2582. ASSERT_TRUE(handler_called);
  2583. EXPECT_EQ("ok", res->body);
  2584. }
  2585. #endif
  2586. TEST(ErrorHandlerTest, ContentLength) {
  2587. Server svr;
  2588. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2589. res.status = StatusCode::OK_200;
  2590. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2591. "text/html"); // <= Content-Length still 13
  2592. });
  2593. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2594. res.set_content("Hello World!\n", "text/plain");
  2595. res.status = 524;
  2596. });
  2597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2598. auto se = detail::scope_exit([&] {
  2599. svr.stop();
  2600. thread.join();
  2601. ASSERT_FALSE(svr.is_running());
  2602. });
  2603. svr.wait_until_ready();
  2604. {
  2605. Client cli(HOST, PORT);
  2606. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2607. ASSERT_TRUE(res);
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2610. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2611. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2612. }
  2613. }
  2614. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2615. TEST(ExceptionTest, WithoutExceptionHandler) {
  2616. Server svr;
  2617. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2618. throw std::runtime_error("exception...");
  2619. });
  2620. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2621. throw std::runtime_error("exception\r\n...");
  2622. });
  2623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. listen_thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli("localhost", PORT);
  2631. {
  2632. auto res = cli.Get("/exception");
  2633. ASSERT_TRUE(res);
  2634. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2635. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2636. }
  2637. {
  2638. auto res = cli.Get("/unknown");
  2639. ASSERT_TRUE(res);
  2640. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2641. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2642. }
  2643. }
  2644. TEST(ExceptionTest, WithExceptionHandler) {
  2645. Server svr;
  2646. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2647. std::exception_ptr ep) {
  2648. EXPECT_FALSE(ep == nullptr);
  2649. try {
  2650. std::rethrow_exception(ep);
  2651. } catch (std::exception &e) {
  2652. EXPECT_EQ("abc", std::string(e.what()));
  2653. } catch (...) {}
  2654. res.status = StatusCode::InternalServerError_500;
  2655. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2656. "text/html"); // <= Content-Length still 13 at this point
  2657. });
  2658. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2659. res.set_content("Hello World!\n", "text/plain");
  2660. throw std::runtime_error("abc");
  2661. });
  2662. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2663. auto se = detail::scope_exit([&] {
  2664. svr.stop();
  2665. thread.join();
  2666. ASSERT_FALSE(svr.is_running());
  2667. });
  2668. svr.wait_until_ready();
  2669. for (size_t i = 0; i < 10; i++) {
  2670. Client cli(HOST, PORT);
  2671. for (size_t j = 0; j < 100; j++) {
  2672. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2673. ASSERT_TRUE(res);
  2674. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2675. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2676. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2677. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2678. }
  2679. cli.set_keep_alive(true);
  2680. for (size_t j = 0; j < 100; j++) {
  2681. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2684. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2685. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2686. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2687. }
  2688. }
  2689. }
  2690. TEST(ExceptionTest, AndErrorHandler) {
  2691. Server svr;
  2692. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2693. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2694. });
  2695. svr.set_exception_handler(
  2696. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2697. EXPECT_FALSE(ep == nullptr);
  2698. try {
  2699. std::rethrow_exception(ep);
  2700. } catch (std::exception &e) {
  2701. res.set_content(e.what(), "text/html");
  2702. } catch (...) {}
  2703. res.status = StatusCode::InternalServerError_500;
  2704. });
  2705. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2706. throw std::runtime_error("EXCEPTION");
  2707. });
  2708. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2709. res.set_content("ERROR", "text/html");
  2710. res.status = StatusCode::InternalServerError_500;
  2711. });
  2712. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2713. auto se = detail::scope_exit([&] {
  2714. svr.stop();
  2715. thread.join();
  2716. ASSERT_FALSE(svr.is_running());
  2717. });
  2718. svr.wait_until_ready();
  2719. Client cli(HOST, PORT);
  2720. {
  2721. auto res = cli.Get("/exception");
  2722. ASSERT_TRUE(res);
  2723. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2724. EXPECT_EQ("EXCEPTION", res->body);
  2725. }
  2726. {
  2727. auto res = cli.Get("/error");
  2728. ASSERT_TRUE(res);
  2729. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2730. EXPECT_EQ("ERROR", res->body);
  2731. }
  2732. {
  2733. auto res = cli.Get("/invalid");
  2734. ASSERT_TRUE(res);
  2735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2736. EXPECT_EQ("NOT_FOUND", res->body);
  2737. }
  2738. }
  2739. #endif
  2740. TEST(NoContentTest, ContentLength) {
  2741. Server svr;
  2742. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2743. res.status = StatusCode::NoContent_204;
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. {
  2753. Client cli(HOST, PORT);
  2754. auto res = cli.Get("/hi");
  2755. ASSERT_TRUE(res);
  2756. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2757. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2758. }
  2759. }
  2760. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2763. ASSERT_TRUE(svr.is_valid());
  2764. #else
  2765. Server svr;
  2766. #endif
  2767. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2768. if (req.path == "/routing_handler") {
  2769. res.set_header("PRE_ROUTING", "on");
  2770. res.set_content("Routing Handler", "text/plain");
  2771. return httplib::Server::HandlerResponse::Handled;
  2772. }
  2773. return httplib::Server::HandlerResponse::Unhandled;
  2774. });
  2775. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2776. res.set_content("Error", "text/html");
  2777. });
  2778. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2779. if (req.path == "/routing_handler") {
  2780. res.set_header("POST_ROUTING", "on");
  2781. }
  2782. });
  2783. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2784. res.set_content("Hello World!\n", "text/plain");
  2785. });
  2786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. {
  2794. #ifdef CPPHTTPLIB_SSL_ENABLED
  2795. SSLClient cli(HOST, PORT);
  2796. cli.enable_server_certificate_verification(false);
  2797. #else
  2798. Client cli(HOST, PORT);
  2799. #endif
  2800. auto res = cli.Get("/routing_handler");
  2801. ASSERT_TRUE(res);
  2802. EXPECT_EQ(StatusCode::OK_200, res->status);
  2803. EXPECT_EQ("Routing Handler", res->body);
  2804. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2805. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2806. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2807. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2808. }
  2809. {
  2810. #ifdef CPPHTTPLIB_SSL_ENABLED
  2811. SSLClient cli(HOST, PORT);
  2812. cli.enable_server_certificate_verification(false);
  2813. #else
  2814. Client cli(HOST, PORT);
  2815. #endif
  2816. auto res = cli.Get("/hi");
  2817. ASSERT_TRUE(res);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. EXPECT_EQ("Hello World!\n", res->body);
  2820. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2821. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2822. }
  2823. {
  2824. #ifdef CPPHTTPLIB_SSL_ENABLED
  2825. SSLClient cli(HOST, PORT);
  2826. cli.enable_server_certificate_verification(false);
  2827. #else
  2828. Client cli(HOST, PORT);
  2829. #endif
  2830. auto res = cli.Get("/aaa");
  2831. ASSERT_TRUE(res);
  2832. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2833. EXPECT_EQ("Error", res->body);
  2834. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2835. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2836. }
  2837. }
  2838. TEST(RequestHandlerTest, PreRequestHandler) {
  2839. auto route_path = "/user/:user";
  2840. Server svr;
  2841. svr.Get("/hi", [](const Request &, Response &res) {
  2842. res.set_content("hi", "text/plain");
  2843. });
  2844. svr.Get(route_path, [](const Request &req, Response &res) {
  2845. res.set_content(req.path_params.at("user"), "text/plain");
  2846. });
  2847. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2848. if (req.matched_route == route_path) {
  2849. auto user = req.path_params.at("user");
  2850. if (user != "john") {
  2851. res.status = StatusCode::Forbidden_403;
  2852. res.set_content("error", "text/html");
  2853. return Server::HandlerResponse::Handled;
  2854. }
  2855. }
  2856. return Server::HandlerResponse::Unhandled;
  2857. });
  2858. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2859. auto se = detail::scope_exit([&] {
  2860. svr.stop();
  2861. thread.join();
  2862. ASSERT_FALSE(svr.is_running());
  2863. });
  2864. svr.wait_until_ready();
  2865. Client cli(HOST, PORT);
  2866. {
  2867. auto res = cli.Get("/hi");
  2868. ASSERT_TRUE(res);
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. EXPECT_EQ("hi", res->body);
  2871. }
  2872. {
  2873. auto res = cli.Get("/user/john");
  2874. ASSERT_TRUE(res);
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. EXPECT_EQ("john", res->body);
  2877. }
  2878. {
  2879. auto res = cli.Get("/user/invalid-user");
  2880. ASSERT_TRUE(res);
  2881. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2882. EXPECT_EQ("error", res->body);
  2883. }
  2884. }
  2885. // The pre-request handler must run before the request body is read, so a
  2886. // rejected request never forces the server to buffer a (potentially large)
  2887. // body. Here the posted body is larger than the payload limit: if the body
  2888. // were read first the server would answer 413, but because the pre-request
  2889. // handler runs first it answers 403 and the body is never read.
  2890. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2891. Server svr;
  2892. svr.set_payload_max_length(8);
  2893. auto handler_ran = false;
  2894. svr.Post("/reject", [&](const Request &req, Response &res) {
  2895. handler_ran = true;
  2896. res.set_content(req.body, "text/plain");
  2897. });
  2898. svr.Post("/accept", [](const Request &req, Response &res) {
  2899. res.set_content(req.body, "text/plain");
  2900. });
  2901. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2902. if (req.matched_route == "/reject") {
  2903. res.status = StatusCode::Forbidden_403;
  2904. res.set_content("denied", "text/plain");
  2905. return Server::HandlerResponse::Handled;
  2906. }
  2907. return Server::HandlerResponse::Unhandled;
  2908. });
  2909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2910. auto se = detail::scope_exit([&] {
  2911. svr.stop();
  2912. thread.join();
  2913. ASSERT_FALSE(svr.is_running());
  2914. });
  2915. svr.wait_until_ready();
  2916. Client cli(HOST, PORT);
  2917. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2918. // rejects with 403 before the body is read, so 413 is never reached.
  2919. {
  2920. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2921. ASSERT_TRUE(res);
  2922. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2923. EXPECT_EQ("denied", res->body);
  2924. EXPECT_FALSE(handler_ran);
  2925. }
  2926. // An approved route still reads the body and enforces the payload limit.
  2927. {
  2928. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2929. ASSERT_TRUE(res);
  2930. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2931. }
  2932. }
  2933. TEST(UserDataTest, BasicOperations) {
  2934. httplib::UserData ud;
  2935. // Initially empty
  2936. EXPECT_FALSE(ud.has("key"));
  2937. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2938. // set and get
  2939. ud.set("key", 42);
  2940. EXPECT_TRUE(ud.has("key"));
  2941. auto *p = ud.get<int>("key");
  2942. ASSERT_NE(nullptr, p);
  2943. EXPECT_EQ(42, *p);
  2944. // Type mismatch → nullptr
  2945. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2946. // Overwrite with different type
  2947. ud.set("key", std::string("hello"));
  2948. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2949. auto *s = ud.get<std::string>("key");
  2950. ASSERT_NE(nullptr, s);
  2951. EXPECT_EQ("hello", *s);
  2952. // erase
  2953. ud.erase("key");
  2954. EXPECT_FALSE(ud.has("key"));
  2955. // clear
  2956. ud.set("a", 1);
  2957. ud.set("b", 2);
  2958. ud.clear();
  2959. EXPECT_FALSE(ud.has("a"));
  2960. EXPECT_FALSE(ud.has("b"));
  2961. }
  2962. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2963. struct AuthCtx {
  2964. std::string user_id;
  2965. };
  2966. Server svr;
  2967. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2968. res.user_data.set("auth", AuthCtx{"alice"});
  2969. return Server::HandlerResponse::Unhandled;
  2970. });
  2971. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2972. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2973. ASSERT_NE(nullptr, ctx);
  2974. res.set_content("Hello " + ctx->user_id, "text/plain");
  2975. });
  2976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2977. auto se = detail::scope_exit([&] {
  2978. svr.stop();
  2979. thread.join();
  2980. ASSERT_FALSE(svr.is_running());
  2981. });
  2982. svr.wait_until_ready();
  2983. Client cli(HOST, PORT);
  2984. auto res = cli.Get("/me");
  2985. ASSERT_TRUE(res);
  2986. EXPECT_EQ(StatusCode::OK_200, res->status);
  2987. EXPECT_EQ("Hello alice", res->body);
  2988. }
  2989. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2990. struct RoleCtx {
  2991. std::string role;
  2992. };
  2993. Server svr;
  2994. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2995. res.user_data.set("role", RoleCtx{"admin"});
  2996. return Server::HandlerResponse::Unhandled;
  2997. });
  2998. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2999. auto *ctx = res.user_data.get<RoleCtx>("role");
  3000. ASSERT_NE(nullptr, ctx);
  3001. res.set_content(ctx->role, "text/plain");
  3002. });
  3003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3004. auto se = detail::scope_exit([&] {
  3005. svr.stop();
  3006. thread.join();
  3007. ASSERT_FALSE(svr.is_running());
  3008. });
  3009. svr.wait_until_ready();
  3010. Client cli(HOST, PORT);
  3011. auto res = cli.Get("/role");
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(StatusCode::OK_200, res->status);
  3014. EXPECT_EQ("admin", res->body);
  3015. }
  3016. TEST(InvalidFormatTest, StatusCode) {
  3017. Server svr;
  3018. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3019. res.set_content("Hello World!\n", "text/plain");
  3020. res.status = 9999; // Status should be a three-digit code...
  3021. });
  3022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3023. auto se = detail::scope_exit([&] {
  3024. svr.stop();
  3025. thread.join();
  3026. ASSERT_FALSE(svr.is_running());
  3027. });
  3028. svr.wait_until_ready();
  3029. {
  3030. Client cli(HOST, PORT);
  3031. auto res = cli.Get("/hi");
  3032. ASSERT_FALSE(res);
  3033. }
  3034. }
  3035. TEST(URLFragmentTest, WithFragment) {
  3036. Server svr;
  3037. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3038. EXPECT_TRUE(req.target == "/hi");
  3039. });
  3040. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3041. auto se = detail::scope_exit([&] {
  3042. svr.stop();
  3043. thread.join();
  3044. ASSERT_FALSE(svr.is_running());
  3045. });
  3046. svr.wait_until_ready();
  3047. {
  3048. Client cli(HOST, PORT);
  3049. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3050. EXPECT_TRUE(res);
  3051. EXPECT_EQ(StatusCode::OK_200, res->status);
  3052. res = cli.Get("/hi%23key1=val1=key2=val2");
  3053. EXPECT_TRUE(res);
  3054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3055. }
  3056. }
  3057. TEST(HeaderWriter, SetHeaderWriter) {
  3058. Server svr;
  3059. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3060. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3061. return detail::write_headers(strm, hdrs);
  3062. });
  3063. svr.Get("/hi", [](const Request &req, Response &res) {
  3064. auto it = req.headers.find("CustomClientHeader");
  3065. EXPECT_TRUE(it != req.headers.end());
  3066. EXPECT_EQ(it->second, "CustomClientValue");
  3067. res.set_content("Hello World!\n", "text/plain");
  3068. });
  3069. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3070. auto se = detail::scope_exit([&] {
  3071. svr.stop();
  3072. thread.join();
  3073. ASSERT_FALSE(svr.is_running());
  3074. });
  3075. svr.wait_until_ready();
  3076. {
  3077. Client cli(HOST, PORT);
  3078. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3079. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3080. return detail::write_headers(strm, hdrs);
  3081. });
  3082. auto res = cli.Get("/hi");
  3083. EXPECT_TRUE(res);
  3084. EXPECT_EQ(StatusCode::OK_200, res->status);
  3085. auto it = res->headers.find("CustomServerHeader");
  3086. EXPECT_TRUE(it != res->headers.end());
  3087. EXPECT_EQ(it->second, "CustomServerValue");
  3088. }
  3089. }
  3090. class ServerTest : public ::testing::Test {
  3091. protected:
  3092. ServerTest()
  3093. : cli_(HOST, PORT)
  3094. #ifdef CPPHTTPLIB_SSL_ENABLED
  3095. ,
  3096. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3097. #endif
  3098. {
  3099. #ifdef CPPHTTPLIB_SSL_ENABLED
  3100. cli_.enable_server_certificate_verification(false);
  3101. #endif
  3102. // Allow LARGE_DATA (100MB) responses
  3103. cli_.set_payload_max_length(200 * 1024 * 1024);
  3104. }
  3105. virtual void SetUp() {
  3106. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3107. svr_.set_payload_max_length(200 * 1024 * 1024);
  3108. svr_.set_mount_point("/", "./www");
  3109. svr_.set_mount_point("/mount", "./www2");
  3110. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3111. svr_.Get("/hi",
  3112. [&](const Request & /*req*/, Response &res) {
  3113. res.set_content("Hello World!", "text/plain");
  3114. })
  3115. .Get("/file_content",
  3116. [&](const Request & /*req*/, Response &res) {
  3117. res.set_file_content("./www/dir/test.html");
  3118. })
  3119. .Get("/file_content_with_content_type",
  3120. [&](const Request & /*req*/, Response &res) {
  3121. res.set_file_content("./www/file", "text/plain");
  3122. })
  3123. .Get("/invalid_file_content",
  3124. [&](const Request & /*req*/, Response &res) {
  3125. res.set_file_content("./www/dir/invalid_file_path");
  3126. })
  3127. .Get("/http_response_splitting",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3130. EXPECT_EQ(0U, res.headers.size());
  3131. EXPECT_FALSE(res.has_header("a"));
  3132. res.set_header("a", "1\nSet-Cookie: a=1");
  3133. EXPECT_EQ(0U, res.headers.size());
  3134. EXPECT_FALSE(res.has_header("a"));
  3135. res.set_header("a", "1\rSet-Cookie: a=1");
  3136. EXPECT_EQ(0U, res.headers.size());
  3137. EXPECT_FALSE(res.has_header("a"));
  3138. res.set_header("a\r\nb", "0");
  3139. EXPECT_EQ(0U, res.headers.size());
  3140. EXPECT_FALSE(res.has_header("a"));
  3141. res.set_header("a\rb", "0");
  3142. EXPECT_EQ(0U, res.headers.size());
  3143. EXPECT_FALSE(res.has_header("a"));
  3144. res.set_header("a\nb", "0");
  3145. EXPECT_EQ(0U, res.headers.size());
  3146. EXPECT_FALSE(res.has_header("a"));
  3147. res.set_redirect("1\r\nSet-Cookie: a=1");
  3148. EXPECT_EQ(0U, res.headers.size());
  3149. EXPECT_FALSE(res.has_header("Location"));
  3150. })
  3151. .Get("/slow",
  3152. [&](const Request & /*req*/, Response &res) {
  3153. std::this_thread::sleep_for(std::chrono::seconds(4));
  3154. res.set_content("slow", "text/plain");
  3155. })
  3156. #if 0
  3157. .Post("/slowpost",
  3158. [&](const Request & /*req*/, Response &res) {
  3159. std::this_thread::sleep_for(std::chrono::seconds(2));
  3160. res.set_content("slow", "text/plain");
  3161. })
  3162. #endif
  3163. .Get("/remote_addr",
  3164. [&](const Request &req, Response &res) {
  3165. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3166. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3167. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3168. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3169. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3170. #endif
  3171. res.set_content(req.remote_addr, "text/plain");
  3172. })
  3173. .Get("/local_addr",
  3174. [&](const Request &req, Response &res) {
  3175. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3176. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3177. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3178. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3179. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3180. #endif
  3181. auto local_addr = req.local_addr;
  3182. auto local_port = std::to_string(req.local_port);
  3183. res.set_content(local_addr.append(":").append(local_port),
  3184. "text/plain");
  3185. })
  3186. .Get("/endwith%",
  3187. [&](const Request & /*req*/, Response &res) {
  3188. res.set_content("Hello World!", "text/plain");
  3189. })
  3190. .Get("/a\\+\\+b",
  3191. [&](const Request &req, Response &res) {
  3192. ASSERT_TRUE(req.has_param("a +b"));
  3193. auto val = req.get_param_value("a +b");
  3194. res.set_content(val, "text/plain");
  3195. })
  3196. .Get("/", [&](const Request & /*req*/,
  3197. Response &res) { res.set_redirect("/hi"); })
  3198. .Post("/1",
  3199. [](const Request & /*req*/, Response &res) {
  3200. res.set_redirect("/2", StatusCode::SeeOther_303);
  3201. })
  3202. .Get("/2",
  3203. [](const Request & /*req*/, Response &res) {
  3204. res.set_content("redirected.", "text/plain");
  3205. res.status = StatusCode::OK_200;
  3206. })
  3207. .Post("/person",
  3208. [&](const Request &req, Response &res) {
  3209. if (req.has_param("name") && req.has_param("note")) {
  3210. persons_[req.get_param_value("name")] =
  3211. req.get_param_value("note");
  3212. } else {
  3213. res.status = StatusCode::BadRequest_400;
  3214. }
  3215. })
  3216. .Put("/person",
  3217. [&](const Request &req, Response &res) {
  3218. if (req.has_param("name") && req.has_param("note")) {
  3219. persons_[req.get_param_value("name")] =
  3220. req.get_param_value("note");
  3221. } else {
  3222. res.status = StatusCode::BadRequest_400;
  3223. }
  3224. })
  3225. .Get("/person/(.*)",
  3226. [&](const Request &req, Response &res) {
  3227. string name = req.matches[1];
  3228. if (persons_.find(name) != persons_.end()) {
  3229. auto note = persons_[name];
  3230. res.set_content(note, "text/plain");
  3231. } else {
  3232. res.status = StatusCode::NotFound_404;
  3233. }
  3234. })
  3235. .Delete("/person",
  3236. [&](const Request &req, Response &res) {
  3237. if (req.has_param("name")) {
  3238. string name = req.get_param_value("name");
  3239. if (persons_.find(name) != persons_.end()) {
  3240. persons_.erase(name);
  3241. res.set_content("DELETED", "text/plain");
  3242. } else {
  3243. res.status = StatusCode::NotFound_404;
  3244. }
  3245. } else {
  3246. res.status = StatusCode::BadRequest_400;
  3247. }
  3248. })
  3249. .Post("/x-www-form-urlencoded-json",
  3250. [&](const Request &req, Response &res) {
  3251. auto json = req.get_param_value("json");
  3252. ASSERT_EQ(JSON_DATA, json);
  3253. res.set_content(json, "appliation/json");
  3254. res.status = StatusCode::OK_200;
  3255. })
  3256. .Get("/streamed-chunked",
  3257. [&](const Request & /*req*/, Response &res) {
  3258. res.set_chunked_content_provider(
  3259. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3260. sink.os << "123";
  3261. sink.os << "456";
  3262. sink.os << "789";
  3263. sink.done();
  3264. return true;
  3265. });
  3266. })
  3267. .Get("/streamed-chunked-with-prohibited-trailer",
  3268. [&](const Request & /*req*/, Response &res) {
  3269. auto i = new int(0);
  3270. // Declare both a prohibited trailer (Content-Length) and an
  3271. // allowed one
  3272. res.set_header("Trailer", "Content-Length, X-Allowed");
  3273. res.set_chunked_content_provider(
  3274. "text/plain",
  3275. [i](size_t /*offset*/, DataSink &sink) {
  3276. switch (*i) {
  3277. case 0: sink.os << "123"; break;
  3278. case 1: sink.os << "456"; break;
  3279. case 2: sink.os << "789"; break;
  3280. case 3: {
  3281. sink.done_with_trailer(
  3282. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3283. } break;
  3284. }
  3285. (*i)++;
  3286. return true;
  3287. },
  3288. [i](bool success) {
  3289. EXPECT_TRUE(success);
  3290. delete i;
  3291. });
  3292. })
  3293. .Get("/streamed-chunked2",
  3294. [&](const Request & /*req*/, Response &res) {
  3295. auto i = new int(0);
  3296. res.set_chunked_content_provider(
  3297. "text/plain",
  3298. [i](size_t /*offset*/, DataSink &sink) {
  3299. switch (*i) {
  3300. case 0: sink.os << "123"; break;
  3301. case 1: sink.os << "456"; break;
  3302. case 2: sink.os << "789"; break;
  3303. case 3: sink.done(); break;
  3304. }
  3305. (*i)++;
  3306. return true;
  3307. },
  3308. [i](bool success) {
  3309. EXPECT_TRUE(success);
  3310. delete i;
  3311. });
  3312. })
  3313. .Get("/streamed-chunked-with-trailer",
  3314. [&](const Request & /*req*/, Response &res) {
  3315. auto i = new int(0);
  3316. res.set_header("Trailer", "Dummy1, Dummy2");
  3317. res.set_chunked_content_provider(
  3318. "text/plain",
  3319. [i](size_t /*offset*/, DataSink &sink) {
  3320. switch (*i) {
  3321. case 0: sink.os << "123"; break;
  3322. case 1: sink.os << "456"; break;
  3323. case 2: sink.os << "789"; break;
  3324. case 3: {
  3325. sink.done_with_trailer(
  3326. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3327. } break;
  3328. }
  3329. (*i)++;
  3330. return true;
  3331. },
  3332. [i](bool success) {
  3333. EXPECT_TRUE(success);
  3334. delete i;
  3335. });
  3336. })
  3337. .Get("/streamed",
  3338. [&](const Request & /*req*/, Response &res) {
  3339. res.set_content_provider(
  3340. 6, "text/plain",
  3341. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3342. sink.os << (offset < 3 ? "a" : "b");
  3343. return true;
  3344. });
  3345. })
  3346. .Get("/streamed-without-length",
  3347. [&](const Request & /*req*/, Response &res) {
  3348. auto data = new std::string("abcdefg");
  3349. res.set_content_provider(
  3350. "text/plain",
  3351. [data](size_t offset, DataSink &sink) {
  3352. if (offset < data->size()) {
  3353. sink.os << data->substr(offset);
  3354. }
  3355. sink.done();
  3356. return true;
  3357. },
  3358. [data](bool success) {
  3359. EXPECT_TRUE(success);
  3360. delete data;
  3361. });
  3362. })
  3363. .Get("/streamed-with-range",
  3364. [&](const Request &req, Response &res) {
  3365. auto data = new std::string("abcdefg");
  3366. res.set_content_provider(
  3367. data->size(), "text/plain",
  3368. [data](size_t offset, size_t length, DataSink &sink) {
  3369. size_t DATA_CHUNK_SIZE = 4;
  3370. const auto &d = *data;
  3371. auto out_len =
  3372. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3373. auto ret =
  3374. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3375. EXPECT_TRUE(ret);
  3376. return true;
  3377. },
  3378. [data, &req](bool success) {
  3379. EXPECT_EQ(success, !req.has_param("error"));
  3380. delete data;
  3381. });
  3382. })
  3383. .Get("/streamed-cancel",
  3384. [&](const Request & /*req*/, Response &res) {
  3385. res.set_content_provider(
  3386. size_t(-1), "text/plain",
  3387. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3388. sink.os << "data_chunk";
  3389. return true;
  3390. });
  3391. })
  3392. .Get("/regex-with-delimiter",
  3393. [&](const Request &req, Response & /*res*/) {
  3394. ASSERT_TRUE(req.has_param("key"));
  3395. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3396. })
  3397. .Get("/with-range",
  3398. [&](const Request & /*req*/, Response &res) {
  3399. res.set_content("abcdefg", "text/plain");
  3400. })
  3401. .Get("/test-start-time",
  3402. [&](const Request &req, Response & /*res*/) {
  3403. EXPECT_NE(req.start_time_,
  3404. std::chrono::steady_clock::time_point::min());
  3405. })
  3406. .Get("/with-range-customized-response",
  3407. [&](const Request & /*req*/, Response &res) {
  3408. res.status = StatusCode::BadRequest_400;
  3409. res.set_content(JSON_DATA, "application/json");
  3410. })
  3411. .Post("/chunked",
  3412. [&](const Request &req, Response & /*res*/) {
  3413. EXPECT_EQ(req.body, "dechunked post body");
  3414. })
  3415. .Post("/large-chunked",
  3416. [&](const Request &req, Response & /*res*/) {
  3417. std::string expected(6 * 30 * 1024u, 'a');
  3418. EXPECT_EQ(req.body, expected);
  3419. })
  3420. .Post("/multipart",
  3421. [&](const Request &req, Response & /*res*/) {
  3422. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3423. req.form.get_field_count("text2") +
  3424. req.form.get_field_count("file3") +
  3425. req.form.get_field_count("file4"));
  3426. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3427. req.form.get_file_count("file2"));
  3428. ASSERT_TRUE(!req.form.has_file("???"));
  3429. ASSERT_TRUE(!req.form.has_field("???"));
  3430. ASSERT_TRUE(req.body.empty());
  3431. {
  3432. const auto &text = req.form.get_field("text1");
  3433. EXPECT_EQ("text default", text);
  3434. }
  3435. {
  3436. const auto &text = req.form.get_field("text2");
  3437. EXPECT_EQ("aωb", text);
  3438. }
  3439. {
  3440. const auto &file = req.form.get_file("file1");
  3441. EXPECT_EQ("hello.txt", file.filename);
  3442. EXPECT_EQ("text/plain", file.content_type);
  3443. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3444. }
  3445. {
  3446. const auto &file = req.form.get_file("file2");
  3447. EXPECT_EQ("world.json", file.filename);
  3448. EXPECT_EQ("application/json", file.content_type);
  3449. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3450. }
  3451. {
  3452. const auto &text = req.form.get_field("file3");
  3453. EXPECT_EQ(0u, text.size());
  3454. }
  3455. {
  3456. const auto &text = req.form.get_field("file4");
  3457. EXPECT_EQ(0u, text.size());
  3458. }
  3459. })
  3460. .Post("/multipart/multi_file_values",
  3461. [&](const Request &req, Response & /*res*/) {
  3462. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3463. req.form.get_field_count("multi_text1"));
  3464. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3465. ASSERT_TRUE(!req.form.has_file("???"));
  3466. ASSERT_TRUE(!req.form.has_field("???"));
  3467. ASSERT_TRUE(req.body.empty());
  3468. {
  3469. const auto &text = req.form.get_field("text");
  3470. EXPECT_EQ("default text", text);
  3471. }
  3472. {
  3473. const auto &text1_values = req.form.get_fields("multi_text1");
  3474. EXPECT_EQ(2u, text1_values.size());
  3475. EXPECT_EQ("aaaaa", text1_values[0]);
  3476. EXPECT_EQ("bbbbb", text1_values[1]);
  3477. }
  3478. {
  3479. const auto &file1_values = req.form.get_files("multi_file1");
  3480. EXPECT_EQ(2u, file1_values.size());
  3481. auto file1 = file1_values[0];
  3482. EXPECT_EQ(file1.filename, "hello.txt");
  3483. EXPECT_EQ(file1.content_type, "text/plain");
  3484. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3485. auto file2 = file1_values[1];
  3486. EXPECT_EQ(file2.filename, "world.json");
  3487. EXPECT_EQ(file2.content_type, "application/json");
  3488. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3489. }
  3490. })
  3491. .Post("/empty",
  3492. [&](const Request &req, Response &res) {
  3493. EXPECT_EQ(req.body, "");
  3494. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3495. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3496. res.set_content("empty", "text/plain");
  3497. })
  3498. .Post("/empty-no-content-type",
  3499. [&](const Request &req, Response &res) {
  3500. EXPECT_EQ(req.body, "");
  3501. EXPECT_FALSE(req.has_header("Content-Type"));
  3502. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3503. res.set_content("empty-no-content-type", "text/plain");
  3504. })
  3505. .Post("/path-only",
  3506. [&](const Request &req, Response &res) {
  3507. EXPECT_EQ(req.body, "");
  3508. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3509. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3510. res.set_content("path-only", "text/plain");
  3511. })
  3512. .Post("/path-headers-only",
  3513. [&](const Request &req, Response &res) {
  3514. EXPECT_EQ(req.body, "");
  3515. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3516. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3517. EXPECT_EQ("world", req.get_header_value("hello"));
  3518. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3519. res.set_content("path-headers-only", "text/plain");
  3520. })
  3521. .Post("/post-large",
  3522. [&](const Request &req, Response &res) {
  3523. EXPECT_EQ(req.body, LARGE_DATA);
  3524. res.set_content(req.body, "text/plain");
  3525. })
  3526. .Post("/post-loopback",
  3527. [&](const Request &, Response &res,
  3528. ContentReader const &content_reader) {
  3529. std::string body;
  3530. content_reader([&](const char *data, size_t data_length) {
  3531. body.append(data, data_length);
  3532. return true;
  3533. });
  3534. res.set_content(body, "text/plain");
  3535. })
  3536. .Put("/put-loopback",
  3537. [&](const Request &, Response &res,
  3538. ContentReader const &content_reader) {
  3539. std::string body;
  3540. content_reader([&](const char *data, size_t data_length) {
  3541. body.append(data, data_length);
  3542. return true;
  3543. });
  3544. res.set_content(body, "text/plain");
  3545. })
  3546. .Patch("/patch-loopback",
  3547. [&](const Request &, Response &res,
  3548. ContentReader const &content_reader) {
  3549. std::string body;
  3550. content_reader([&](const char *data, size_t data_length) {
  3551. body.append(data, data_length);
  3552. return true;
  3553. });
  3554. res.set_content(body, "text/plain");
  3555. })
  3556. .Put("/empty-no-content-type",
  3557. [&](const Request &req, Response &res) {
  3558. EXPECT_EQ(req.body, "");
  3559. EXPECT_FALSE(req.has_header("Content-Type"));
  3560. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3561. res.set_content("empty-no-content-type", "text/plain");
  3562. })
  3563. .Put("/put",
  3564. [&](const Request &req, Response &res) {
  3565. EXPECT_EQ(req.body, "PUT");
  3566. res.set_content(req.body, "text/plain");
  3567. })
  3568. .Put("/put-large",
  3569. [&](const Request &req, Response &res) {
  3570. EXPECT_EQ(req.body, LARGE_DATA);
  3571. res.set_content(req.body, "text/plain");
  3572. })
  3573. .Patch("/patch",
  3574. [&](const Request &req, Response &res) {
  3575. EXPECT_EQ(req.body, "PATCH");
  3576. res.set_content(req.body, "text/plain");
  3577. })
  3578. .Delete("/delete",
  3579. [&](const Request & /*req*/, Response &res) {
  3580. res.set_content("DELETE", "text/plain");
  3581. })
  3582. .Delete("/delete-body",
  3583. [&](const Request &req, Response &res) {
  3584. EXPECT_EQ(req.body, "content");
  3585. res.set_content(req.body, "text/plain");
  3586. })
  3587. .Options(R"(\*)",
  3588. [&](const Request & /*req*/, Response &res) {
  3589. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3590. })
  3591. .Get("/request-target",
  3592. [&](const Request &req, Response & /*res*/) {
  3593. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3594. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3595. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3596. })
  3597. .Get("/long-query-value",
  3598. [&](const Request &req, Response & /*res*/) {
  3599. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3600. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3601. })
  3602. .Get("/too-long-query-value",
  3603. [&](const Request &req, Response & /*res*/) {
  3604. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3605. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3606. })
  3607. .Get("/array-param",
  3608. [&](const Request &req, Response & /*res*/) {
  3609. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3610. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3611. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3612. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3613. })
  3614. .Get("/array-param-values",
  3615. [&](const Request &req, Response & /*res*/) {
  3616. auto values = req.get_param_values("array");
  3617. EXPECT_EQ(3u, values.size());
  3618. EXPECT_EQ("value1", values[0]);
  3619. EXPECT_EQ("value2", values[1]);
  3620. EXPECT_EQ("value3", values[2]);
  3621. auto empty = req.get_param_values("nonexistent");
  3622. EXPECT_TRUE(empty.empty());
  3623. })
  3624. .Post("/validate-no-multiple-headers",
  3625. [&](const Request &req, Response & /*res*/) {
  3626. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3627. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3628. })
  3629. .Post("/content_receiver",
  3630. [&](const Request &req, Response &res,
  3631. const ContentReader &content_reader) {
  3632. if (req.is_multipart_form_data()) {
  3633. std::vector<FormData> items;
  3634. content_reader(
  3635. [&](const FormData &file) {
  3636. items.push_back(file);
  3637. return true;
  3638. },
  3639. [&](const char *data, size_t data_length) {
  3640. items.back().content.append(data, data_length);
  3641. return true;
  3642. });
  3643. EXPECT_EQ(5u, items.size());
  3644. {
  3645. const auto &file = get_file_value(items, "text1");
  3646. EXPECT_TRUE(file.filename.empty());
  3647. EXPECT_EQ("text default", file.content);
  3648. }
  3649. {
  3650. const auto &file = get_file_value(items, "text2");
  3651. EXPECT_TRUE(file.filename.empty());
  3652. EXPECT_EQ("aωb", file.content);
  3653. }
  3654. {
  3655. const auto &file = get_file_value(items, "file1");
  3656. EXPECT_EQ("hello.txt", file.filename);
  3657. EXPECT_EQ("text/plain", file.content_type);
  3658. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3659. }
  3660. {
  3661. const auto &file = get_file_value(items, "file2");
  3662. EXPECT_EQ("world.json", file.filename);
  3663. EXPECT_EQ("application/json", file.content_type);
  3664. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3665. }
  3666. {
  3667. const auto &file = get_file_value(items, "file3");
  3668. EXPECT_TRUE(file.filename.empty());
  3669. EXPECT_EQ("application/octet-stream", file.content_type);
  3670. EXPECT_EQ(0u, file.content.size());
  3671. }
  3672. } else {
  3673. std::string body;
  3674. content_reader([&](const char *data, size_t data_length) {
  3675. EXPECT_EQ(7U, data_length);
  3676. body.append(data, data_length);
  3677. return true;
  3678. });
  3679. EXPECT_EQ(body, "content");
  3680. res.set_content(body, "text/plain");
  3681. }
  3682. })
  3683. .Put("/content_receiver",
  3684. [&](const Request & /*req*/, Response &res,
  3685. const ContentReader &content_reader) {
  3686. std::string body;
  3687. content_reader([&](const char *data, size_t data_length) {
  3688. body.append(data, data_length);
  3689. return true;
  3690. });
  3691. EXPECT_EQ(body, "content");
  3692. res.set_content(body, "text/plain");
  3693. })
  3694. .Patch("/content_receiver",
  3695. [&](const Request & /*req*/, Response &res,
  3696. const ContentReader &content_reader) {
  3697. std::string body;
  3698. content_reader([&](const char *data, size_t data_length) {
  3699. body.append(data, data_length);
  3700. return true;
  3701. });
  3702. EXPECT_EQ(body, "content");
  3703. res.set_content(body, "text/plain");
  3704. })
  3705. .Post("/query-string-and-body",
  3706. [&](const Request &req, Response & /*res*/) {
  3707. ASSERT_TRUE(req.has_param("key"));
  3708. EXPECT_EQ(req.get_param_value("key"), "value");
  3709. EXPECT_EQ(req.body, "content");
  3710. })
  3711. .Get("/last-request",
  3712. [&](const Request &req, Response & /*res*/) {
  3713. EXPECT_EQ("close", req.get_header_value("Connection"));
  3714. })
  3715. .Get(R"(/redirect/(\d+))",
  3716. [&](const Request &req, Response &res) {
  3717. auto num = std::stoi(req.matches[1]) + 1;
  3718. std::string url = "/redirect/" + std::to_string(num);
  3719. res.set_redirect(url);
  3720. })
  3721. .Post("/binary",
  3722. [&](const Request &req, Response &res) {
  3723. EXPECT_EQ(4U, req.body.size());
  3724. EXPECT_EQ("application/octet-stream",
  3725. req.get_header_value("Content-Type"));
  3726. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3727. res.set_content(req.body, "application/octet-stream");
  3728. })
  3729. .Put("/binary",
  3730. [&](const Request &req, Response &res) {
  3731. EXPECT_EQ(4U, req.body.size());
  3732. EXPECT_EQ("application/octet-stream",
  3733. req.get_header_value("Content-Type"));
  3734. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3735. res.set_content(req.body, "application/octet-stream");
  3736. })
  3737. .Patch("/binary",
  3738. [&](const Request &req, Response &res) {
  3739. EXPECT_EQ(4U, req.body.size());
  3740. EXPECT_EQ("application/octet-stream",
  3741. req.get_header_value("Content-Type"));
  3742. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3743. res.set_content(req.body, "application/octet-stream");
  3744. })
  3745. .Delete("/binary",
  3746. [&](const Request &req, Response &res) {
  3747. EXPECT_EQ(4U, req.body.size());
  3748. EXPECT_EQ("application/octet-stream",
  3749. req.get_header_value("Content-Type"));
  3750. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3751. res.set_content(req.body, "application/octet-stream");
  3752. })
  3753. .Get("/issue1772",
  3754. [&](const Request & /*req*/, Response &res) {
  3755. res.status = 401;
  3756. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3757. })
  3758. .Delete("/issue609",
  3759. [](const httplib::Request &, httplib::Response &res,
  3760. const httplib::ContentReader &) {
  3761. res.set_content("ok", "text/plain");
  3762. })
  3763. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3764. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3765. .Get("/compress",
  3766. [&](const Request & /*req*/, Response &res) {
  3767. res.set_content(
  3768. "12345678901234567890123456789012345678901234567890123456789"
  3769. "01234567890123456789012345678901234567890",
  3770. "text/plain");
  3771. })
  3772. .Get("/compress-with-charset",
  3773. [&](const Request & /*req*/, Response &res) {
  3774. res.set_content(
  3775. "12345678901234567890123456789012345678901234567890123456789"
  3776. "01234567890123456789012345678901234567890",
  3777. "application/json; charset=utf-8");
  3778. })
  3779. .Get("/nocompress",
  3780. [&](const Request & /*req*/, Response &res) {
  3781. res.set_content(
  3782. "12345678901234567890123456789012345678901234567890123456789"
  3783. "01234567890123456789012345678901234567890",
  3784. "application/octet-stream");
  3785. })
  3786. .Post("/compress-multipart",
  3787. [&](const Request &req, Response & /*res*/) {
  3788. EXPECT_EQ(2u, req.form.fields.size());
  3789. ASSERT_TRUE(!req.form.has_field("???"));
  3790. {
  3791. const auto &text = req.form.get_field("key1");
  3792. EXPECT_EQ("test", text);
  3793. }
  3794. {
  3795. const auto &text = req.form.get_field("key2");
  3796. EXPECT_EQ("--abcdefg123", text);
  3797. }
  3798. })
  3799. #endif
  3800. ;
  3801. persons_["john"] = "programmer";
  3802. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3803. svr_.wait_until_ready();
  3804. }
  3805. virtual void TearDown() {
  3806. svr_.stop();
  3807. if (!request_threads_.empty()) {
  3808. std::this_thread::sleep_for(std::chrono::seconds(1));
  3809. for (auto &t : request_threads_) {
  3810. t.join();
  3811. }
  3812. }
  3813. t_.join();
  3814. }
  3815. map<string, string> persons_;
  3816. #ifdef CPPHTTPLIB_SSL_ENABLED
  3817. SSLClient cli_;
  3818. SSLServer svr_;
  3819. #else
  3820. Client cli_;
  3821. Server svr_;
  3822. #endif
  3823. thread t_;
  3824. std::vector<thread> request_threads_;
  3825. };
  3826. TEST_F(ServerTest, GetMethod200) {
  3827. auto res = cli_.Get("/hi");
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ("HTTP/1.1", res->version);
  3830. EXPECT_EQ(StatusCode::OK_200, res->status);
  3831. EXPECT_EQ("OK", res->reason);
  3832. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3833. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3834. EXPECT_EQ("Hello World!", res->body);
  3835. }
  3836. TEST_F(ServerTest, GetEmptyFile) {
  3837. auto res = cli_.Get("/empty_file");
  3838. ASSERT_TRUE(res);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3841. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3842. EXPECT_EQ("", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetFileContent) {
  3845. auto res = cli_.Get("/file_content");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3850. EXPECT_EQ("test.html", res->body);
  3851. }
  3852. TEST_F(ServerTest, GetFileContentWithRange) {
  3853. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3854. ASSERT_TRUE(res);
  3855. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3856. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3857. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3858. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3859. EXPECT_EQ("est", res->body);
  3860. }
  3861. TEST_F(ServerTest, GetFileContentWithContentType) {
  3862. auto res = cli_.Get("/file_content_with_content_type");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3866. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3867. EXPECT_EQ("file\n", res->body);
  3868. }
  3869. TEST_F(ServerTest, GetInvalidFileContent) {
  3870. auto res = cli_.Get("/invalid_file_content");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3873. }
  3874. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3875. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3876. ASSERT_TRUE(res);
  3877. EXPECT_EQ("HTTP/1.1", res->version);
  3878. EXPECT_EQ(StatusCode::OK_200, res->status);
  3879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3880. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3881. EXPECT_EQ("Hello World!", res->body);
  3882. }
  3883. TEST_F(ServerTest, GetMethod302) {
  3884. auto res = cli_.Get("/");
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::Found_302, res->status);
  3887. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3888. }
  3889. TEST_F(ServerTest, GetMethod302Redirect) {
  3890. cli_.set_follow_location(true);
  3891. auto res = cli_.Get("/");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. EXPECT_EQ("Hello World!", res->body);
  3895. EXPECT_EQ("/hi", res->location);
  3896. }
  3897. TEST_F(ServerTest, GetMethod404) {
  3898. auto res = cli_.Get("/invalid");
  3899. ASSERT_TRUE(res);
  3900. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3901. }
  3902. TEST_F(ServerTest, HeadMethod200) {
  3903. auto res = cli_.Head("/hi");
  3904. ASSERT_TRUE(res);
  3905. EXPECT_EQ(StatusCode::OK_200, res->status);
  3906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3907. EXPECT_TRUE(res->body.empty());
  3908. }
  3909. TEST_F(ServerTest, HeadMethod200Static) {
  3910. auto res = cli_.Head("/mount/dir/index.html");
  3911. ASSERT_TRUE(res);
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3914. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3915. EXPECT_TRUE(res->body.empty());
  3916. }
  3917. TEST_F(ServerTest, HeadMethod404) {
  3918. auto res = cli_.Head("/invalid");
  3919. ASSERT_TRUE(res);
  3920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3921. EXPECT_TRUE(res->body.empty());
  3922. }
  3923. TEST_F(ServerTest, GetMethodPersonJohn) {
  3924. auto res = cli_.Get("/person/john");
  3925. ASSERT_TRUE(res);
  3926. EXPECT_EQ(StatusCode::OK_200, res->status);
  3927. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3928. EXPECT_EQ("programmer", res->body);
  3929. }
  3930. TEST_F(ServerTest, PostMethod1) {
  3931. auto res = cli_.Get("/person/john1");
  3932. ASSERT_TRUE(res);
  3933. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3934. res = cli_.Post("/person", "name=john1&note=coder",
  3935. "application/x-www-form-urlencoded");
  3936. ASSERT_TRUE(res);
  3937. ASSERT_EQ(StatusCode::OK_200, res->status);
  3938. res = cli_.Get("/person/john1");
  3939. ASSERT_TRUE(res);
  3940. ASSERT_EQ(StatusCode::OK_200, res->status);
  3941. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3942. ASSERT_EQ("coder", res->body);
  3943. }
  3944. TEST_F(ServerTest, PostMethod2) {
  3945. auto res = cli_.Get("/person/john2");
  3946. ASSERT_TRUE(res);
  3947. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3948. Params params;
  3949. params.emplace("name", "john2");
  3950. params.emplace("note", "coder");
  3951. res = cli_.Post("/person", params);
  3952. ASSERT_TRUE(res);
  3953. ASSERT_EQ(StatusCode::OK_200, res->status);
  3954. res = cli_.Get("/person/john2");
  3955. ASSERT_TRUE(res);
  3956. ASSERT_EQ(StatusCode::OK_200, res->status);
  3957. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3958. ASSERT_EQ("coder", res->body);
  3959. }
  3960. TEST_F(ServerTest, PutMethod3) {
  3961. auto res = cli_.Get("/person/john3");
  3962. ASSERT_TRUE(res);
  3963. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3964. Params params;
  3965. params.emplace("name", "john3");
  3966. params.emplace("note", "coder");
  3967. res = cli_.Put("/person", params);
  3968. ASSERT_TRUE(res);
  3969. ASSERT_EQ(StatusCode::OK_200, res->status);
  3970. res = cli_.Get("/person/john3");
  3971. ASSERT_TRUE(res);
  3972. ASSERT_EQ(StatusCode::OK_200, res->status);
  3973. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3974. ASSERT_EQ("coder", res->body);
  3975. }
  3976. TEST_F(ServerTest, DeleteMethod1) {
  3977. auto res = cli_.Get("/person/john4");
  3978. ASSERT_TRUE(res);
  3979. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3980. Params params;
  3981. params.emplace("name", "john4");
  3982. params.emplace("note", "coder");
  3983. res = cli_.Post("/person", params);
  3984. ASSERT_TRUE(res);
  3985. ASSERT_EQ(StatusCode::OK_200, res->status);
  3986. res = cli_.Get("/person/john4");
  3987. ASSERT_TRUE(res);
  3988. ASSERT_EQ(StatusCode::OK_200, res->status);
  3989. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3990. ASSERT_EQ("coder", res->body);
  3991. Params delete_params;
  3992. delete_params.emplace("name", "john4");
  3993. res = cli_.Delete("/person", delete_params);
  3994. ASSERT_TRUE(res);
  3995. ASSERT_EQ(StatusCode::OK_200, res->status);
  3996. ASSERT_EQ("DELETED", res->body);
  3997. res = cli_.Get("/person/john4");
  3998. ASSERT_TRUE(res);
  3999. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4000. }
  4001. TEST_F(ServerTest, DeleteMethod2) {
  4002. auto res = cli_.Get("/person/john5");
  4003. ASSERT_TRUE(res);
  4004. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4005. Params params;
  4006. params.emplace("name", "john5");
  4007. params.emplace("note", "developer");
  4008. res = cli_.Post("/person", params);
  4009. ASSERT_TRUE(res);
  4010. ASSERT_EQ(StatusCode::OK_200, res->status);
  4011. res = cli_.Get("/person/john5");
  4012. ASSERT_TRUE(res);
  4013. ASSERT_EQ(StatusCode::OK_200, res->status);
  4014. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4015. ASSERT_EQ("developer", res->body);
  4016. Params delete_params;
  4017. delete_params.emplace("name", "john5");
  4018. Headers headers;
  4019. headers.emplace("Custom-Header", "test-value");
  4020. res = cli_.Delete("/person", headers, delete_params);
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ("DELETED", res->body);
  4024. res = cli_.Get("/person/john5");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4027. }
  4028. TEST_F(ServerTest, DeleteMethod3) {
  4029. auto res = cli_.Get("/person/john6");
  4030. ASSERT_TRUE(res);
  4031. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4032. Params params;
  4033. params.emplace("name", "john6");
  4034. params.emplace("note", "tester");
  4035. res = cli_.Post("/person", params);
  4036. ASSERT_TRUE(res);
  4037. ASSERT_EQ(StatusCode::OK_200, res->status);
  4038. res = cli_.Get("/person/john6");
  4039. ASSERT_TRUE(res);
  4040. ASSERT_EQ(StatusCode::OK_200, res->status);
  4041. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4042. ASSERT_EQ("tester", res->body);
  4043. Params delete_params;
  4044. delete_params.emplace("name", "john6");
  4045. Headers headers;
  4046. headers.emplace("Custom-Header", "test-value");
  4047. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4048. ASSERT_TRUE(res);
  4049. ASSERT_EQ(StatusCode::OK_200, res->status);
  4050. ASSERT_EQ("DELETED", res->body);
  4051. res = cli_.Get("/person/john6");
  4052. ASSERT_TRUE(res);
  4053. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4054. }
  4055. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4056. Params params;
  4057. params.emplace("json", JSON_DATA);
  4058. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4059. ASSERT_TRUE(res);
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_EQ(JSON_DATA, res->body);
  4062. }
  4063. TEST_F(ServerTest, PostEmptyContent) {
  4064. auto res = cli_.Post("/empty", "", "text/plain");
  4065. ASSERT_TRUE(res);
  4066. ASSERT_EQ(StatusCode::OK_200, res->status);
  4067. ASSERT_EQ("empty", res->body);
  4068. }
  4069. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4070. auto res = cli_.Post("/empty-no-content-type");
  4071. ASSERT_TRUE(res);
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_EQ("empty-no-content-type", res->body);
  4074. }
  4075. TEST_F(ServerTest, PostPathOnly) {
  4076. auto res = cli_.Post("/path-only");
  4077. ASSERT_TRUE(res);
  4078. ASSERT_EQ(StatusCode::OK_200, res->status);
  4079. ASSERT_EQ("path-only", res->body);
  4080. }
  4081. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4082. auto res = cli_.Post("/path-headers-only",
  4083. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4084. ASSERT_TRUE(res);
  4085. ASSERT_EQ(StatusCode::OK_200, res->status);
  4086. ASSERT_EQ("path-headers-only", res->body);
  4087. }
  4088. TEST_F(ServerTest, PostLarge) {
  4089. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4090. ASSERT_TRUE(res);
  4091. ASSERT_EQ(StatusCode::OK_200, res->status);
  4092. EXPECT_EQ(LARGE_DATA, res->body);
  4093. }
  4094. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4095. auto res = cli_.Put("/empty-no-content-type");
  4096. ASSERT_TRUE(res);
  4097. ASSERT_EQ(StatusCode::OK_200, res->status);
  4098. ASSERT_EQ("empty-no-content-type", res->body);
  4099. }
  4100. TEST_F(ServerTest, GetMethodDir) {
  4101. auto res = cli_.Get("/dir/");
  4102. ASSERT_TRUE(res);
  4103. EXPECT_EQ(StatusCode::OK_200, res->status);
  4104. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4105. auto body = R"(<html>
  4106. <head>
  4107. </head>
  4108. <body>
  4109. <a href="/dir/test.html">Test</a>
  4110. <a href="/hi">hi</a>
  4111. </body>
  4112. </html>
  4113. )";
  4114. EXPECT_EQ(body, res->body);
  4115. }
  4116. TEST_F(ServerTest, GetMethodDirTest) {
  4117. auto res = cli_.Get("/dir/test.html");
  4118. ASSERT_TRUE(res);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4121. EXPECT_EQ("test.html", res->body);
  4122. }
  4123. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4124. auto res = cli_.Get("/dir/../dir/test.html");
  4125. ASSERT_TRUE(res);
  4126. EXPECT_EQ(StatusCode::OK_200, res->status);
  4127. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4128. EXPECT_EQ("test.html", res->body);
  4129. }
  4130. TEST_F(ServerTest, GetMethodInvalidPath) {
  4131. auto res = cli_.Get("/dir/../test.html");
  4132. ASSERT_TRUE(res);
  4133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4134. }
  4135. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4136. auto res = cli_.Get("/../www/dir/test.html");
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4139. }
  4140. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4141. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4142. ASSERT_TRUE(res);
  4143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4144. }
  4145. TEST_F(ServerTest, GetMethodDirMountTest) {
  4146. auto res = cli_.Get("/mount/dir/test.html");
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::OK_200, res->status);
  4149. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4150. EXPECT_EQ("test.html", res->body);
  4151. }
  4152. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4153. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4154. ASSERT_TRUE(res);
  4155. EXPECT_EQ(StatusCode::OK_200, res->status);
  4156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4157. EXPECT_EQ("test.html", res->body);
  4158. }
  4159. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4160. auto res = cli_.Get("/mount/dir/../test.html");
  4161. ASSERT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4163. }
  4164. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4165. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4166. ASSERT_TRUE(res);
  4167. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4168. }
  4169. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4170. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4171. ASSERT_TRUE(res);
  4172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4173. }
  4174. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4175. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4178. }
  4179. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4180. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4183. }
  4184. TEST_F(ServerTest, PostMethod303) {
  4185. auto res = cli_.Post("/1", "body", "text/plain");
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4188. EXPECT_EQ("/2", res->get_header_value("Location"));
  4189. }
  4190. TEST_F(ServerTest, PostMethod303Redirect) {
  4191. cli_.set_follow_location(true);
  4192. auto res = cli_.Post("/1", "body", "text/plain");
  4193. ASSERT_TRUE(res);
  4194. EXPECT_EQ(StatusCode::OK_200, res->status);
  4195. EXPECT_EQ("redirected.", res->body);
  4196. EXPECT_EQ("/2", res->location);
  4197. }
  4198. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4199. auto res = cli_.Get("/dir/test.abcde");
  4200. ASSERT_TRUE(res);
  4201. EXPECT_EQ(StatusCode::OK_200, res->status);
  4202. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4203. EXPECT_EQ("abcde", res->body);
  4204. }
  4205. TEST_F(ServerTest, StaticFileRange) {
  4206. auto res =
  4207. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4208. ASSERT_TRUE(res);
  4209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4210. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4211. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4212. EXPECT_EQ(true, res->has_header("Content-Range"));
  4213. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4214. EXPECT_EQ(std::string("cd"), res->body);
  4215. }
  4216. TEST_F(ServerTest, StaticFileRanges) {
  4217. auto res = cli_.Get("/dir/test.abcde",
  4218. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_TRUE(
  4222. res->get_header_value("Content-Type")
  4223. .find(
  4224. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4225. 0);
  4226. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4227. }
  4228. TEST_F(ServerTest, StaticFileRangeHead) {
  4229. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4232. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4233. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4234. EXPECT_EQ(true, res->has_header("Content-Range"));
  4235. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4236. }
  4237. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4238. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4242. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4243. EXPECT_EQ(true, res->has_header("Content-Range"));
  4244. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4245. res->get_header_value("Content-Range"));
  4246. EXPECT_EQ("LAST\n", res->body);
  4247. }
  4248. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4249. auto res =
  4250. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4254. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4255. EXPECT_EQ(true, res->has_header("Content-Range"));
  4256. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4257. }
  4258. TEST_F(ServerTest, StaticFileBigFile) {
  4259. auto res = cli_.Get("/dir/1MB.txt");
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::OK_200, res->status);
  4262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4263. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4264. }
  4265. TEST_F(ServerTest, InvalidBaseDirMount) {
  4266. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4267. }
  4268. TEST_F(ServerTest, Binary) {
  4269. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4270. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4271. "application/octet-stream");
  4272. ASSERT_TRUE(res);
  4273. ASSERT_EQ(StatusCode::OK_200, res->status);
  4274. ASSERT_EQ(4U, res->body.size());
  4275. res = cli_.Put("/binary", binary.data(), binary.size(),
  4276. "application/octet-stream");
  4277. ASSERT_TRUE(res);
  4278. ASSERT_EQ(StatusCode::OK_200, res->status);
  4279. ASSERT_EQ(4U, res->body.size());
  4280. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4281. "application/octet-stream");
  4282. ASSERT_TRUE(res);
  4283. ASSERT_EQ(StatusCode::OK_200, res->status);
  4284. ASSERT_EQ(4U, res->body.size());
  4285. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4286. "application/octet-stream");
  4287. ASSERT_TRUE(res);
  4288. ASSERT_EQ(StatusCode::OK_200, res->status);
  4289. ASSERT_EQ(4U, res->body.size());
  4290. }
  4291. TEST_F(ServerTest, BinaryString) {
  4292. auto binary = std::string("\x00\x01\x02\x03", 4);
  4293. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4294. ASSERT_TRUE(res);
  4295. ASSERT_EQ(StatusCode::OK_200, res->status);
  4296. ASSERT_EQ(4U, res->body.size());
  4297. res = cli_.Put("/binary", binary, "application/octet-stream");
  4298. ASSERT_TRUE(res);
  4299. ASSERT_EQ(StatusCode::OK_200, res->status);
  4300. ASSERT_EQ(4U, res->body.size());
  4301. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4302. ASSERT_TRUE(res);
  4303. ASSERT_EQ(StatusCode::OK_200, res->status);
  4304. ASSERT_EQ(4U, res->body.size());
  4305. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4306. ASSERT_TRUE(res);
  4307. ASSERT_EQ(StatusCode::OK_200, res->status);
  4308. ASSERT_EQ(4U, res->body.size());
  4309. }
  4310. TEST_F(ServerTest, EmptyRequest) {
  4311. auto res = cli_.Get("");
  4312. ASSERT_TRUE(!res);
  4313. EXPECT_EQ(Error::Connection, res.error());
  4314. }
  4315. TEST_F(ServerTest, LongRequest) {
  4316. std::string request;
  4317. for (size_t i = 0; i < 545; i++) {
  4318. request += "/TooLongRequest";
  4319. }
  4320. request += "OK";
  4321. auto res = cli_.Get(request.c_str());
  4322. ASSERT_TRUE(res);
  4323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4324. }
  4325. TEST_F(ServerTest, TooLongRequest) {
  4326. std::string request;
  4327. for (size_t i = 0; i < 546; i++) {
  4328. request += "/TooLongRequest";
  4329. }
  4330. request += "_NG";
  4331. auto start = std::chrono::high_resolution_clock::now();
  4332. cli_.set_keep_alive(true);
  4333. auto res = cli_.Get(request.c_str());
  4334. auto end = std::chrono::high_resolution_clock::now();
  4335. auto elapsed =
  4336. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4337. .count();
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4340. EXPECT_LE(elapsed, 1000);
  4341. EXPECT_EQ("close", res->get_header_value("Connection"));
  4342. EXPECT_FALSE(cli_.is_socket_open());
  4343. }
  4344. TEST_F(ServerTest, AlmostTooLongRequest) {
  4345. // test for #2046 - URI length check shouldn't include other content on req
  4346. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4347. // leading /, space, HTTP/1.1)
  4348. std::string request =
  4349. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4350. auto res = cli_.Get(request.c_str());
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4353. }
  4354. TEST_F(ServerTest, LongHeader) {
  4355. Request req;
  4356. req.method = "GET";
  4357. req.path = "/hi";
  4358. std::string host_and_port;
  4359. host_and_port += HOST;
  4360. host_and_port += ":";
  4361. host_and_port += std::to_string(PORT);
  4362. req.headers.emplace("Host", host_and_port.c_str());
  4363. req.headers.emplace("Accept", "*/*");
  4364. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4365. req.headers.emplace(
  4366. "Header-Name",
  4367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4374. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4382. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4383. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4385. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4386. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4387. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4388. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4389. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4390. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4391. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4392. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4395. "@@@@@@@@@@@@@@@@");
  4396. auto res = std::make_shared<Response>();
  4397. auto error = Error::Success;
  4398. auto ret = cli_.send(req, *res, error);
  4399. ASSERT_TRUE(ret);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. }
  4402. TEST_F(ServerTest, LongQueryValue) {
  4403. auto start = std::chrono::high_resolution_clock::now();
  4404. cli_.set_keep_alive(true);
  4405. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4406. auto end = std::chrono::high_resolution_clock::now();
  4407. auto elapsed =
  4408. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4409. .count();
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4412. EXPECT_LE(elapsed, 1000);
  4413. EXPECT_EQ("close", res->get_header_value("Connection"));
  4414. EXPECT_FALSE(cli_.is_socket_open());
  4415. }
  4416. TEST_F(ServerTest, TooLongQueryValue) {
  4417. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4418. ASSERT_FALSE(res);
  4419. EXPECT_EQ(Error::Read, res.error());
  4420. }
  4421. TEST_F(ServerTest, TooLongHeader) {
  4422. Request req;
  4423. req.method = "GET";
  4424. req.path = "/hi";
  4425. std::string host_and_port;
  4426. host_and_port += HOST;
  4427. host_and_port += ":";
  4428. host_and_port += std::to_string(PORT);
  4429. req.headers.emplace("Host", host_and_port.c_str());
  4430. req.headers.emplace("Accept", "*/*");
  4431. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4432. req.headers.emplace(
  4433. "Header-Name",
  4434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4445. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4446. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4447. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4448. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4449. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4450. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4451. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4455. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4456. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4457. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4458. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4459. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4460. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4461. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4462. "@@@@@@@@@@@@@@@@@");
  4463. auto res = std::make_shared<Response>();
  4464. auto error = Error::Success;
  4465. auto ret = cli_.send(req, *res, error);
  4466. ASSERT_TRUE(ret);
  4467. EXPECT_EQ(StatusCode::OK_200, res->status);
  4468. }
  4469. TEST_F(ServerTest, HeaderCountAtLimit) {
  4470. // Test with headers just under the 100 limit
  4471. httplib::Headers headers;
  4472. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4473. // This should keep us just under the 100 header limit
  4474. for (int i = 0; i < 95; i++) {
  4475. std::string name = "X-Test-Header-" + std::to_string(i);
  4476. std::string value = "value" + std::to_string(i);
  4477. headers.emplace(name, value);
  4478. }
  4479. // This should work fine as we're under the limit
  4480. auto res = cli_.Get("/hi", headers);
  4481. EXPECT_TRUE(res);
  4482. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4483. }
  4484. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4485. // Test with many headers to exceed the 100 limit
  4486. httplib::Headers headers;
  4487. // Add 150 headers to definitely exceed the 100 limit
  4488. for (int i = 0; i < 150; i++) {
  4489. std::string name = "X-Test-Header-" + std::to_string(i);
  4490. std::string value = "value" + std::to_string(i);
  4491. headers.emplace(name, value);
  4492. }
  4493. // This should fail due to exceeding header count limit
  4494. cli_.set_keep_alive(true);
  4495. auto res = cli_.Get("/hi", headers);
  4496. // The server should respond with 400 Bad Request
  4497. ASSERT_TRUE(res);
  4498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4499. EXPECT_EQ("close", res->get_header_value("Connection"));
  4500. EXPECT_FALSE(cli_.is_socket_open());
  4501. }
  4502. TEST_F(ServerTest, PercentEncoding) {
  4503. auto res = cli_.Get("/e%6edwith%");
  4504. ASSERT_TRUE(res);
  4505. EXPECT_EQ(StatusCode::OK_200, res->status);
  4506. }
  4507. TEST_F(ServerTest, PercentEncodingUnicode) {
  4508. auto res = cli_.Get("/e%u006edwith%");
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. }
  4512. TEST_F(ServerTest, InvalidPercentEncoding) {
  4513. auto res = cli_.Get("/%endwith%");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4516. }
  4517. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4518. auto res = cli_.Get("/%uendwith%");
  4519. ASSERT_TRUE(res);
  4520. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4521. }
  4522. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4523. auto res = cli_.Get("/hello?aaa=bbb%");
  4524. ASSERT_TRUE(res);
  4525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4526. }
  4527. TEST_F(ServerTest, PlusSignEncoding) {
  4528. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("a +b", res->body);
  4532. }
  4533. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4534. // This test simulates a potential DoS attack using many headers
  4535. // to verify our security fix prevents memory exhaustion
  4536. httplib::Headers attack_headers;
  4537. // Attempt to add many headers like an attacker would (200 headers to far
  4538. // exceed limit)
  4539. for (int i = 0; i < 200; i++) {
  4540. std::string name = "X-Attack-Header-" + std::to_string(i);
  4541. std::string value = "attack_payload_" + std::to_string(i);
  4542. attack_headers.emplace(name, value);
  4543. }
  4544. // Try to POST with excessive headers
  4545. cli_.set_keep_alive(true);
  4546. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4547. // Should either fail or return 400 Bad Request due to security limit
  4548. if (res) {
  4549. // If we get a response, it should be 400 Bad Request
  4550. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4551. EXPECT_EQ("close", res->get_header_value("Connection"));
  4552. }
  4553. EXPECT_FALSE(cli_.is_socket_open());
  4554. }
  4555. TEST_F(ServerTest, MultipartFormData) {
  4556. UploadFormDataItems items = {
  4557. {"text1", "text default", "", ""},
  4558. {"text2", "aωb", "", ""},
  4559. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4560. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4561. {"file3", "", "", "application/octet-stream"},
  4562. {"file4", "", "", " application/json tmp-string "}};
  4563. auto res = cli_.Post("/multipart", items);
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. }
  4567. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4568. UploadFormDataItems items = {
  4569. {"text", "default text", "", ""},
  4570. {"multi_text1", "aaaaa", "", ""},
  4571. {"multi_text1", "bbbbb", "", ""},
  4572. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4573. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4574. "application/json"},
  4575. };
  4576. auto res = cli_.Post("/multipart/multi_file_values", items);
  4577. ASSERT_TRUE(res);
  4578. EXPECT_EQ(StatusCode::OK_200, res->status);
  4579. }
  4580. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4581. auto res = cli_.Get("/hi");
  4582. ASSERT_TRUE(res);
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4585. EXPECT_EQ("Hello World!", res->body);
  4586. }
  4587. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4588. Request req;
  4589. req.method = "POST";
  4590. req.path = "/chunked";
  4591. std::string host_and_port;
  4592. host_and_port += HOST;
  4593. host_and_port += ":";
  4594. host_and_port += std::to_string(PORT);
  4595. req.headers.emplace("Host", host_and_port.c_str());
  4596. req.headers.emplace("Accept", "*/*");
  4597. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4598. req.headers.emplace("Content-Type", "text/plain");
  4599. req.headers.emplace("Content-Length", "0");
  4600. req.headers.emplace(
  4601. "Transfer-Encoding",
  4602. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4603. // Client does not chunk, so make a chunked body manually.
  4604. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4605. auto res = std::make_shared<Response>();
  4606. auto error = Error::Success;
  4607. auto ret = cli_.send(req, *res, error);
  4608. ASSERT_TRUE(ret);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. }
  4611. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4612. // rather than treat them as valid lengths.
  4613. template <typename ClientT>
  4614. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4615. Request req;
  4616. req.method = "POST";
  4617. req.path = "/chunked";
  4618. std::string host_and_port;
  4619. host_and_port += HOST;
  4620. host_and_port += ":";
  4621. host_and_port += std::to_string(PORT);
  4622. req.headers.emplace("Host", host_and_port.c_str());
  4623. req.headers.emplace("Content-Length", "0");
  4624. req.headers.emplace("Transfer-Encoding", "chunked");
  4625. req.body = body;
  4626. auto res = std::make_shared<Response>();
  4627. auto error = Error::Success;
  4628. ASSERT_TRUE(cli.send(req, *res, error));
  4629. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4630. }
  4631. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4632. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4633. }
  4634. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4635. expect_chunked_body_rejected(
  4636. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4637. }
  4638. TEST_F(ServerTest, GetStreamed2) {
  4639. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4642. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4643. EXPECT_EQ(true, res->has_header("Content-Range"));
  4644. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4645. EXPECT_EQ(std::string("ab"), res->body);
  4646. }
  4647. TEST_F(ServerTest, GetStreamed) {
  4648. auto res = cli_.Get("/streamed");
  4649. ASSERT_TRUE(res);
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4652. EXPECT_EQ(std::string("aaabbb"), res->body);
  4653. }
  4654. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4655. auto res = cli_.Get("/streamed-without-length",
  4656. Headers{make_range_header({{0, -1}})});
  4657. ASSERT_TRUE(res);
  4658. EXPECT_EQ(StatusCode::OK_200, res->status);
  4659. EXPECT_EQ(false, res->has_header("Content-Length"));
  4660. EXPECT_EQ(false, res->has_header("Content-Range"));
  4661. EXPECT_EQ(std::string("abcdefg"), res->body);
  4662. }
  4663. TEST_F(ServerTest, GetStreamedWithRange1) {
  4664. auto res =
  4665. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4668. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4669. EXPECT_EQ(true, res->has_header("Content-Range"));
  4670. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4671. EXPECT_EQ(std::string("def"), res->body);
  4672. }
  4673. TEST_F(ServerTest, GetStreamedWithRange2) {
  4674. auto res =
  4675. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4676. ASSERT_TRUE(res);
  4677. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4678. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4679. EXPECT_EQ(true, res->has_header("Content-Range"));
  4680. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4681. EXPECT_EQ(std::string("bcdefg"), res->body);
  4682. }
  4683. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4684. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4685. ASSERT_TRUE(res);
  4686. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4687. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4688. EXPECT_EQ(true, res->has_header("Content-Range"));
  4689. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4690. EXPECT_EQ(std::string("efg"), res->body);
  4691. }
  4692. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4693. auto res =
  4694. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4695. ASSERT_TRUE(res);
  4696. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4697. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4698. EXPECT_EQ(false, res->has_header("Content-Range"));
  4699. EXPECT_EQ(0U, res->body.size());
  4700. }
  4701. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4702. auto res =
  4703. cli_.Get("/streamed-with-range",
  4704. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4705. "92233720368547758079223372036854775807"}});
  4706. ASSERT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4708. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4709. EXPECT_EQ(false, res->has_header("Content-Range"));
  4710. EXPECT_EQ(0U, res->body.size());
  4711. }
  4712. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4713. auto res = cli_.Get(
  4714. "/with-range",
  4715. Headers{{"Range",
  4716. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4717. {"Accept-Encoding", ""}});
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4720. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4721. EXPECT_EQ(true, res->has_header("Content-Range"));
  4722. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4723. EXPECT_EQ(std::string("abcdefg"), res->body);
  4724. }
  4725. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4726. auto res = cli_.Get("/with-range", Headers{
  4727. {"Range", "bytes=0-"},
  4728. {"Accept-Encoding", ""},
  4729. });
  4730. ASSERT_TRUE(res);
  4731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4732. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4733. EXPECT_EQ(true, res->has_header("Content-Range"));
  4734. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4735. EXPECT_EQ(std::string("abcdefg"), res->body);
  4736. }
  4737. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4738. auto res = cli_.Get("/streamed-with-range",
  4739. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4742. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4743. EXPECT_EQ(false, res->has_header("Content-Range"));
  4744. EXPECT_EQ(267U, res->body.size());
  4745. // Check that both range contents are present
  4746. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4747. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4748. // Check that Content-Range headers are present for both ranges
  4749. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4750. std::string::npos);
  4751. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4752. std::string::npos);
  4753. }
  4754. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4755. Ranges ranges;
  4756. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4757. ranges.emplace_back(0, -1);
  4758. }
  4759. auto res = cli_.Get("/streamed-with-range?error",
  4760. Headers{{make_range_header(ranges)}});
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4763. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4764. EXPECT_EQ(false, res->has_header("Content-Range"));
  4765. EXPECT_EQ(0U, res->body.size());
  4766. }
  4767. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4768. auto res = cli_.Get("/streamed-with-range",
  4769. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4770. ASSERT_TRUE(res);
  4771. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4772. EXPECT_EQ(5U, res->body.size());
  4773. // Check that overlapping ranges are coalesced into a single range
  4774. EXPECT_EQ("bcdef", res->body);
  4775. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4776. // Should be single range, not multipart
  4777. EXPECT_TRUE(res->has_header("Content-Range"));
  4778. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4779. }
  4780. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4781. auto res = cli_.Get("/streamed-with-range",
  4782. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4785. EXPECT_EQ(268U, res->body.size());
  4786. // Check that both range contents are present
  4787. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4788. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4789. // Check that Content-Range headers are present for both ranges
  4790. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4791. std::string::npos);
  4792. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4793. std::string::npos);
  4794. }
  4795. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4796. auto res = cli_.Get("/streamed-with-range",
  4797. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4798. ASSERT_TRUE(res);
  4799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4800. EXPECT_EQ(269U, res->body.size());
  4801. // Check that both duplicate range contents are present
  4802. size_t first_abc = res->body.find("abc\r\n");
  4803. EXPECT_TRUE(first_abc != std::string::npos);
  4804. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4805. EXPECT_TRUE(second_abc != std::string::npos);
  4806. // Check that Content-Range headers are present for both ranges
  4807. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4808. EXPECT_TRUE(first_range != std::string::npos);
  4809. size_t second_range =
  4810. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4811. EXPECT_TRUE(second_range != std::string::npos);
  4812. }
  4813. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4814. auto res =
  4815. cli_.Get("/streamed-with-range?error",
  4816. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4817. ASSERT_TRUE(res);
  4818. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4819. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4820. EXPECT_EQ(false, res->has_header("Content-Range"));
  4821. EXPECT_EQ(0U, res->body.size());
  4822. }
  4823. TEST_F(ServerTest, GetStreamedEndless) {
  4824. uint64_t offset = 0;
  4825. auto res = cli_.Get("/streamed-cancel",
  4826. [&](const char * /*data*/, uint64_t data_length) {
  4827. if (offset < 100) {
  4828. offset += data_length;
  4829. return true;
  4830. }
  4831. return false;
  4832. });
  4833. ASSERT_TRUE(!res);
  4834. EXPECT_EQ(Error::Canceled, res.error());
  4835. }
  4836. TEST_F(ServerTest, ClientStop) {
  4837. std::atomic_size_t count{4};
  4838. std::vector<std::thread> threads;
  4839. for (auto i = count.load(); i != 0; --i) {
  4840. threads.emplace_back([&]() {
  4841. auto res = cli_.Get("/streamed-cancel",
  4842. [&](const char *, uint64_t) { return true; });
  4843. --count;
  4844. ASSERT_TRUE(!res);
  4845. EXPECT_TRUE(res.error() == Error::Canceled ||
  4846. res.error() == Error::Read || res.error() == Error::Write);
  4847. });
  4848. }
  4849. std::this_thread::sleep_for(std::chrono::seconds(2));
  4850. while (count != 0) {
  4851. cli_.stop();
  4852. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4853. }
  4854. for (auto &t : threads) {
  4855. t.join();
  4856. }
  4857. }
  4858. TEST_F(ServerTest, GetWithRange1) {
  4859. auto res = cli_.Get("/with-range", Headers{
  4860. make_range_header({{3, 5}}),
  4861. {"Accept-Encoding", ""},
  4862. });
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4865. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4866. EXPECT_EQ(true, res->has_header("Content-Range"));
  4867. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4868. EXPECT_EQ(std::string("def"), res->body);
  4869. }
  4870. TEST_F(ServerTest, GetWithRange2) {
  4871. auto res = cli_.Get("/with-range", Headers{
  4872. make_range_header({{1, -1}}),
  4873. {"Accept-Encoding", ""},
  4874. });
  4875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4876. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4877. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4878. EXPECT_EQ(true, res->has_header("Content-Range"));
  4879. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4880. EXPECT_EQ(std::string("bcdefg"), res->body);
  4881. }
  4882. TEST_F(ServerTest, GetWithRange3) {
  4883. auto res = cli_.Get("/with-range", Headers{
  4884. make_range_header({{0, 0}}),
  4885. {"Accept-Encoding", ""},
  4886. });
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4889. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4890. EXPECT_EQ(true, res->has_header("Content-Range"));
  4891. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4892. EXPECT_EQ(std::string("a"), res->body);
  4893. }
  4894. TEST_F(ServerTest, GetWithRange4) {
  4895. auto res = cli_.Get("/with-range", Headers{
  4896. make_range_header({{-1, 2}}),
  4897. {"Accept-Encoding", ""},
  4898. });
  4899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4901. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4902. EXPECT_EQ(true, res->has_header("Content-Range"));
  4903. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4904. EXPECT_EQ(std::string("fg"), res->body);
  4905. }
  4906. TEST_F(ServerTest, GetWithRange5) {
  4907. auto res = cli_.Get("/with-range", Headers{
  4908. make_range_header({{0, 5}}),
  4909. {"Accept-Encoding", ""},
  4910. });
  4911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4912. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4913. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4914. EXPECT_EQ(true, res->has_header("Content-Range"));
  4915. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4916. EXPECT_EQ(std::string("abcdef"), res->body);
  4917. }
  4918. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4919. auto res =
  4920. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  4921. ASSERT_TRUE(res);
  4922. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4923. }
  4924. TEST_F(ServerTest, GetWithRangeMultipart) {
  4925. auto res =
  4926. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4927. ASSERT_TRUE(res);
  4928. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4929. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4930. EXPECT_EQ(false, res->has_header("Content-Range"));
  4931. EXPECT_EQ(267U, res->body.size());
  4932. }
  4933. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4934. auto res = cli_.Get("/with-range",
  4935. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4938. }
  4939. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4940. auto res = cli_.Get("/with-range-customized-response",
  4941. Headers{{make_range_header({{1, 2}})}});
  4942. ASSERT_TRUE(res);
  4943. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4944. EXPECT_EQ(true, res->has_header("Content-Length"));
  4945. EXPECT_EQ(false, res->has_header("Content-Range"));
  4946. EXPECT_EQ(JSON_DATA, res->body);
  4947. }
  4948. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4949. auto res = cli_.Get("/with-range-customized-response",
  4950. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4951. ASSERT_TRUE(res);
  4952. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4953. EXPECT_EQ(true, res->has_header("Content-Length"));
  4954. EXPECT_EQ(false, res->has_header("Content-Range"));
  4955. EXPECT_EQ(JSON_DATA, res->body);
  4956. }
  4957. TEST_F(ServerTest, Issue1772) {
  4958. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  4959. ASSERT_TRUE(res);
  4960. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4961. }
  4962. TEST_F(ServerTest, Issue609) {
  4963. auto res = cli_.Delete("/issue609");
  4964. ASSERT_TRUE(res);
  4965. EXPECT_EQ(StatusCode::OK_200, res->status);
  4966. EXPECT_EQ(std::string("ok"), res->body);
  4967. }
  4968. TEST_F(ServerTest, GetStreamedChunked) {
  4969. auto res = cli_.Get("/streamed-chunked");
  4970. ASSERT_TRUE(res);
  4971. EXPECT_EQ(StatusCode::OK_200, res->status);
  4972. EXPECT_EQ(std::string("123456789"), res->body);
  4973. }
  4974. TEST_F(ServerTest, GetStreamedChunked2) {
  4975. auto res = cli_.Get("/streamed-chunked2");
  4976. ASSERT_TRUE(res);
  4977. EXPECT_EQ(StatusCode::OK_200, res->status);
  4978. EXPECT_EQ(std::string("123456789"), res->body);
  4979. }
  4980. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4981. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4982. ASSERT_TRUE(res);
  4983. EXPECT_EQ(StatusCode::OK_200, res->status);
  4984. EXPECT_EQ(std::string("123456789"), res->body);
  4985. EXPECT_TRUE(res->has_header("Trailer"));
  4986. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4987. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4988. // Trailers are now stored separately from headers (security fix)
  4989. EXPECT_EQ(2U, res->trailers.size());
  4990. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4991. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4992. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4993. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4994. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4995. // Verify trailers are NOT in headers (security verification)
  4996. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4997. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4998. }
  4999. TEST_F(ServerTest, LargeChunkedPost) {
  5000. Request req;
  5001. req.method = "POST";
  5002. req.path = "/large-chunked";
  5003. std::string host_and_port;
  5004. host_and_port += HOST;
  5005. host_and_port += ":";
  5006. host_and_port += std::to_string(PORT);
  5007. req.headers.emplace("Host", host_and_port.c_str());
  5008. req.headers.emplace("Accept", "*/*");
  5009. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5010. req.headers.emplace("Content-Type", "text/plain");
  5011. req.headers.emplace("Content-Length", "0");
  5012. req.headers.emplace("Transfer-Encoding", "chunked");
  5013. std::string long_string(30 * 1024u, 'a');
  5014. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5015. // Attempt to make a large enough post to exceed OS buffers, to test that
  5016. // the server handles short reads if the full chunk data isn't available.
  5017. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5018. auto res = std::make_shared<Response>();
  5019. auto error = Error::Success;
  5020. auto ret = cli_.send(req, *res, error);
  5021. ASSERT_TRUE(ret);
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. }
  5024. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5025. auto res = cli_.Get("/remote_addr");
  5026. ASSERT_TRUE(res);
  5027. EXPECT_EQ(StatusCode::OK_200, res->status);
  5028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5029. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5030. }
  5031. TEST_F(ServerTest, GetMethodLocalAddr) {
  5032. auto res = cli_.Get("/local_addr");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5036. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5037. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5038. }
  5039. TEST_F(ServerTest, HTTPResponseSplitting) {
  5040. auto res = cli_.Get("/http_response_splitting");
  5041. ASSERT_TRUE(res);
  5042. EXPECT_EQ(StatusCode::OK_200, res->status);
  5043. }
  5044. TEST_F(ServerTest, SlowRequest) {
  5045. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5046. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5047. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5048. }
  5049. #if 0
  5050. TEST_F(ServerTest, SlowPost) {
  5051. char buffer[64 * 1024];
  5052. memset(buffer, 0x42, sizeof(buffer));
  5053. auto res = cli_.Post(
  5054. "/slowpost", 64 * 1024 * 1024,
  5055. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5056. auto ret = sink.write(buffer, sizeof(buffer));
  5057. EXPECT_TRUE(ret);
  5058. return true;
  5059. },
  5060. "text/plain");
  5061. ASSERT_TRUE(res);
  5062. EXPECT_EQ(StatusCode::OK_200, res->status);
  5063. }
  5064. TEST_F(ServerTest, SlowPostFail) {
  5065. char buffer[64 * 1024];
  5066. memset(buffer, 0x42, sizeof(buffer));
  5067. cli_.set_write_timeout(std::chrono::seconds(0));
  5068. auto res = cli_.Post(
  5069. "/slowpost", 64 * 1024 * 1024,
  5070. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5071. sink.write(buffer, sizeof(buffer));
  5072. return true;
  5073. },
  5074. "text/plain");
  5075. ASSERT_TRUE(!res);
  5076. EXPECT_EQ(Error::Write, res.error());
  5077. }
  5078. #endif
  5079. TEST_F(ServerTest, Put) {
  5080. auto res = cli_.Put("/put", "PUT", "text/plain");
  5081. ASSERT_TRUE(res);
  5082. EXPECT_EQ(StatusCode::OK_200, res->status);
  5083. EXPECT_EQ("PUT", res->body);
  5084. }
  5085. TEST_F(ServerTest, PutWithContentProvider) {
  5086. auto res = cli_.Put(
  5087. "/put", 3,
  5088. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5089. sink.os << "PUT";
  5090. return true;
  5091. },
  5092. "text/plain");
  5093. ASSERT_TRUE(res);
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. EXPECT_EQ("PUT", res->body);
  5096. }
  5097. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5098. auto res = cli_.Post(
  5099. "/post", 42,
  5100. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5101. return false;
  5102. },
  5103. "text/plain");
  5104. ASSERT_TRUE(!res);
  5105. EXPECT_EQ(Error::Canceled, res.error());
  5106. }
  5107. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5108. auto res = cli_.Put(
  5109. "/put",
  5110. [](size_t /*offset*/, DataSink &sink) {
  5111. sink.os << "PUT";
  5112. sink.done();
  5113. return true;
  5114. },
  5115. "text/plain");
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ("PUT", res->body);
  5119. }
  5120. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5121. auto res = cli_.Post(
  5122. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5123. "text/plain");
  5124. ASSERT_TRUE(!res);
  5125. EXPECT_EQ(Error::Canceled, res.error());
  5126. }
  5127. TEST_F(ServerTest, PostLoopBack) {
  5128. std::string body;
  5129. auto res = cli_.Post(
  5130. "/post-loopback", 9,
  5131. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5132. EXPECT_EQ(9u, length);
  5133. sink.write("123", 3);
  5134. sink.write("456", 3);
  5135. sink.write("789", 3);
  5136. return true;
  5137. },
  5138. "text/plain",
  5139. [&body](const char *data, size_t data_length) {
  5140. body.append(data, data_length);
  5141. return true;
  5142. });
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("123456789", body);
  5146. }
  5147. TEST_F(ServerTest, PutLoopBack) {
  5148. std::string body;
  5149. auto res = cli_.Put(
  5150. "/put-loopback", 9,
  5151. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5152. EXPECT_EQ(9u, length);
  5153. sink.write("123", 3);
  5154. sink.write("456", 3);
  5155. sink.write("789", 3);
  5156. return true;
  5157. },
  5158. "text/plain",
  5159. [&body](const char *data, size_t data_length) {
  5160. body.append(data, data_length);
  5161. return true;
  5162. });
  5163. ASSERT_TRUE(res);
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. EXPECT_EQ("123456789", body);
  5166. }
  5167. TEST_F(ServerTest, PatchLoopBack) {
  5168. std::string body;
  5169. auto res = cli_.Patch(
  5170. "/patch-loopback", 9,
  5171. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5172. EXPECT_EQ(9u, length);
  5173. sink.write("123", 3);
  5174. sink.write("456", 3);
  5175. sink.write("789", 3);
  5176. return true;
  5177. },
  5178. "text/plain",
  5179. [&body](const char *data, size_t data_length) {
  5180. body.append(data, data_length);
  5181. return true;
  5182. });
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. EXPECT_EQ("123456789", body);
  5186. }
  5187. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5188. std::string body;
  5189. auto res = cli_.Post(
  5190. "/post-loopback",
  5191. [](size_t /*offset*/, DataSink &sink) {
  5192. sink.write("123", 3);
  5193. sink.write("456", 3);
  5194. sink.write("789", 3);
  5195. sink.done();
  5196. return true;
  5197. },
  5198. "text/plain",
  5199. [&body](const char *data, size_t data_length) {
  5200. body.append(data, data_length);
  5201. return true;
  5202. });
  5203. ASSERT_TRUE(res);
  5204. EXPECT_EQ(StatusCode::OK_200, res->status);
  5205. EXPECT_EQ("123456789", body);
  5206. }
  5207. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5208. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5209. cli_.set_compress(true);
  5210. auto res = cli_.Put(
  5211. "/put", 3,
  5212. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5213. sink.os << "PUT";
  5214. return true;
  5215. },
  5216. "text/plain");
  5217. ASSERT_TRUE(res);
  5218. EXPECT_EQ(StatusCode::OK_200, res->status);
  5219. EXPECT_EQ("PUT", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5222. cli_.set_compress(true);
  5223. auto res = cli_.Post(
  5224. "/post", 42,
  5225. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5226. return false;
  5227. },
  5228. "text/plain");
  5229. ASSERT_TRUE(!res);
  5230. EXPECT_EQ(Error::Canceled, res.error());
  5231. }
  5232. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5233. cli_.set_compress(true);
  5234. auto res = cli_.Put(
  5235. "/put",
  5236. [](size_t /*offset*/, DataSink &sink) {
  5237. sink.os << "PUT";
  5238. sink.done();
  5239. return true;
  5240. },
  5241. "text/plain");
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. EXPECT_EQ("PUT", res->body);
  5245. }
  5246. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5247. cli_.set_compress(true);
  5248. auto res = cli_.Post(
  5249. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5250. "text/plain");
  5251. ASSERT_TRUE(!res);
  5252. EXPECT_EQ(Error::Canceled, res.error());
  5253. }
  5254. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5255. cli_.set_compress(true);
  5256. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5257. ASSERT_TRUE(res);
  5258. EXPECT_EQ(StatusCode::OK_200, res->status);
  5259. EXPECT_EQ(LARGE_DATA, res->body);
  5260. }
  5261. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5262. #ifdef CPPHTTPLIB_SSL_ENABLED
  5263. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5264. Client cli(s.c_str());
  5265. cli.enable_server_certificate_verification(false);
  5266. #else
  5267. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5268. Client cli(s.c_str());
  5269. #endif
  5270. cli.set_compress(true);
  5271. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5272. ASSERT_TRUE(res);
  5273. EXPECT_EQ(StatusCode::OK_200, res->status);
  5274. EXPECT_EQ(LARGE_DATA, res->body);
  5275. // The compressed size should be less than a 10th of the original. May vary
  5276. // depending on the zlib library.
  5277. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5278. static_cast<uint64_t>(10 * 1024 * 1024));
  5279. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5280. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5281. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5282. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5283. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5284. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5285. #endif
  5286. }
  5287. TEST_F(ServerTest, PutContentWithDeflate) {
  5288. cli_.set_compress(false);
  5289. Headers headers;
  5290. headers.emplace("Content-Encoding", "deflate");
  5291. // PUT in deflate format:
  5292. auto res = cli_.Put("/put", headers,
  5293. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5294. ASSERT_TRUE(res);
  5295. EXPECT_EQ(StatusCode::OK_200, res->status);
  5296. EXPECT_EQ("PUT", res->body);
  5297. }
  5298. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5299. Headers headers;
  5300. headers.emplace("Accept-Encoding", "gzip, deflate");
  5301. auto res = cli_.Get("/streamed-chunked", headers);
  5302. ASSERT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ(std::string("123456789"), res->body);
  5305. }
  5306. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5307. Headers headers;
  5308. headers.emplace("Accept-Encoding", "gzip, deflate");
  5309. auto res = cli_.Get("/streamed-chunked2", headers);
  5310. ASSERT_TRUE(res);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. EXPECT_EQ(std::string("123456789"), res->body);
  5313. }
  5314. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5315. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5316. ASSERT_TRUE(res);
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. }
  5319. TEST(GzipDecompressor, ChunkedDecompression) {
  5320. std::string data;
  5321. for (size_t i = 0; i < 32 * 1024; ++i) {
  5322. data.push_back(static_cast<char>('a' + i % 26));
  5323. }
  5324. std::string compressed_data;
  5325. {
  5326. httplib::detail::gzip_compressor compressor;
  5327. bool result = compressor.compress(
  5328. data.data(), data.size(),
  5329. /*last=*/true,
  5330. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5331. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5332. compressed_data_size);
  5333. return true;
  5334. });
  5335. ASSERT_TRUE(result);
  5336. }
  5337. std::string decompressed_data;
  5338. {
  5339. httplib::detail::gzip_decompressor decompressor;
  5340. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5341. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5342. size_t chunk_size = 130;
  5343. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5344. chunk_begin += chunk_size) {
  5345. size_t current_chunk_size =
  5346. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5347. bool result = decompressor.decompress(
  5348. compressed_data.data() + chunk_begin, current_chunk_size,
  5349. [&](const char *decompressed_data_chunk,
  5350. size_t decompressed_data_chunk_size) {
  5351. decompressed_data.insert(decompressed_data.size(),
  5352. decompressed_data_chunk,
  5353. decompressed_data_chunk_size);
  5354. return true;
  5355. });
  5356. ASSERT_TRUE(result);
  5357. }
  5358. }
  5359. ASSERT_EQ(data, decompressed_data);
  5360. }
  5361. TEST(GzipDecompressor, DeflateDecompression) {
  5362. std::string original_text = "Raw deflate without gzip";
  5363. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5364. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5365. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5366. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5367. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5368. std::string decompressed_data;
  5369. {
  5370. httplib::detail::gzip_decompressor decompressor;
  5371. bool result = decompressor.decompress(
  5372. compressed_data.data(), compressed_data.size(),
  5373. [&](const char *decompressed_data_chunk,
  5374. size_t decompressed_data_chunk_size) {
  5375. decompressed_data.insert(decompressed_data.size(),
  5376. decompressed_data_chunk,
  5377. decompressed_data_chunk_size);
  5378. return true;
  5379. });
  5380. ASSERT_TRUE(result);
  5381. }
  5382. ASSERT_EQ(original_text, decompressed_data);
  5383. }
  5384. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5385. std::string original_text = "Raw deflate without gzip";
  5386. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5387. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5388. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5389. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5390. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5391. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5392. std::string decompressed_data;
  5393. {
  5394. httplib::detail::gzip_decompressor decompressor;
  5395. bool result = decompressor.decompress(
  5396. compressed_data.data(), compressed_data.size(),
  5397. [&](const char *decompressed_data_chunk,
  5398. size_t decompressed_data_chunk_size) {
  5399. decompressed_data.insert(decompressed_data.size(),
  5400. decompressed_data_chunk,
  5401. decompressed_data_chunk_size);
  5402. return true;
  5403. });
  5404. ASSERT_TRUE(result);
  5405. }
  5406. ASSERT_EQ(original_text, decompressed_data);
  5407. }
  5408. #endif
  5409. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5410. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5411. Headers headers;
  5412. headers.emplace("Accept-Encoding", "br");
  5413. auto res = cli_.Get("/streamed-chunked", headers);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. EXPECT_EQ(std::string("123456789"), res->body);
  5417. }
  5418. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5419. Headers headers;
  5420. headers.emplace("Accept-Encoding", "br");
  5421. auto res = cli_.Get("/streamed-chunked2", headers);
  5422. ASSERT_TRUE(res);
  5423. EXPECT_EQ(StatusCode::OK_200, res->status);
  5424. EXPECT_EQ(std::string("123456789"), res->body);
  5425. }
  5426. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5427. cli_.set_compress(true);
  5428. auto res = cli_.Put(
  5429. "/put", 3,
  5430. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5431. sink.os << "PUT";
  5432. return true;
  5433. },
  5434. "text/plain");
  5435. ASSERT_TRUE(res);
  5436. EXPECT_EQ(StatusCode::OK_200, res->status);
  5437. EXPECT_EQ("PUT", res->body);
  5438. }
  5439. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5440. cli_.set_compress(true);
  5441. auto res = cli_.Put(
  5442. "/put",
  5443. [](size_t /*offset*/, DataSink &sink) {
  5444. sink.os << "PUT";
  5445. sink.done();
  5446. return true;
  5447. },
  5448. "text/plain");
  5449. ASSERT_TRUE(res);
  5450. EXPECT_EQ(StatusCode::OK_200, res->status);
  5451. EXPECT_EQ("PUT", res->body);
  5452. }
  5453. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5454. cli_.set_compress(true);
  5455. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5456. ASSERT_TRUE(res);
  5457. EXPECT_EQ(StatusCode::OK_200, res->status);
  5458. EXPECT_EQ(LARGE_DATA, res->body);
  5459. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5460. }
  5461. #endif
  5462. TEST_F(ServerTest, Patch) {
  5463. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("PATCH", res->body);
  5467. }
  5468. TEST_F(ServerTest, Delete) {
  5469. auto res = cli_.Delete("/delete");
  5470. ASSERT_TRUE(res);
  5471. EXPECT_EQ(StatusCode::OK_200, res->status);
  5472. EXPECT_EQ("DELETE", res->body);
  5473. }
  5474. TEST_F(ServerTest, DeleteContentReceiver) {
  5475. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5476. ASSERT_TRUE(res);
  5477. EXPECT_EQ(StatusCode::OK_200, res->status);
  5478. EXPECT_EQ("content", res->body);
  5479. }
  5480. TEST_F(ServerTest, Options) {
  5481. auto res = cli_.Options("*");
  5482. ASSERT_TRUE(res);
  5483. EXPECT_EQ(StatusCode::OK_200, res->status);
  5484. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5485. EXPECT_TRUE(res->body.empty());
  5486. }
  5487. TEST_F(ServerTest, URL) {
  5488. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5489. ASSERT_TRUE(res);
  5490. EXPECT_EQ(StatusCode::OK_200, res->status);
  5491. }
  5492. TEST_F(ServerTest, ArrayParam) {
  5493. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5494. ASSERT_TRUE(res);
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. }
  5497. TEST_F(ServerTest, ArrayParamValues) {
  5498. auto res =
  5499. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5500. ASSERT_TRUE(res);
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. }
  5503. TEST_F(ServerTest, NoMultipleHeaders) {
  5504. Headers headers = {{"Content-Length", "5"}};
  5505. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. }
  5510. TEST_F(ServerTest, PostContentReceiver) {
  5511. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5512. ASSERT_TRUE(res);
  5513. ASSERT_EQ(StatusCode::OK_200, res->status);
  5514. ASSERT_EQ("content", res->body);
  5515. }
  5516. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5517. UploadFormDataItems items = {
  5518. {"text1", "text default", "", ""},
  5519. {"text2", "aωb", "", ""},
  5520. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5521. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5522. {"file3", "", "", "application/octet-stream"},
  5523. };
  5524. auto res = cli_.Post("/content_receiver", items);
  5525. ASSERT_TRUE(res);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. }
  5528. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5529. UploadFormDataItems items = {
  5530. {"text1", "text default", "", ""},
  5531. {"text2", "aωb", "", ""},
  5532. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5533. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5534. {"file3", "", "", "application/octet-stream"},
  5535. };
  5536. auto boundary = std::string("+++++");
  5537. std::string body;
  5538. for (const auto &item : items) {
  5539. body += "--" + boundary + "\r\n";
  5540. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5541. if (!item.filename.empty()) {
  5542. body += "; filename=\"" + item.filename + "\"";
  5543. }
  5544. body += "\r\n";
  5545. if (!item.content_type.empty()) {
  5546. body += "Content-Type: " + item.content_type + "\r\n";
  5547. }
  5548. body += "\r\n";
  5549. body += item.content + "\r\n";
  5550. }
  5551. body += "--" + boundary + "--\r\n";
  5552. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5553. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. }
  5557. TEST(MultipartFormDataTest, FieldEscaping) {
  5558. Server svr;
  5559. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5560. const ContentReader &content_reader) {
  5561. ASSERT_TRUE(req.is_multipart_form_data());
  5562. std::vector<FormData> received;
  5563. content_reader(
  5564. [&](const FormData &file) {
  5565. received.push_back(file);
  5566. return true;
  5567. },
  5568. [&](const char *data, size_t data_length) {
  5569. received.back().content.append(data, data_length);
  5570. return true;
  5571. });
  5572. // '"', CR and LF in names and filenames are escaped following the
  5573. // WHATWG HTML standard, so each part still parses as a single part
  5574. // with no injected headers. Content types get CR/LF escaped too,
  5575. // while '"' (legal there, e.g. quoted charset) is preserved.
  5576. ASSERT_EQ(4U, received.size());
  5577. EXPECT_EQ("na%22me", received[0].name);
  5578. EXPECT_EQ("quoted name", received[0].content);
  5579. EXPECT_EQ("file", received[1].name);
  5580. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5581. received[1].filename);
  5582. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5583. EXPECT_EQ("injected", received[1].content);
  5584. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5585. EXPECT_EQ("my%22file.txt", received[2].filename);
  5586. EXPECT_EQ("cr lf name", received[2].content);
  5587. EXPECT_EQ("typed", received[3].name);
  5588. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5589. received[3].content_type);
  5590. EXPECT_EQ("typed content", received[3].content);
  5591. });
  5592. auto port = svr.bind_to_any_port("localhost");
  5593. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5594. auto se = detail::scope_exit([&] {
  5595. svr.stop();
  5596. t.join();
  5597. ASSERT_FALSE(svr.is_running());
  5598. });
  5599. svr.wait_until_ready();
  5600. Client cli("localhost", port);
  5601. UploadFormDataItems items = {
  5602. {"na\"me", "quoted name", "", ""},
  5603. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5604. "application/octet-stream"},
  5605. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5606. {"typed", "typed content", "",
  5607. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5608. };
  5609. auto res = cli.Post("/post", items);
  5610. ASSERT_TRUE(res);
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. }
  5613. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5614. const UploadFormDataItems items = {
  5615. {"name1", "Content 1", "", ""},
  5616. {"name2", "Content 2", "file2.txt", "text/plain"},
  5617. };
  5618. Server svr;
  5619. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5620. const ContentReader &content_reader) {
  5621. ASSERT_TRUE(req.is_multipart_form_data());
  5622. std::vector<FormData> received;
  5623. content_reader(
  5624. [&](const FormData &file) {
  5625. received.push_back(file);
  5626. return true;
  5627. },
  5628. [&](const char *data, size_t data_length) {
  5629. received.back().content.append(data, data_length);
  5630. return true;
  5631. });
  5632. ASSERT_EQ(2U, received.size());
  5633. EXPECT_EQ("name1", received[0].name);
  5634. EXPECT_EQ("Content 1", received[0].content);
  5635. EXPECT_EQ("name2", received[1].name);
  5636. EXPECT_EQ("Content 2", received[1].content);
  5637. EXPECT_EQ("file2.txt", received[1].filename);
  5638. EXPECT_EQ("text/plain", received[1].content_type);
  5639. });
  5640. auto port = svr.bind_to_any_port("localhost");
  5641. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5642. auto se = detail::scope_exit([&] {
  5643. svr.stop();
  5644. t.join();
  5645. ASSERT_FALSE(svr.is_running());
  5646. });
  5647. svr.wait_until_ready();
  5648. Client cli("localhost", port);
  5649. // Whole-body serialization with a generated boundary
  5650. {
  5651. MultipartFormDataWriter writer;
  5652. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5653. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5654. writer.content_type());
  5655. auto body = writer.serialize(items);
  5656. EXPECT_EQ(body.size(), writer.content_length(items));
  5657. auto res = cli.Post("/post", body, writer.content_type());
  5658. ASSERT_TRUE(res);
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. }
  5661. // Per-part framing with a custom boundary via a content provider
  5662. {
  5663. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5664. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5665. MultipartFormDataWriter writer("custom-boundary_123");
  5666. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5667. std::string body;
  5668. for (const auto &item : items) {
  5669. body += writer.item_begin(item);
  5670. body += item.content;
  5671. body += MultipartFormDataWriter::item_end();
  5672. }
  5673. body += writer.finish();
  5674. EXPECT_EQ(body.size(), writer.content_length(items));
  5675. auto res = cli.Post(
  5676. "/post", body.size(),
  5677. [&](size_t offset, size_t length, DataSink &sink) {
  5678. sink.write(body.data() + offset, length);
  5679. return true;
  5680. },
  5681. writer.content_type());
  5682. ASSERT_TRUE(res);
  5683. EXPECT_EQ(StatusCode::OK_200, res->status);
  5684. }
  5685. }
  5686. TEST_F(ServerTest, PostContentReceiverGzip) {
  5687. cli_.set_compress(true);
  5688. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5689. ASSERT_TRUE(res);
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ("content", res->body);
  5692. }
  5693. TEST_F(ServerTest, PutContentReceiver) {
  5694. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5695. ASSERT_TRUE(res);
  5696. ASSERT_EQ(StatusCode::OK_200, res->status);
  5697. ASSERT_EQ("content", res->body);
  5698. }
  5699. TEST_F(ServerTest, PatchContentReceiver) {
  5700. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5701. ASSERT_TRUE(res);
  5702. ASSERT_EQ(StatusCode::OK_200, res->status);
  5703. ASSERT_EQ("content", res->body);
  5704. }
  5705. template <typename ClientType>
  5706. void TestWithHeadersAndContentReceiver(
  5707. ClientType &cli,
  5708. std::function<Result(ClientType &, const std::string &, const Headers &,
  5709. const std::string &, const std::string &,
  5710. ContentReceiver, DownloadProgress)>
  5711. request_func) {
  5712. Headers headers;
  5713. headers.emplace("X-Custom-Header", "test-value");
  5714. std::string received_body;
  5715. auto res = request_func(
  5716. cli, "/content_receiver", headers, "content", "application/json",
  5717. [&](const char *data, size_t data_length) {
  5718. received_body.append(data, data_length);
  5719. return true;
  5720. },
  5721. nullptr);
  5722. ASSERT_TRUE(res);
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ("content", received_body);
  5725. }
  5726. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5727. #ifdef CPPHTTPLIB_SSL_ENABLED
  5728. using ClientT = SSLClient;
  5729. #else
  5730. using ClientT = Client;
  5731. #endif
  5732. TestWithHeadersAndContentReceiver<ClientT>(
  5733. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5734. const std::string &body, const std::string &content_type,
  5735. ContentReceiver receiver, DownloadProgress progress) {
  5736. return cli.Post(path, headers, body, content_type, receiver, progress);
  5737. });
  5738. }
  5739. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5740. #ifdef CPPHTTPLIB_SSL_ENABLED
  5741. using ClientT = SSLClient;
  5742. #else
  5743. using ClientT = Client;
  5744. #endif
  5745. TestWithHeadersAndContentReceiver<ClientT>(
  5746. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5747. const std::string &body, const std::string &content_type,
  5748. ContentReceiver receiver, DownloadProgress progress) {
  5749. return cli.Put(path, headers, body, content_type, receiver, progress);
  5750. });
  5751. }
  5752. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5753. #ifdef CPPHTTPLIB_SSL_ENABLED
  5754. using ClientT = SSLClient;
  5755. #else
  5756. using ClientT = Client;
  5757. #endif
  5758. TestWithHeadersAndContentReceiver<ClientT>(
  5759. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5760. const std::string &body, const std::string &content_type,
  5761. ContentReceiver receiver, DownloadProgress progress) {
  5762. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5763. });
  5764. }
  5765. template <typename ClientType>
  5766. void TestWithHeadersAndContentReceiverWithProgress(
  5767. ClientType &cli,
  5768. std::function<Result(ClientType &, const std::string &, const Headers &,
  5769. const std::string &, const std::string &,
  5770. ContentReceiver, DownloadProgress)>
  5771. request_func) {
  5772. Headers headers;
  5773. headers.emplace("X-Test-Header", "progress-test");
  5774. std::string received_body;
  5775. auto progress_called = false;
  5776. auto res = request_func(
  5777. cli, "/content_receiver", headers, "content", "text/plain",
  5778. [&](const char *data, size_t data_length) {
  5779. received_body.append(data, data_length);
  5780. return true;
  5781. },
  5782. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5783. progress_called = true;
  5784. return true;
  5785. });
  5786. ASSERT_TRUE(res);
  5787. EXPECT_EQ(StatusCode::OK_200, res->status);
  5788. EXPECT_EQ("content", received_body);
  5789. EXPECT_TRUE(progress_called);
  5790. }
  5791. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5792. #ifdef CPPHTTPLIB_SSL_ENABLED
  5793. using ClientT = SSLClient;
  5794. #else
  5795. using ClientT = Client;
  5796. #endif
  5797. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5798. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5799. const std::string &body, const std::string &content_type,
  5800. ContentReceiver receiver, DownloadProgress progress) {
  5801. return cli.Post(path, headers, body, content_type, receiver, progress);
  5802. });
  5803. }
  5804. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5805. #ifdef CPPHTTPLIB_SSL_ENABLED
  5806. using ClientT = SSLClient;
  5807. #else
  5808. using ClientT = Client;
  5809. #endif
  5810. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5811. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5812. const std::string &body, const std::string &content_type,
  5813. ContentReceiver receiver, DownloadProgress progress) {
  5814. return cli.Put(path, headers, body, content_type, receiver, progress);
  5815. });
  5816. }
  5817. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5818. #ifdef CPPHTTPLIB_SSL_ENABLED
  5819. using ClientT = SSLClient;
  5820. #else
  5821. using ClientT = Client;
  5822. #endif
  5823. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5824. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5825. const std::string &body, const std::string &content_type,
  5826. ContentReceiver receiver, DownloadProgress progress) {
  5827. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5828. });
  5829. }
  5830. template <typename ClientType>
  5831. void TestWithHeadersAndContentReceiverError(
  5832. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5833. const Headers &, const std::string &,
  5834. const std::string &, ContentReceiver)>
  5835. request_func) {
  5836. Headers headers;
  5837. headers.emplace("X-Error-Test", "true");
  5838. std::string received_body;
  5839. auto receiver_failed = false;
  5840. auto res =
  5841. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5842. [&](const char *data, size_t data_length) {
  5843. received_body.append(data, data_length);
  5844. receiver_failed = true;
  5845. return false;
  5846. });
  5847. ASSERT_FALSE(res);
  5848. EXPECT_TRUE(receiver_failed);
  5849. }
  5850. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5851. #ifdef CPPHTTPLIB_SSL_ENABLED
  5852. using ClientT = SSLClient;
  5853. #else
  5854. using ClientT = Client;
  5855. #endif
  5856. TestWithHeadersAndContentReceiverError<ClientT>(
  5857. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5858. const std::string &body, const std::string &content_type,
  5859. ContentReceiver receiver) {
  5860. return cli.Post(path, headers, body, content_type, receiver);
  5861. });
  5862. }
  5863. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5864. #ifdef CPPHTTPLIB_SSL_ENABLED
  5865. using ClientT = SSLClient;
  5866. #else
  5867. using ClientT = Client;
  5868. #endif
  5869. TestWithHeadersAndContentReceiverError<ClientT>(
  5870. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5871. const std::string &body, const std::string &content_type,
  5872. ContentReceiver receiver) {
  5873. return cli.Put(path, headers, body, content_type, receiver);
  5874. });
  5875. }
  5876. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5877. #ifdef CPPHTTPLIB_SSL_ENABLED
  5878. using ClientT = SSLClient;
  5879. #else
  5880. using ClientT = Client;
  5881. #endif
  5882. TestWithHeadersAndContentReceiverError<ClientT>(
  5883. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5884. const std::string &body, const std::string &content_type,
  5885. ContentReceiver receiver) {
  5886. return cli.Patch(path, headers, body, content_type, receiver);
  5887. });
  5888. }
  5889. TEST_F(ServerTest, PostQueryStringAndBody) {
  5890. auto res =
  5891. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5892. ASSERT_TRUE(res);
  5893. ASSERT_EQ(StatusCode::OK_200, res->status);
  5894. }
  5895. TEST_F(ServerTest, HTTP2Magic) {
  5896. Request req;
  5897. req.method = "PRI";
  5898. req.path = "*";
  5899. req.body = "SM";
  5900. auto res = std::make_shared<Response>();
  5901. auto error = Error::Success;
  5902. auto ret = cli_.send(req, *res, error);
  5903. ASSERT_TRUE(ret);
  5904. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5905. }
  5906. TEST_F(ServerTest, KeepAlive) {
  5907. auto res = cli_.Get("/hi");
  5908. ASSERT_TRUE(res);
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5911. EXPECT_EQ("Hello World!", res->body);
  5912. res = cli_.Get("/hi");
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(StatusCode::OK_200, res->status);
  5915. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5916. EXPECT_EQ("Hello World!", res->body);
  5917. res = cli_.Get("/hi");
  5918. ASSERT_TRUE(res);
  5919. EXPECT_EQ(StatusCode::OK_200, res->status);
  5920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5921. EXPECT_EQ("Hello World!", res->body);
  5922. res = cli_.Get("/not-exist");
  5923. ASSERT_TRUE(res);
  5924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5925. res = cli_.Post("/empty", "", "text/plain");
  5926. ASSERT_TRUE(res);
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5929. EXPECT_EQ("empty", res->body);
  5930. EXPECT_EQ("close", res->get_header_value("Connection"));
  5931. res = cli_.Post(
  5932. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5933. "text/plain");
  5934. ASSERT_TRUE(res);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5937. EXPECT_EQ("empty", res->body);
  5938. cli_.set_keep_alive(false);
  5939. res = cli_.Get("/last-request");
  5940. ASSERT_TRUE(res);
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. EXPECT_EQ("close", res->get_header_value("Connection"));
  5943. }
  5944. TEST_F(ServerTest, TooManyRedirect) {
  5945. cli_.set_follow_location(true);
  5946. auto res = cli_.Get("/redirect/0");
  5947. ASSERT_TRUE(!res);
  5948. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5949. }
  5950. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5951. Request req;
  5952. req.method = "FOOBAR";
  5953. req.path = "/hi";
  5954. cli_.set_keep_alive(true);
  5955. auto res = cli_.send(req);
  5956. ASSERT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5958. EXPECT_EQ("close", res->get_header_value("Connection"));
  5959. EXPECT_FALSE(cli_.is_socket_open());
  5960. }
  5961. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5962. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5963. TEST_F(ServerTest, Gzip) {
  5964. Headers headers;
  5965. headers.emplace("Accept-Encoding", "gzip, deflate");
  5966. auto res = cli_.Get("/compress", headers);
  5967. ASSERT_TRUE(res);
  5968. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5969. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5970. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5971. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5972. "7890123456789012345678901234567890",
  5973. res->body);
  5974. EXPECT_EQ(StatusCode::OK_200, res->status);
  5975. }
  5976. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5977. Headers headers;
  5978. headers.emplace("Accept-Encoding", "gzip, deflate");
  5979. auto res = cli_.Get("/compress-with-charset", headers);
  5980. ASSERT_TRUE(res);
  5981. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5982. EXPECT_EQ("application/json; charset=utf-8",
  5983. res->get_header_value("Content-Type"));
  5984. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5985. "7890123456789012345678901234567890",
  5986. res->body);
  5987. EXPECT_EQ(StatusCode::OK_200, res->status);
  5988. }
  5989. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5990. Headers headers;
  5991. headers.emplace("Accept-Encoding", "");
  5992. auto res = cli_.Get("/compress", headers);
  5993. ASSERT_TRUE(res);
  5994. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5996. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5997. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5998. "7890123456789012345678901234567890",
  5999. res->body);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. }
  6002. TEST_F(ServerTest, GzipWithContentReceiver) {
  6003. Headers headers;
  6004. headers.emplace("Accept-Encoding", "gzip, deflate");
  6005. std::string body;
  6006. auto res = cli_.Get("/compress", headers,
  6007. [&](const char *data, uint64_t data_length) {
  6008. EXPECT_EQ(100U, data_length);
  6009. body.append(data, data_length);
  6010. return true;
  6011. });
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6015. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6016. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6017. "7890123456789012345678901234567890",
  6018. body);
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. }
  6021. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6022. Headers headers;
  6023. headers.emplace("Accept-Encoding", "gzip, deflate");
  6024. cli_.set_decompress(false);
  6025. auto res = cli_.Get("/compress", headers);
  6026. ASSERT_TRUE(res);
  6027. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6030. EXPECT_EQ(33U, res->body.size());
  6031. EXPECT_EQ(StatusCode::OK_200, res->status);
  6032. }
  6033. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6034. Headers headers;
  6035. headers.emplace("Accept-Encoding", "");
  6036. std::string body;
  6037. auto res = cli_.Get("/compress", headers,
  6038. [&](const char *data, uint64_t data_length) {
  6039. EXPECT_EQ(100U, data_length);
  6040. body.append(data, data_length);
  6041. return true;
  6042. });
  6043. ASSERT_TRUE(res);
  6044. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6046. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6047. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6048. "7890123456789012345678901234567890",
  6049. body);
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. }
  6052. TEST_F(ServerTest, NoGzip) {
  6053. Headers headers;
  6054. headers.emplace("Accept-Encoding", "gzip, deflate");
  6055. auto res = cli_.Get("/nocompress", headers);
  6056. ASSERT_TRUE(res);
  6057. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6058. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6059. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6060. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6061. "7890123456789012345678901234567890",
  6062. res->body);
  6063. EXPECT_EQ(StatusCode::OK_200, res->status);
  6064. }
  6065. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6066. Headers headers;
  6067. headers.emplace("Accept-Encoding", "gzip, deflate");
  6068. std::string body;
  6069. auto res = cli_.Get("/nocompress", headers,
  6070. [&](const char *data, uint64_t data_length) {
  6071. EXPECT_EQ(100U, data_length);
  6072. body.append(data, data_length);
  6073. return true;
  6074. });
  6075. ASSERT_TRUE(res);
  6076. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6077. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6080. "7890123456789012345678901234567890",
  6081. body);
  6082. EXPECT_EQ(StatusCode::OK_200, res->status);
  6083. }
  6084. TEST_F(ServerTest, MultipartFormDataGzip) {
  6085. UploadFormDataItems items = {
  6086. {"key1", "test", "", ""},
  6087. {"key2", "--abcdefg123", "", ""},
  6088. };
  6089. cli_.set_compress(true);
  6090. auto res = cli_.Post("/compress-multipart", items);
  6091. ASSERT_TRUE(res);
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. }
  6094. #endif
  6095. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6096. TEST_F(ServerTest, Brotli) {
  6097. Headers headers;
  6098. headers.emplace("Accept-Encoding", "br");
  6099. auto res = cli_.Get("/compress", headers);
  6100. ASSERT_TRUE(res);
  6101. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6103. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6104. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6105. "7890123456789012345678901234567890",
  6106. res->body);
  6107. EXPECT_EQ(StatusCode::OK_200, res->status);
  6108. }
  6109. #endif
  6110. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6111. TEST_F(ServerTest, Zstd) {
  6112. Headers headers;
  6113. headers.emplace("Accept-Encoding", "zstd");
  6114. auto res = cli_.Get("/compress", headers);
  6115. ASSERT_TRUE(res);
  6116. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6118. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6120. "7890123456789012345678901234567890",
  6121. res->body);
  6122. EXPECT_EQ(StatusCode::OK_200, res->status);
  6123. }
  6124. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6125. Headers headers;
  6126. headers.emplace("Accept-Encoding", "");
  6127. auto res = cli_.Get("/compress", headers);
  6128. ASSERT_TRUE(res);
  6129. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6130. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6131. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6133. "7890123456789012345678901234567890",
  6134. res->body);
  6135. EXPECT_EQ(StatusCode::OK_200, res->status);
  6136. }
  6137. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6138. Headers headers;
  6139. headers.emplace("Accept-Encoding", "zstd");
  6140. std::string body;
  6141. auto res = cli_.Get("/compress", headers,
  6142. [&](const char *data, uint64_t data_length) {
  6143. EXPECT_EQ(100U, data_length);
  6144. body.append(data, data_length);
  6145. return true;
  6146. });
  6147. ASSERT_TRUE(res);
  6148. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6150. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6151. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6152. "7890123456789012345678901234567890",
  6153. body);
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. }
  6156. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6157. Headers headers;
  6158. headers.emplace("Accept-Encoding", "zstd");
  6159. cli_.set_decompress(false);
  6160. auto res = cli_.Get("/compress", headers);
  6161. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6162. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6163. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6164. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6165. ASSERT_TRUE(res);
  6166. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6168. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6169. EXPECT_EQ(StatusCode::OK_200, res->status);
  6170. ASSERT_EQ(26U, res->body.size());
  6171. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6172. 0);
  6173. }
  6174. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6175. Headers headers;
  6176. headers.emplace("Accept-Encoding", "");
  6177. std::string body;
  6178. auto res = cli_.Get("/compress", headers,
  6179. [&](const char *data, uint64_t data_length) {
  6180. EXPECT_EQ(100U, data_length);
  6181. body.append(data, data_length);
  6182. return true;
  6183. });
  6184. ASSERT_TRUE(res);
  6185. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6188. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6189. "7890123456789012345678901234567890",
  6190. body);
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. }
  6193. TEST_F(ServerTest, NoZstd) {
  6194. Headers headers;
  6195. headers.emplace("Accept-Encoding", "zstd");
  6196. auto res = cli_.Get("/nocompress", headers);
  6197. ASSERT_TRUE(res);
  6198. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6199. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6200. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6201. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6202. "7890123456789012345678901234567890",
  6203. res->body);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. }
  6206. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6207. Headers headers;
  6208. headers.emplace("Accept-Encoding", "zstd");
  6209. std::string body;
  6210. auto res = cli_.Get("/nocompress", headers,
  6211. [&](const char *data, uint64_t data_length) {
  6212. EXPECT_EQ(100U, data_length);
  6213. body.append(data, data_length);
  6214. return true;
  6215. });
  6216. ASSERT_TRUE(res);
  6217. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6218. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6219. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6220. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6221. "7890123456789012345678901234567890",
  6222. body);
  6223. EXPECT_EQ(StatusCode::OK_200, res->status);
  6224. }
  6225. // TODO: How to enable zstd ??
  6226. TEST_F(ServerTest, MultipartFormDataZstd) {
  6227. UploadFormDataItems items = {
  6228. {"key1", "test", "", ""},
  6229. {"key2", "--abcdefg123", "", ""},
  6230. };
  6231. Headers headers;
  6232. headers.emplace("Accept-Encoding", "zstd");
  6233. cli_.set_compress(true);
  6234. auto res = cli_.Post("/compress-multipart", headers, items);
  6235. ASSERT_TRUE(res);
  6236. EXPECT_EQ(StatusCode::OK_200, res->status);
  6237. }
  6238. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6239. Headers headers;
  6240. headers.emplace("Accept-Encoding", "zstd");
  6241. cli_.set_compress(true);
  6242. auto res = cli_.Put(
  6243. "/put", headers, 3,
  6244. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6245. sink.os << "PUT";
  6246. return true;
  6247. },
  6248. "text/plain");
  6249. ASSERT_TRUE(res);
  6250. EXPECT_EQ(StatusCode::OK_200, res->status);
  6251. EXPECT_EQ("PUT", res->body);
  6252. }
  6253. // Pre-compression logging tests
  6254. TEST_F(ServerTest, PreCompressionLogging) {
  6255. // Test data for compression (matches the actual /compress endpoint content)
  6256. const std::string test_content =
  6257. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6258. "3456789012345678901234567890";
  6259. // Variables to capture logging data
  6260. std::string pre_compression_body;
  6261. std::string pre_compression_content_type;
  6262. std::string pre_compression_content_encoding;
  6263. std::string post_compression_body;
  6264. std::string post_compression_content_type;
  6265. std::string post_compression_content_encoding;
  6266. // Set up pre-compression logger
  6267. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6268. const Response &res) {
  6269. pre_compression_body = res.body;
  6270. pre_compression_content_type = res.get_header_value("Content-Type");
  6271. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6272. });
  6273. // Set up post-compression logger
  6274. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6275. post_compression_body = res.body;
  6276. post_compression_content_type = res.get_header_value("Content-Type");
  6277. post_compression_content_encoding =
  6278. res.get_header_value("Content-Encoding");
  6279. });
  6280. // Test with gzip compression
  6281. Headers headers;
  6282. headers.emplace("Accept-Encoding", "gzip");
  6283. auto res = cli_.Get("/compress", headers);
  6284. // Verify response was compressed
  6285. ASSERT_TRUE(res);
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6288. // Verify pre-compression logger captured uncompressed content
  6289. EXPECT_EQ(test_content, pre_compression_body);
  6290. EXPECT_EQ("text/plain", pre_compression_content_type);
  6291. EXPECT_TRUE(pre_compression_content_encoding
  6292. .empty()); // No encoding header before compression
  6293. // Verify post-compression logger captured compressed content
  6294. EXPECT_NE(test_content,
  6295. post_compression_body); // Should be different after compression
  6296. EXPECT_EQ("text/plain", post_compression_content_type);
  6297. EXPECT_EQ("gzip", post_compression_content_encoding);
  6298. // Verify compressed content is smaller
  6299. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6300. }
  6301. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6302. const std::string test_content =
  6303. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6304. "3456789012345678901234567890";
  6305. std::string pre_compression_body;
  6306. std::string post_compression_body;
  6307. svr_.set_pre_compression_logger(
  6308. [&](const Request & /*req*/, const Response &res) {
  6309. pre_compression_body = res.body;
  6310. });
  6311. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6312. post_compression_body = res.body;
  6313. });
  6314. Headers headers;
  6315. headers.emplace("Accept-Encoding", "br");
  6316. auto res = cli_.Get("/compress", headers);
  6317. ASSERT_TRUE(res);
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6320. // Verify pre-compression content is uncompressed
  6321. EXPECT_EQ(test_content, pre_compression_body);
  6322. // Verify post-compression content is compressed
  6323. EXPECT_NE(test_content, post_compression_body);
  6324. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6325. }
  6326. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6327. const std::string test_content =
  6328. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6329. "3456789012345678901234567890";
  6330. std::string pre_compression_body;
  6331. std::string post_compression_body;
  6332. svr_.set_pre_compression_logger(
  6333. [&](const Request & /*req*/, const Response &res) {
  6334. pre_compression_body = res.body;
  6335. });
  6336. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6337. post_compression_body = res.body;
  6338. });
  6339. // Request without compression (use /nocompress endpoint)
  6340. Headers headers;
  6341. auto res = cli_.Get("/nocompress", headers);
  6342. ASSERT_TRUE(res);
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6345. // Pre-compression logger should not be called when no compression is applied
  6346. EXPECT_TRUE(
  6347. pre_compression_body.empty()); // Pre-compression logger not called
  6348. EXPECT_EQ(
  6349. test_content,
  6350. post_compression_body); // Post-compression logger captures final content
  6351. }
  6352. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6353. const std::string test_content =
  6354. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6355. "3456789012345678901234567890";
  6356. std::string pre_compression_body;
  6357. bool pre_logger_called = false;
  6358. // Set only pre-compression logger
  6359. svr_.set_pre_compression_logger(
  6360. [&](const Request & /*req*/, const Response &res) {
  6361. pre_compression_body = res.body;
  6362. pre_logger_called = true;
  6363. });
  6364. Headers headers;
  6365. headers.emplace("Accept-Encoding", "gzip");
  6366. auto res = cli_.Get("/compress", headers);
  6367. ASSERT_TRUE(res);
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6370. // Verify pre-compression logger was called
  6371. EXPECT_TRUE(pre_logger_called);
  6372. EXPECT_EQ(test_content, pre_compression_body);
  6373. }
  6374. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6375. {
  6376. // Test with Expect: 100-continue header - success case
  6377. // Server returns 100 Continue, client sends body, server returns 200 OK
  6378. Request req;
  6379. req.method = "POST";
  6380. req.path = "/post-large";
  6381. req.set_header("Expect", "100-continue");
  6382. req.body = LARGE_DATA;
  6383. Response res;
  6384. auto error = Error::Success;
  6385. cli_.set_keep_alive(true);
  6386. auto ret = cli_.send(req, res, error);
  6387. EXPECT_TRUE(ret);
  6388. EXPECT_EQ(StatusCode::OK_200, res.status);
  6389. EXPECT_EQ(LARGE_DATA, res.body);
  6390. }
  6391. {
  6392. // Test with Expect: 100-continue header - error case
  6393. // Client should not send the body when server returns an error
  6394. Request req;
  6395. req.method = "POST";
  6396. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6397. req.set_header("Expect", "100-continue");
  6398. req.body = LARGE_DATA;
  6399. Response res;
  6400. auto error = Error::Success;
  6401. auto start = std::chrono::high_resolution_clock::now();
  6402. cli_.set_keep_alive(true);
  6403. auto ret = cli_.send(req, res, error);
  6404. auto end = std::chrono::high_resolution_clock::now();
  6405. auto elapsed =
  6406. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6407. .count();
  6408. // With Expect: 100-continue, request completes successfully but with error
  6409. EXPECT_TRUE(ret);
  6410. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6411. EXPECT_EQ("close", res.get_header_value("Connection"));
  6412. EXPECT_FALSE(cli_.is_socket_open());
  6413. EXPECT_LE(elapsed, 2000);
  6414. }
  6415. {
  6416. // Send an extra GET request to ensure error recovery without hanging
  6417. Request req;
  6418. req.method = "GET";
  6419. req.path = "/hi";
  6420. auto start = std::chrono::high_resolution_clock::now();
  6421. auto res = cli_.send(req);
  6422. auto end = std::chrono::high_resolution_clock::now();
  6423. auto elapsed =
  6424. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6425. .count();
  6426. ASSERT_TRUE(res);
  6427. EXPECT_EQ(StatusCode::OK_200, res->status);
  6428. EXPECT_EQ("Hello World!", res->body);
  6429. EXPECT_LE(elapsed, 500);
  6430. }
  6431. }
  6432. TEST(ZstdDecompressor, ChunkedDecompression) {
  6433. std::string data;
  6434. for (size_t i = 0; i < 32 * 1024; ++i) {
  6435. data.push_back(static_cast<char>('a' + i % 26));
  6436. }
  6437. std::string compressed_data;
  6438. {
  6439. httplib::detail::zstd_compressor compressor;
  6440. bool result = compressor.compress(
  6441. data.data(), data.size(),
  6442. /*last=*/true,
  6443. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6444. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6445. compressed_data_size);
  6446. return true;
  6447. });
  6448. ASSERT_TRUE(result);
  6449. }
  6450. std::string decompressed_data;
  6451. {
  6452. httplib::detail::zstd_decompressor decompressor;
  6453. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6454. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6455. size_t chunk_size = 130;
  6456. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6457. chunk_begin += chunk_size) {
  6458. size_t current_chunk_size =
  6459. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6460. bool result = decompressor.decompress(
  6461. compressed_data.data() + chunk_begin, current_chunk_size,
  6462. [&](const char *decompressed_data_chunk,
  6463. size_t decompressed_data_chunk_size) {
  6464. decompressed_data.insert(decompressed_data.size(),
  6465. decompressed_data_chunk,
  6466. decompressed_data_chunk_size);
  6467. return true;
  6468. });
  6469. ASSERT_TRUE(result);
  6470. }
  6471. }
  6472. ASSERT_EQ(data, decompressed_data);
  6473. }
  6474. TEST(ZstdDecompressor, Decompress) {
  6475. std::string original_text = "Compressed with ZSTD";
  6476. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6477. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6478. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6479. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6480. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6481. std::string decompressed_data;
  6482. {
  6483. httplib::detail::zstd_decompressor decompressor;
  6484. bool result = decompressor.decompress(
  6485. compressed_data.data(), compressed_data.size(),
  6486. [&](const char *decompressed_data_chunk,
  6487. size_t decompressed_data_chunk_size) {
  6488. decompressed_data.insert(decompressed_data.size(),
  6489. decompressed_data_chunk,
  6490. decompressed_data_chunk_size);
  6491. return true;
  6492. });
  6493. ASSERT_TRUE(result);
  6494. }
  6495. ASSERT_EQ(original_text, decompressed_data);
  6496. }
  6497. #endif
  6498. // Sends a raw request to a server listening at HOST:PORT.
  6499. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6500. std::string *resp = nullptr) {
  6501. auto error = Error::Success;
  6502. auto client_sock = detail::create_client_socket(
  6503. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6504. /*connection_timeout_sec=*/5, 0,
  6505. /*read_timeout_sec=*/5, 0,
  6506. /*write_timeout_sec=*/5, 0, std::string(), error);
  6507. if (client_sock == INVALID_SOCKET) { return false; }
  6508. auto ret = detail::process_client_socket(
  6509. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6510. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6511. if (req.size() !=
  6512. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6513. return false;
  6514. }
  6515. char buf[512];
  6516. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6517. while (line_reader.getline()) {
  6518. if (resp) { *resp += line_reader.ptr(); }
  6519. }
  6520. return true;
  6521. });
  6522. detail::close_socket(client_sock);
  6523. return ret;
  6524. }
  6525. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6526. Server svr;
  6527. std::string header_value;
  6528. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6529. header_value = req.get_header_value("foo");
  6530. res.set_content("ok", "text/plain");
  6531. });
  6532. thread t = thread([&] { svr.listen(HOST, PORT); });
  6533. auto se = detail::scope_exit([&] {
  6534. svr.stop();
  6535. t.join();
  6536. ASSERT_FALSE(svr.is_running());
  6537. });
  6538. svr.wait_until_ready();
  6539. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6540. // like characters are not treated the same - use vertical tab and escape.
  6541. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6542. "foo: \t \v bar \x1B\t \r\n"
  6543. "Connection: close\r\n"
  6544. "\r\n";
  6545. std::string res;
  6546. ASSERT_TRUE(send_request(5, req, &res));
  6547. EXPECT_EQ(header_value, "");
  6548. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6549. }
  6550. // Sends a raw request and verifies that there isn't a crash or exception.
  6551. static void test_raw_request(const std::string &req,
  6552. std::string *out = nullptr) {
  6553. Server svr;
  6554. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6555. res.set_content("ok", "text/plain");
  6556. });
  6557. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6558. res.set_content("ok", "text/plain");
  6559. });
  6560. svr.Get("/header_field_value_check",
  6561. [&](const Request & /*req*/, Response &res) {
  6562. res.set_content("ok", "text/plain");
  6563. });
  6564. // Server read timeout must be longer than the client read timeout for the
  6565. // bug to reproduce, probably to force the server to process a request
  6566. // without a trailing blank line.
  6567. const time_t client_read_timeout_sec = 1;
  6568. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6569. bool listen_thread_ok = false;
  6570. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6571. auto se = detail::scope_exit([&] {
  6572. svr.stop();
  6573. t.join();
  6574. ASSERT_FALSE(svr.is_running());
  6575. EXPECT_TRUE(listen_thread_ok);
  6576. });
  6577. svr.wait_until_ready();
  6578. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6579. }
  6580. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6581. // A certain header line causes an exception if the header property is parsed
  6582. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6583. test_raw_request(
  6584. "GET /hi HTTP/1.1\r\n"
  6585. " : "
  6586. " "
  6587. " ");
  6588. }
  6589. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6590. // A certain header line causes an exception if the header property *name* is
  6591. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6592. // greedy matcher and requires backtracking when there are a lot of ":"
  6593. // characters.
  6594. // This occurs with libc++ but not libstdc++.
  6595. test_raw_request(
  6596. "GET /hi HTTP/1.1\r\n"
  6597. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6598. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6599. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6600. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6601. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6602. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6603. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6604. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6605. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6606. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6607. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6608. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6609. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6610. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6611. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6612. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6613. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6614. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6615. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6616. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6617. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6618. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6619. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6620. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6621. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6622. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6623. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6624. "&&&%%%");
  6625. }
  6626. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6627. // Make sure this doesn't crash the server.
  6628. // In a previous version of the header line regex, the "\r" rendered the line
  6629. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6630. // a new position where the leading white space ended and the field value
  6631. // began.
  6632. // The crash occurs with libc++ but not libstdc++.
  6633. test_raw_request("GET /hi HTTP/1.1\r\n"
  6634. "a:" +
  6635. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6636. "\r\n"
  6637. "\r\n");
  6638. }
  6639. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6640. std::string out;
  6641. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6642. "Content-Type: text/plain\r\n"
  6643. "Transfer-Encoding: chunked\r\n"
  6644. "\r\n"
  6645. "nothex\r\n",
  6646. &out);
  6647. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6648. }
  6649. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6650. std::string out;
  6651. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6652. "Content-Type: text/plain\r\n"
  6653. "Transfer-Encoding: chunked\r\n"
  6654. "\r\n"
  6655. "3\r\n"
  6656. "xyz\r\n"
  6657. "NaN\r\n",
  6658. &out);
  6659. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6660. }
  6661. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6662. std::string out;
  6663. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6664. "Content-Type: text/plain\r\n"
  6665. "Transfer-Encoding: chunked\r\n"
  6666. "\r\n"
  6667. // Length is too large for 64 bits.
  6668. "1ffffffffffffffff\r\n"
  6669. "xyz\r\n",
  6670. &out);
  6671. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6672. }
  6673. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6674. test_raw_request("GET /hi HTTP/1.1\r\n"
  6675. "Content-Type: text/plain\r\n\r");
  6676. }
  6677. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6678. std::string out;
  6679. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6680. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6681. }
  6682. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6683. Server svr;
  6684. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6685. EXPECT_TRUE(!req.remote_addr.empty());
  6686. });
  6687. thread t = thread([&] { svr.listen(HOST, PORT); });
  6688. auto se = detail::scope_exit([&] {
  6689. svr.stop();
  6690. t.join();
  6691. ASSERT_FALSE(svr.is_running());
  6692. });
  6693. svr.wait_until_ready();
  6694. // Send an invalid request line to trigger Bad Request
  6695. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6696. std::string out;
  6697. ASSERT_TRUE(send_request(5, bad_req, &out));
  6698. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6699. }
  6700. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6701. std::string out;
  6702. std::string request(
  6703. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6704. test_raw_request(request, &out);
  6705. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6706. }
  6707. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6708. std::string out;
  6709. std::string request(
  6710. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6711. test_raw_request(request, &out);
  6712. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6713. }
  6714. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6715. std::string out;
  6716. std::string request(
  6717. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6718. test_raw_request(request, &out);
  6719. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6720. }
  6721. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6722. std::string out;
  6723. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6724. "Test: \r\n\r\n",
  6725. &out);
  6726. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6727. }
  6728. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6729. Server svr;
  6730. std::string x_custom;
  6731. std::string cookie;
  6732. std::string xff;
  6733. std::string x_unicode;
  6734. std::string x_iis;
  6735. svr.Get("/check", [&](const Request &req, Response &res) {
  6736. x_custom = req.get_header_value("X-Custom");
  6737. cookie = req.get_header_value("Cookie");
  6738. xff = req.get_header_value("X-Forwarded-For");
  6739. x_unicode = req.get_header_value("X-Unicode");
  6740. x_iis = req.get_header_value("X-IIS");
  6741. res.set_content("ok", "text/plain");
  6742. });
  6743. thread t = thread([&] { svr.listen(HOST, PORT); });
  6744. auto se = detail::scope_exit([&] {
  6745. svr.stop();
  6746. t.join();
  6747. ASSERT_FALSE(svr.is_running());
  6748. });
  6749. svr.wait_until_ready();
  6750. const std::string req = "GET /check HTTP/1.1\r\n"
  6751. "Host: localhost\r\n"
  6752. "X-Custom: a%0D%0AInjected: b\r\n"
  6753. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6754. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6755. "X-Unicode: %E3%81%82\r\n"
  6756. "X-IIS: %u00E9\r\n"
  6757. "Connection: close\r\n"
  6758. "\r\n";
  6759. std::string res;
  6760. ASSERT_TRUE(send_request(5, req, &res));
  6761. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6762. // Every value must be returned verbatim (wire form), with no decoding.
  6763. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6764. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6765. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6766. EXPECT_EQ("%E3%81%82", x_unicode);
  6767. EXPECT_EQ("%u00E9", x_iis);
  6768. }
  6769. // Applications that previously relied on automatic percent-decoding can
  6770. // reproduce the old behavior by explicitly calling decode_path_component()
  6771. // or, for RFC 3986 conformance, decode_uri_component().
  6772. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6773. Server svr;
  6774. std::string decoded;
  6775. svr.Get("/check", [&](const Request &req, Response &res) {
  6776. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6777. res.set_content("ok", "text/plain");
  6778. });
  6779. thread t = thread([&] { svr.listen(HOST, PORT); });
  6780. auto se = detail::scope_exit([&] {
  6781. svr.stop();
  6782. t.join();
  6783. ASSERT_FALSE(svr.is_running());
  6784. });
  6785. svr.wait_until_ready();
  6786. const std::string req = "GET /check HTTP/1.1\r\n"
  6787. "Host: localhost\r\n"
  6788. "X-Custom: hello%20world\r\n"
  6789. "Connection: close\r\n"
  6790. "\r\n";
  6791. std::string res;
  6792. ASSERT_TRUE(send_request(5, req, &res));
  6793. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6794. EXPECT_EQ("hello world", decoded);
  6795. }
  6796. // Regression test for #2033. Browsers send Referer values that include
  6797. // percent-encoded characters such as %0A inside the URL. Decoding the
  6798. // header value would either trip the post-decode CR/LF/NUL guard (the
  6799. // original bug, returning 400) or, after that guard was relaxed, silently
  6800. // store a literal LF — both unacceptable. The wire form must round-trip.
  6801. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6802. Server svr;
  6803. std::string referer;
  6804. svr.Get("/check", [&](const Request &req, Response &res) {
  6805. referer = req.get_header_value("Referer");
  6806. res.set_content("ok", "text/plain");
  6807. });
  6808. thread t = thread([&] { svr.listen(HOST, PORT); });
  6809. auto se = detail::scope_exit([&] {
  6810. svr.stop();
  6811. t.join();
  6812. ASSERT_FALSE(svr.is_running());
  6813. });
  6814. svr.wait_until_ready();
  6815. const std::string req = "GET /check HTTP/1.1\r\n"
  6816. "Host: localhost\r\n"
  6817. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6818. "Connection: close\r\n"
  6819. "\r\n";
  6820. std::string res;
  6821. ASSERT_TRUE(send_request(5, req, &res));
  6822. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6823. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6824. }
  6825. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6826. Server svr;
  6827. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6828. res.set_header("Cache-Control", "no-cache");
  6829. res.set_chunked_content_provider(
  6830. "text/event-stream", [](size_t offset, DataSink &sink) {
  6831. std::string s = "data:";
  6832. s += std::to_string(offset);
  6833. s += "\n\n";
  6834. auto ret = sink.write(s.data(), s.size());
  6835. EXPECT_TRUE(ret);
  6836. std::this_thread::sleep_for(std::chrono::seconds(1));
  6837. return true;
  6838. });
  6839. });
  6840. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6841. svr.wait_until_ready();
  6842. Client client(HOST, PORT);
  6843. const Headers headers = {{"Accept", "text/event-stream"}};
  6844. auto get_thread = std::thread([&client, &headers]() {
  6845. auto res = client.Get(
  6846. "/events", headers,
  6847. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6848. });
  6849. auto se = detail::scope_exit([&] {
  6850. svr.stop();
  6851. get_thread.join();
  6852. listen_thread.join();
  6853. ASSERT_FALSE(svr.is_running());
  6854. });
  6855. // Give GET time to get a few messages.
  6856. std::this_thread::sleep_for(std::chrono::seconds(2));
  6857. }
  6858. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6859. httplib::Server svr;
  6860. svr.Post("/hi",
  6861. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6862. res.status = StatusCode::OK_200;
  6863. });
  6864. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6865. svr.wait_until_ready();
  6866. Client cli(HOST, PORT);
  6867. auto res = cli.Post("/hi", "data", "text/plain");
  6868. ASSERT_TRUE(res);
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. svr.stop();
  6871. thread.join();
  6872. ASSERT_FALSE(svr.is_running());
  6873. res = cli.Post("/hi", "data", "text/plain");
  6874. ASSERT_FALSE(res);
  6875. }
  6876. TEST(ServerStopTest, ListenFailure) {
  6877. Server svr;
  6878. auto t = thread([&]() {
  6879. auto ret = svr.listen("????", PORT);
  6880. EXPECT_FALSE(ret);
  6881. });
  6882. svr.wait_until_ready();
  6883. svr.stop();
  6884. t.join();
  6885. }
  6886. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6887. TEST(ServerStopTest, Decommision) {
  6888. Server svr;
  6889. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6890. for (int i = 0; i < 4; i++) {
  6891. auto is_even = !(i % 2);
  6892. std::thread t{[&] {
  6893. try {
  6894. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6895. if (is_even) {
  6896. throw std::runtime_error("Some thing that happens to go wrong.");
  6897. }
  6898. svr.listen(HOST, PORT);
  6899. } catch (...) { svr.decommission(); }
  6900. }};
  6901. svr.wait_until_ready();
  6902. // Server is up
  6903. {
  6904. Client cli(HOST, PORT);
  6905. auto res = cli.Get("/hi");
  6906. if (is_even) {
  6907. EXPECT_FALSE(res);
  6908. } else {
  6909. EXPECT_TRUE(res);
  6910. EXPECT_EQ("hi...", res->body);
  6911. }
  6912. }
  6913. svr.stop();
  6914. t.join();
  6915. // Server is down...
  6916. {
  6917. Client cli(HOST, PORT);
  6918. auto res = cli.Get("/hi");
  6919. EXPECT_FALSE(res);
  6920. }
  6921. }
  6922. }
  6923. #endif
  6924. // Helper function for string body upload progress tests
  6925. template <typename SetupHandler, typename ClientCall>
  6926. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6927. ClientCall &&client_call,
  6928. const string &body) {
  6929. Server svr;
  6930. setup_handler(svr);
  6931. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6932. auto se = detail::scope_exit([&] {
  6933. svr.stop();
  6934. t.join();
  6935. });
  6936. svr.wait_until_ready();
  6937. Client cli(HOST, PORT);
  6938. vector<uint64_t> progress_values;
  6939. bool progress_called = false;
  6940. auto res =
  6941. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6942. progress_values.push_back(current);
  6943. progress_called = true;
  6944. return true;
  6945. });
  6946. ASSERT_TRUE(res);
  6947. EXPECT_EQ(200, res->status);
  6948. EXPECT_TRUE(progress_called);
  6949. }
  6950. TEST(UploadProgressTest, PostStringBodyBasic) {
  6951. TestStringBodyUploadProgress(
  6952. [](Server &svr) {
  6953. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6954. res.set_content("received", "text/plain");
  6955. });
  6956. },
  6957. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6958. return cli.Post("/test", body, "text/plain", progress_callback);
  6959. },
  6960. "test data for upload progress");
  6961. }
  6962. TEST(UploadProgressTest, PutStringBodyBasic) {
  6963. TestStringBodyUploadProgress(
  6964. [](Server &svr) {
  6965. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6966. res.set_content("put received", "text/plain");
  6967. });
  6968. },
  6969. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6970. return cli.Put("/test", body, "text/plain", progress_callback);
  6971. },
  6972. "put test data for upload progress");
  6973. }
  6974. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6975. TestStringBodyUploadProgress(
  6976. [](Server &svr) {
  6977. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6978. res.set_content("patch received", "text/plain");
  6979. });
  6980. },
  6981. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6982. return cli.Patch("/test", body, "text/plain", progress_callback);
  6983. },
  6984. "patch test data for upload progress");
  6985. }
  6986. // Helper function for content provider upload progress tests
  6987. template <typename SetupHandler, typename ClientCall>
  6988. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6989. ClientCall &&client_call) {
  6990. Server svr;
  6991. setup_handler(svr);
  6992. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6993. auto se = detail::scope_exit([&] {
  6994. svr.stop();
  6995. t.join();
  6996. });
  6997. svr.wait_until_ready();
  6998. Client cli(HOST, PORT);
  6999. vector<uint64_t> progress_values;
  7000. auto res =
  7001. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7002. progress_values.push_back(current);
  7003. return true;
  7004. });
  7005. ASSERT_TRUE(res);
  7006. EXPECT_EQ(200, res->status);
  7007. EXPECT_FALSE(progress_values.empty());
  7008. }
  7009. TEST(UploadProgressTest, PostContentProviderProgress) {
  7010. TestContentProviderUploadProgress(
  7011. [](Server &svr) {
  7012. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7013. res.set_content("provider received", "text/plain");
  7014. });
  7015. },
  7016. [](Client &cli, UploadProgress progress_callback) {
  7017. return cli.Post(
  7018. "/test", 10,
  7019. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7020. sink.os << "test data";
  7021. return true;
  7022. },
  7023. "text/plain", progress_callback);
  7024. });
  7025. }
  7026. // Helper function for multipart upload progress tests
  7027. template <typename SetupHandler, typename ClientCall>
  7028. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7029. ClientCall &&client_call,
  7030. const string &endpoint) {
  7031. Server svr;
  7032. setup_handler(svr);
  7033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7034. auto se = detail::scope_exit([&] {
  7035. svr.stop();
  7036. t.join();
  7037. });
  7038. svr.wait_until_ready();
  7039. Client cli(HOST, PORT);
  7040. vector<uint64_t> progress_values;
  7041. UploadFormDataItems items = {
  7042. {"field1", "value1", "", ""},
  7043. {"field2", "longer value for progress tracking test", "", ""},
  7044. {"file1", "file content data for upload progress", "test.txt",
  7045. "text/plain"}};
  7046. auto res = client_call(cli, endpoint, items,
  7047. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7048. progress_values.push_back(current);
  7049. return true;
  7050. });
  7051. ASSERT_TRUE(res);
  7052. EXPECT_EQ(200, res->status);
  7053. EXPECT_FALSE(progress_values.empty());
  7054. }
  7055. TEST(UploadProgressTest, PostMultipartProgress) {
  7056. TestMultipartUploadProgress(
  7057. [](Server &svr) {
  7058. svr.Post("/multipart", [](const Request &req, Response &res) {
  7059. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7060. res.set_content("multipart received", "text/plain");
  7061. });
  7062. },
  7063. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7064. UploadProgress progress_callback) {
  7065. return cli.Post(endpoint, items, progress_callback);
  7066. },
  7067. "/multipart");
  7068. }
  7069. // Helper function for basic download progress tests
  7070. template <typename SetupHandler, typename ClientCall>
  7071. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7072. ClientCall &&client_call, const string &endpoint,
  7073. size_t expected_content_size) {
  7074. Server svr;
  7075. setup_handler(svr);
  7076. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7077. auto se = detail::scope_exit([&] {
  7078. svr.stop();
  7079. t.join();
  7080. });
  7081. svr.wait_until_ready();
  7082. Client cli(HOST, PORT);
  7083. vector<uint64_t> progress_values;
  7084. auto res = client_call(cli, endpoint,
  7085. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7086. progress_values.push_back(current);
  7087. return true;
  7088. });
  7089. ASSERT_TRUE(res);
  7090. EXPECT_EQ(200, res->status);
  7091. EXPECT_FALSE(progress_values.empty());
  7092. EXPECT_EQ(expected_content_size, res->body.size());
  7093. }
  7094. TEST(DownloadProgressTest, GetBasic) {
  7095. TestBasicDownloadProgress(
  7096. [](Server &svr) {
  7097. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7098. string content(1000, 'D');
  7099. res.set_content(content, "text/plain");
  7100. });
  7101. },
  7102. [](Client &cli, const string &endpoint,
  7103. DownloadProgress progress_callback) {
  7104. return cli.Get(endpoint, progress_callback);
  7105. },
  7106. "/download", 1000u);
  7107. }
  7108. // Helper function for content receiver download progress tests
  7109. template <typename SetupHandler, typename ClientCall>
  7110. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7111. ClientCall &&client_call,
  7112. const string &endpoint,
  7113. size_t expected_content_size) {
  7114. Server svr;
  7115. setup_handler(svr);
  7116. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7117. auto se = detail::scope_exit([&] {
  7118. svr.stop();
  7119. t.join();
  7120. });
  7121. svr.wait_until_ready();
  7122. Client cli(HOST, PORT);
  7123. vector<uint64_t> progress_values;
  7124. string received_body;
  7125. auto res = client_call(
  7126. cli, endpoint,
  7127. [&](const char *data, size_t data_length) -> bool {
  7128. received_body.append(data, data_length);
  7129. return true;
  7130. },
  7131. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7132. progress_values.push_back(current);
  7133. return true;
  7134. });
  7135. ASSERT_TRUE(res);
  7136. EXPECT_EQ(200, res->status);
  7137. EXPECT_FALSE(progress_values.empty());
  7138. EXPECT_EQ(expected_content_size, received_body.size());
  7139. EXPECT_TRUE(res->body.empty());
  7140. }
  7141. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7142. TestContentReceiverDownloadProgress(
  7143. [](Server &svr) {
  7144. svr.Get("/download-receiver",
  7145. [](const Request & /*req*/, Response &res) {
  7146. string content(2000, 'R');
  7147. res.set_content(content, "text/plain");
  7148. });
  7149. },
  7150. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7151. DownloadProgress progress_callback) {
  7152. return cli.Get(endpoint, content_receiver, progress_callback);
  7153. },
  7154. "/download-receiver", 2000u);
  7155. }
  7156. TEST(StreamingTest, NoContentLengthStreaming) {
  7157. Server svr;
  7158. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7159. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7160. if (offset < 6) {
  7161. sink.os << (offset < 3 ? "a" : "b");
  7162. } else {
  7163. sink.done();
  7164. }
  7165. return true;
  7166. });
  7167. });
  7168. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7169. auto listen_se = detail::scope_exit([&] {
  7170. svr.stop();
  7171. listen_thread.join();
  7172. ASSERT_FALSE(svr.is_running());
  7173. });
  7174. svr.wait_until_ready();
  7175. Client client(HOST, PORT);
  7176. auto get_thread = std::thread([&client]() {
  7177. std::string s;
  7178. auto res =
  7179. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7180. s += std::string(data, len);
  7181. return true;
  7182. });
  7183. ASSERT_TRUE(res);
  7184. EXPECT_EQ(StatusCode::OK_200, res->status);
  7185. EXPECT_EQ("aaabbb", s);
  7186. });
  7187. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7188. // Give GET time to get a few messages.
  7189. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7190. }
  7191. TEST(MountTest, Unmount) {
  7192. Server svr;
  7193. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7194. auto se = detail::scope_exit([&] {
  7195. svr.stop();
  7196. listen_thread.join();
  7197. ASSERT_FALSE(svr.is_running());
  7198. });
  7199. svr.wait_until_ready();
  7200. Client cli("localhost", PORT);
  7201. svr.set_mount_point("/mount2", "./www2");
  7202. auto res = cli.Get("/");
  7203. ASSERT_TRUE(res);
  7204. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7205. res = cli.Get("/mount2/dir/test.html");
  7206. ASSERT_TRUE(res);
  7207. EXPECT_EQ(StatusCode::OK_200, res->status);
  7208. svr.set_mount_point("/", "./www");
  7209. res = cli.Get("/dir/");
  7210. ASSERT_TRUE(res);
  7211. EXPECT_EQ(StatusCode::OK_200, res->status);
  7212. svr.remove_mount_point("/");
  7213. res = cli.Get("/dir/");
  7214. ASSERT_TRUE(res);
  7215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7216. svr.remove_mount_point("/mount2");
  7217. res = cli.Get("/mount2/dir/test.html");
  7218. ASSERT_TRUE(res);
  7219. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7220. }
  7221. TEST(MountTest, Redicect) {
  7222. Server svr;
  7223. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7224. auto se = detail::scope_exit([&] {
  7225. svr.stop();
  7226. listen_thread.join();
  7227. ASSERT_FALSE(svr.is_running());
  7228. });
  7229. svr.set_mount_point("/", "./www");
  7230. svr.wait_until_ready();
  7231. Client cli("localhost", PORT);
  7232. auto res = cli.Get("/dir/");
  7233. ASSERT_TRUE(res);
  7234. EXPECT_EQ(StatusCode::OK_200, res->status);
  7235. res = cli.Get("/dir");
  7236. ASSERT_TRUE(res);
  7237. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7238. res = cli.Get("/file");
  7239. ASSERT_TRUE(res);
  7240. EXPECT_EQ(StatusCode::OK_200, res->status);
  7241. res = cli.Get("/file/");
  7242. ASSERT_TRUE(res);
  7243. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7244. cli.set_follow_location(true);
  7245. res = cli.Get("/dir");
  7246. ASSERT_TRUE(res);
  7247. EXPECT_EQ(StatusCode::OK_200, res->status);
  7248. }
  7249. TEST(MountTest, MultibytesPathName) {
  7250. Server svr;
  7251. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7252. auto se = detail::scope_exit([&] {
  7253. svr.stop();
  7254. listen_thread.join();
  7255. ASSERT_FALSE(svr.is_running());
  7256. });
  7257. svr.set_mount_point("/", "./www");
  7258. svr.wait_until_ready();
  7259. Client cli("localhost", PORT);
  7260. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7261. ASSERT_TRUE(res);
  7262. EXPECT_EQ(StatusCode::OK_200, res->status);
  7263. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7264. }
  7265. #ifdef _WIN32
  7266. // Issue #2435: mmap::open() must succeed even when another handle holds
  7267. // the file open for writing (e.g. an active log file).
  7268. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7269. const char *path = "mmap_concurrent_writer_test.txt";
  7270. const char *content = "hello";
  7271. {
  7272. std::ofstream f(path, std::ios::binary);
  7273. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7274. }
  7275. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7276. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7277. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7278. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7279. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7280. detail::mmap m(path);
  7281. ASSERT_TRUE(m.is_open());
  7282. EXPECT_EQ(strlen(content), m.size());
  7283. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7284. }
  7285. #endif
  7286. TEST(KeepAliveTest, ReadTimeout) {
  7287. Server svr;
  7288. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7289. std::this_thread::sleep_for(std::chrono::seconds(2));
  7290. res.set_content("a", "text/plain");
  7291. });
  7292. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7293. res.set_content("b", "text/plain");
  7294. });
  7295. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7296. auto se = detail::scope_exit([&] {
  7297. svr.stop();
  7298. listen_thread.join();
  7299. ASSERT_FALSE(svr.is_running());
  7300. });
  7301. svr.wait_until_ready();
  7302. Client cli("localhost", PORT);
  7303. cli.set_keep_alive(true);
  7304. cli.set_read_timeout(std::chrono::seconds(1));
  7305. auto resa = cli.Get("/a");
  7306. ASSERT_FALSE(resa);
  7307. EXPECT_EQ(Error::Read, resa.error());
  7308. auto resb = cli.Get("/b");
  7309. ASSERT_TRUE(resb);
  7310. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7311. EXPECT_EQ("b", resb->body);
  7312. }
  7313. TEST(KeepAliveTest, MaxCount) {
  7314. size_t keep_alive_max_count = 3;
  7315. Server svr;
  7316. svr.set_keep_alive_max_count(keep_alive_max_count);
  7317. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7318. res.set_content("Hello World!", "text/plain");
  7319. });
  7320. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7321. auto se = detail::scope_exit([&] {
  7322. svr.stop();
  7323. listen_thread.join();
  7324. ASSERT_FALSE(svr.is_running());
  7325. });
  7326. svr.wait_until_ready();
  7327. Client cli(HOST, PORT);
  7328. cli.set_keep_alive(true);
  7329. for (size_t i = 0; i < 5; i++) {
  7330. auto result = cli.Get("/hi");
  7331. ASSERT_TRUE(result);
  7332. EXPECT_EQ(StatusCode::OK_200, result->status);
  7333. if (i == keep_alive_max_count - 1) {
  7334. EXPECT_EQ("close", result->get_header_value("Connection"));
  7335. } else {
  7336. EXPECT_FALSE(result->has_header("Connection"));
  7337. }
  7338. }
  7339. }
  7340. TEST(KeepAliveTest, Issue1041) {
  7341. Server svr;
  7342. svr.set_keep_alive_timeout(3);
  7343. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7344. res.set_content("Hello World!", "text/plain");
  7345. });
  7346. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7347. auto se = detail::scope_exit([&] {
  7348. svr.stop();
  7349. listen_thread.join();
  7350. ASSERT_FALSE(svr.is_running());
  7351. });
  7352. svr.wait_until_ready();
  7353. Client cli(HOST, PORT);
  7354. cli.set_keep_alive(true);
  7355. auto result = cli.Get("/hi");
  7356. ASSERT_TRUE(result);
  7357. EXPECT_EQ(StatusCode::OK_200, result->status);
  7358. std::this_thread::sleep_for(std::chrono::seconds(5));
  7359. result = cli.Get("/hi");
  7360. ASSERT_TRUE(result);
  7361. EXPECT_EQ(StatusCode::OK_200, result->status);
  7362. }
  7363. TEST(KeepAliveTest, Issue1959) {
  7364. Server svr;
  7365. svr.set_keep_alive_timeout(5);
  7366. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7367. res.set_content("a", "text/plain");
  7368. });
  7369. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7370. auto se = detail::scope_exit([&] {
  7371. if (!svr.is_running()) return;
  7372. svr.stop();
  7373. listen_thread.join();
  7374. ASSERT_FALSE(svr.is_running());
  7375. });
  7376. svr.wait_until_ready();
  7377. Client cli("localhost", PORT);
  7378. cli.set_keep_alive(true);
  7379. using namespace std::chrono;
  7380. auto start = steady_clock::now();
  7381. cli.Get("/a");
  7382. svr.stop();
  7383. listen_thread.join();
  7384. auto end = steady_clock::now();
  7385. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7386. EXPECT_LT(elapsed, 5000);
  7387. }
  7388. #ifdef CPPHTTPLIB_SSL_ENABLED
  7389. TEST(KeepAliveTest, SSLClientReconnection) {
  7390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7391. ASSERT_TRUE(svr.is_valid());
  7392. svr.set_keep_alive_timeout(1);
  7393. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7394. res.set_content("Hello World!", "text/plain");
  7395. });
  7396. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7397. auto se = detail::scope_exit([&] {
  7398. svr.stop();
  7399. listen_thread.join();
  7400. ASSERT_FALSE(svr.is_running());
  7401. });
  7402. svr.wait_until_ready();
  7403. SSLClient cli(HOST, PORT);
  7404. cli.enable_server_certificate_verification(false);
  7405. cli.set_keep_alive(true);
  7406. auto result = cli.Get("/hi");
  7407. ASSERT_TRUE(result);
  7408. EXPECT_EQ(StatusCode::OK_200, result->status);
  7409. result = cli.Get("/hi");
  7410. ASSERT_TRUE(result);
  7411. EXPECT_EQ(StatusCode::OK_200, result->status);
  7412. std::this_thread::sleep_for(std::chrono::seconds(2));
  7413. // Recoonect
  7414. result = cli.Get("/hi");
  7415. ASSERT_TRUE(result);
  7416. EXPECT_EQ(StatusCode::OK_200, result->status);
  7417. result = cli.Get("/hi");
  7418. ASSERT_TRUE(result);
  7419. EXPECT_EQ(StatusCode::OK_200, result->status);
  7420. }
  7421. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7422. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7423. ASSERT_TRUE(svr.is_valid());
  7424. svr.set_keep_alive_timeout(1);
  7425. std::string content = "reconnect";
  7426. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7427. res.set_content("Hello World!", "text/plain");
  7428. });
  7429. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7430. auto se = detail::scope_exit([&] {
  7431. svr.stop();
  7432. listen_thread.join();
  7433. ASSERT_FALSE(svr.is_running());
  7434. });
  7435. svr.wait_until_ready();
  7436. SSLClient cli(HOST, PORT);
  7437. cli.enable_server_certificate_verification(false);
  7438. cli.set_keep_alive(true);
  7439. auto result = cli.Post(
  7440. "/hi", content.size(),
  7441. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7442. sink.write(content.c_str(), content.size());
  7443. return true;
  7444. },
  7445. "text/plain");
  7446. ASSERT_TRUE(result);
  7447. EXPECT_EQ(200, result->status);
  7448. std::this_thread::sleep_for(std::chrono::seconds(2));
  7449. // Recoonect
  7450. result = cli.Post(
  7451. "/hi", content.size(),
  7452. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7453. sink.write(content.c_str(), content.size());
  7454. return true;
  7455. },
  7456. "text/plain");
  7457. ASSERT_TRUE(result);
  7458. EXPECT_EQ(200, result->status);
  7459. result = cli.Post(
  7460. "/hi", content.size(),
  7461. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7462. sink.write(content.c_str(), content.size());
  7463. return true;
  7464. },
  7465. "text/plain");
  7466. ASSERT_TRUE(result);
  7467. EXPECT_EQ(200, result->status);
  7468. }
  7469. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7470. using namespace httplib::tls;
  7471. {
  7472. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7473. ASSERT_TRUE(svr.is_valid());
  7474. svr.Get("/sni", [&](const Request &req, Response &res) {
  7475. std::string expected = req.sni();
  7476. EXPECT_EQ(expected, req.get_param_value("expected"));
  7477. res.set_content("ok", "text/plain");
  7478. });
  7479. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7480. auto se = detail::scope_exit([&] {
  7481. svr.stop();
  7482. listen_thread.join();
  7483. ASSERT_FALSE(svr.is_running());
  7484. });
  7485. svr.wait_until_ready();
  7486. {
  7487. SSLClient cli("localhost", PORT);
  7488. cli.enable_server_certificate_verification(false);
  7489. auto res = cli.Get("/sni?expected=localhost");
  7490. ASSERT_TRUE(res);
  7491. }
  7492. {
  7493. SSLClient cli("::1", PORT);
  7494. cli.enable_server_certificate_verification(false);
  7495. auto res = cli.Get("/sni?expected=");
  7496. // NOTE: This may fail if the server is listening on IPv4 only
  7497. // (e.g., when localhost resolves to 127.0.0.1 only)
  7498. if (res) {
  7499. EXPECT_EQ(StatusCode::OK_200, res->status);
  7500. } else {
  7501. EXPECT_EQ(Error::Connection, res.error());
  7502. }
  7503. }
  7504. }
  7505. }
  7506. #endif
  7507. TEST(ClientProblemDetectionTest, ContentProvider) {
  7508. Server svr;
  7509. size_t content_length = 1024 * 1024;
  7510. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7511. res.set_content_provider(
  7512. content_length, "text/plain",
  7513. [&](size_t offset, size_t length, DataSink &sink) {
  7514. auto out_len = std::min(length, static_cast<size_t>(1024));
  7515. std::string out(out_len, '@');
  7516. sink.write(out.data(), out_len);
  7517. return offset < 4096;
  7518. },
  7519. [](bool success) { ASSERT_FALSE(success); });
  7520. });
  7521. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7522. res.set_content_provider(
  7523. 0, "text/plain",
  7524. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7525. EXPECT_TRUE(false);
  7526. return true;
  7527. },
  7528. [](bool success) { ASSERT_FALSE(success); });
  7529. });
  7530. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7531. auto se = detail::scope_exit([&] {
  7532. svr.stop();
  7533. listen_thread.join();
  7534. ASSERT_FALSE(svr.is_running());
  7535. });
  7536. svr.wait_until_ready();
  7537. Client cli("localhost", PORT);
  7538. {
  7539. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7540. size_t /*data_length*/) { return false; });
  7541. ASSERT_FALSE(res);
  7542. }
  7543. {
  7544. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7545. size_t /*data_length*/) { return false; });
  7546. ASSERT_TRUE(res);
  7547. }
  7548. }
  7549. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7550. Server svr;
  7551. svr.set_error_handler([](Request const &, Response &res) -> void {
  7552. res.set_chunked_content_provider(
  7553. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7554. sink.os << "hello";
  7555. sink.os << "world";
  7556. sink.done();
  7557. return true;
  7558. });
  7559. });
  7560. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7561. auto se = detail::scope_exit([&] {
  7562. svr.stop();
  7563. listen_thread.join();
  7564. ASSERT_FALSE(svr.is_running());
  7565. });
  7566. svr.wait_until_ready();
  7567. Client cli("localhost", PORT);
  7568. auto res = cli.Get("/");
  7569. ASSERT_TRUE(res);
  7570. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7571. EXPECT_EQ("helloworld", res->body);
  7572. }
  7573. TEST(LongPollingTest, ClientCloseDetection) {
  7574. Server svr;
  7575. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7576. res.set_chunked_content_provider(
  7577. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7578. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7579. sink.os << "hello";
  7580. auto count = 10;
  7581. while (count > 0 && sink.is_writable()) {
  7582. this_thread::sleep_for(chrono::milliseconds(10));
  7583. count--;
  7584. }
  7585. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7586. return true;
  7587. });
  7588. });
  7589. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7590. auto se = detail::scope_exit([&] {
  7591. svr.stop();
  7592. listen_thread.join();
  7593. ASSERT_FALSE(svr.is_running());
  7594. });
  7595. svr.wait_until_ready();
  7596. Client cli("localhost", PORT);
  7597. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7598. EXPECT_EQ("hello", string(data, data_length));
  7599. return false; // close the socket immediately.
  7600. });
  7601. ASSERT_FALSE(res);
  7602. }
  7603. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7604. Server svr;
  7605. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7606. res.set_chunked_content_provider(
  7607. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7608. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7609. sink.os << "hello";
  7610. EXPECT_TRUE(sink.os.good());
  7611. // Wait for the client to close the connection
  7612. auto count = 10;
  7613. while (count > 0 && sink.is_writable()) {
  7614. this_thread::sleep_for(chrono::milliseconds(10));
  7615. count--;
  7616. }
  7617. // After client disconnect, write repeatedly until the socket
  7618. // write actually fails (small writes may be absorbed by the
  7619. // kernel buffer)
  7620. std::string chunk(1024, 'x');
  7621. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7622. sink.os << chunk;
  7623. }
  7624. EXPECT_TRUE(sink.os.fail());
  7625. return true;
  7626. });
  7627. });
  7628. auto port = svr.bind_to_any_port("localhost");
  7629. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7630. auto se = detail::scope_exit([&] {
  7631. svr.stop();
  7632. listen_thread.join();
  7633. ASSERT_FALSE(svr.is_running());
  7634. });
  7635. svr.wait_until_ready();
  7636. Client cli("localhost", port);
  7637. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7638. EXPECT_EQ("hello", string(data, data_length));
  7639. return false; // close the socket immediately.
  7640. });
  7641. ASSERT_FALSE(res);
  7642. }
  7643. TEST(GetWithParametersTest, GetWithParameters) {
  7644. Server svr;
  7645. svr.Get("/", [&](const Request &req, Response &) {
  7646. EXPECT_EQ("world", req.get_param_value("hello"));
  7647. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7648. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7649. });
  7650. svr.Get("/params", [&](const Request &req, Response &) {
  7651. EXPECT_EQ("world", req.get_param_value("hello"));
  7652. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7653. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7654. });
  7655. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7656. EXPECT_EQ("resource-id", req.matches[1]);
  7657. EXPECT_EQ("foo", req.get_param_value("param1"));
  7658. EXPECT_EQ("bar", req.get_param_value("param2"));
  7659. });
  7660. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7661. EXPECT_EQ("user-id", req.path_params.at("id"));
  7662. EXPECT_EQ("foo", req.get_param_value("param1"));
  7663. EXPECT_EQ("bar", req.get_param_value("param2"));
  7664. });
  7665. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, 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. {
  7673. Client cli(HOST, PORT);
  7674. Params params;
  7675. params.emplace("hello", "world");
  7676. params.emplace("hello2", "world2");
  7677. params.emplace("hello3", "world3");
  7678. auto res = cli.Get("/", params, Headers{});
  7679. ASSERT_TRUE(res);
  7680. EXPECT_EQ(StatusCode::OK_200, res->status);
  7681. }
  7682. {
  7683. Client cli(HOST, PORT);
  7684. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7685. ASSERT_TRUE(res);
  7686. EXPECT_EQ(StatusCode::OK_200, res->status);
  7687. }
  7688. {
  7689. Client cli(HOST, PORT);
  7690. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7691. ASSERT_TRUE(res);
  7692. EXPECT_EQ(StatusCode::OK_200, res->status);
  7693. }
  7694. {
  7695. Client cli(HOST, PORT);
  7696. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7697. ASSERT_TRUE(res);
  7698. EXPECT_EQ(StatusCode::OK_200, res->status);
  7699. }
  7700. }
  7701. TEST(GetWithParametersTest, GetWithParameters2) {
  7702. Server svr;
  7703. svr.Get("/", [&](const Request &req, Response &res) {
  7704. auto text = req.get_param_value("hello");
  7705. res.set_content(text, "text/plain");
  7706. });
  7707. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7708. auto se = detail::scope_exit([&] {
  7709. svr.stop();
  7710. listen_thread.join();
  7711. ASSERT_FALSE(svr.is_running());
  7712. });
  7713. svr.wait_until_ready();
  7714. Client cli("localhost", PORT);
  7715. Params params;
  7716. params.emplace("hello", "world");
  7717. std::string body;
  7718. auto res = cli.Get("/", params, Headers{},
  7719. [&](const char *data, size_t data_length) {
  7720. body.append(data, data_length);
  7721. return true;
  7722. });
  7723. ASSERT_TRUE(res);
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_EQ("world", body);
  7726. }
  7727. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7728. Server svr;
  7729. svr.Get("/search", [&](const Request &req, Response &res) {
  7730. auto q = req.get_param_value("q");
  7731. res.set_content(q, "text/plain");
  7732. });
  7733. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7734. auto se = detail::scope_exit([&] {
  7735. svr.stop();
  7736. listen_thread.join();
  7737. ASSERT_FALSE(svr.is_running());
  7738. });
  7739. svr.wait_until_ready();
  7740. Client cli("localhost", PORT);
  7741. // Verify that Get(path, params) works without requiring Headers argument
  7742. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7743. ASSERT_TRUE(res);
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. EXPECT_EQ("cpp-httplib", res->body);
  7746. }
  7747. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7748. auto host = "httpbingo.org";
  7749. auto path = std::string{"/range/32"};
  7750. #ifdef CPPHTTPLIB_SSL_ENABLED
  7751. SSLClient cli(host);
  7752. #else
  7753. Client cli(host);
  7754. #endif
  7755. cli.set_default_headers({make_range_header({{1, 10}})});
  7756. cli.set_connection_timeout(5);
  7757. {
  7758. auto res = cli.Get(path);
  7759. ASSERT_TRUE(res);
  7760. EXPECT_EQ("bcdefghijk", res->body);
  7761. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7762. }
  7763. {
  7764. auto res = cli.Get(path);
  7765. ASSERT_TRUE(res);
  7766. EXPECT_EQ("bcdefghijk", res->body);
  7767. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7768. }
  7769. }
  7770. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7771. Server svr;
  7772. svr.set_default_headers({{"Hello", "World"}});
  7773. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7774. res.set_content("ok", "text/plain");
  7775. });
  7776. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7777. auto se = detail::scope_exit([&] {
  7778. svr.stop();
  7779. listen_thread.join();
  7780. ASSERT_FALSE(svr.is_running());
  7781. });
  7782. svr.wait_until_ready();
  7783. Client cli("localhost", PORT);
  7784. auto res = cli.Get("/");
  7785. ASSERT_TRUE(res);
  7786. EXPECT_EQ(StatusCode::OK_200, res->status);
  7787. EXPECT_EQ("ok", res->body);
  7788. EXPECT_EQ("World", res->get_header_value("Hello"));
  7789. }
  7790. #ifdef CPPHTTPLIB_SSL_ENABLED
  7791. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7793. ASSERT_TRUE(svr.is_valid());
  7794. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7795. std::this_thread::sleep_for(std::chrono::seconds(2));
  7796. res.set_content("a", "text/plain");
  7797. });
  7798. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7799. res.set_content("b", "text/plain");
  7800. });
  7801. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7802. auto se = detail::scope_exit([&] {
  7803. svr.stop();
  7804. listen_thread.join();
  7805. ASSERT_FALSE(svr.is_running());
  7806. });
  7807. svr.wait_until_ready();
  7808. SSLClient cli("localhost", PORT);
  7809. cli.enable_server_certificate_verification(false);
  7810. cli.set_keep_alive(true);
  7811. cli.set_read_timeout(std::chrono::seconds(1));
  7812. auto resa = cli.Get("/a");
  7813. ASSERT_TRUE(!resa);
  7814. EXPECT_EQ(Error::Read, resa.error());
  7815. auto resb = cli.Get("/b");
  7816. ASSERT_TRUE(resb);
  7817. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7818. EXPECT_EQ("b", resb->body);
  7819. }
  7820. #endif
  7821. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7822. protected:
  7823. ServerTestWithAI_PASSIVE()
  7824. : cli_(HOST, PORT)
  7825. #ifdef CPPHTTPLIB_SSL_ENABLED
  7826. ,
  7827. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7828. #endif
  7829. {
  7830. #ifdef CPPHTTPLIB_SSL_ENABLED
  7831. cli_.enable_server_certificate_verification(false);
  7832. #endif
  7833. }
  7834. virtual void SetUp() {
  7835. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7836. res.set_content("Hello World!", "text/plain");
  7837. });
  7838. t_ = thread(
  7839. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7840. svr_.wait_until_ready();
  7841. }
  7842. virtual void TearDown() {
  7843. svr_.stop();
  7844. t_.join();
  7845. }
  7846. #ifdef CPPHTTPLIB_SSL_ENABLED
  7847. SSLClient cli_;
  7848. SSLServer svr_;
  7849. #else
  7850. Client cli_;
  7851. Server svr_;
  7852. #endif
  7853. thread t_;
  7854. };
  7855. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7856. auto res = cli_.Get("/hi");
  7857. ASSERT_TRUE(res);
  7858. EXPECT_EQ(StatusCode::OK_200, res->status);
  7859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7860. EXPECT_EQ("Hello World!", res->body);
  7861. }
  7862. class ServerUpDownTest : public ::testing::Test {
  7863. protected:
  7864. ServerUpDownTest() : cli_(HOST, PORT) {}
  7865. virtual void SetUp() {
  7866. t_ = thread([&]() {
  7867. svr_.bind_to_any_port(HOST);
  7868. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7869. ASSERT_TRUE(svr_.listen_after_bind());
  7870. });
  7871. svr_.wait_until_ready();
  7872. }
  7873. virtual void TearDown() {
  7874. svr_.stop();
  7875. t_.join();
  7876. }
  7877. Client cli_;
  7878. Server svr_;
  7879. thread t_;
  7880. };
  7881. TEST_F(ServerUpDownTest, QuickStartStop) {
  7882. // Should not crash, especially when run with
  7883. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7884. }
  7885. class PayloadMaxLengthTest : public ::testing::Test {
  7886. protected:
  7887. PayloadMaxLengthTest()
  7888. : cli_(HOST, PORT)
  7889. #ifdef CPPHTTPLIB_SSL_ENABLED
  7890. ,
  7891. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7892. #endif
  7893. {
  7894. #ifdef CPPHTTPLIB_SSL_ENABLED
  7895. cli_.enable_server_certificate_verification(false);
  7896. #endif
  7897. }
  7898. virtual void SetUp() {
  7899. svr_.set_payload_max_length(8);
  7900. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7901. res.set_content("test", "text/plain");
  7902. });
  7903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7904. svr_.wait_until_ready();
  7905. }
  7906. virtual void TearDown() {
  7907. svr_.stop();
  7908. t_.join();
  7909. }
  7910. #ifdef CPPHTTPLIB_SSL_ENABLED
  7911. SSLClient cli_;
  7912. SSLServer svr_;
  7913. #else
  7914. Client cli_;
  7915. Server svr_;
  7916. #endif
  7917. thread t_;
  7918. };
  7919. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7920. auto res = cli_.Post("/test", "123456789", "text/plain");
  7921. ASSERT_TRUE(res);
  7922. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7923. res = cli_.Post("/test", "12345678", "text/plain");
  7924. ASSERT_TRUE(res);
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. }
  7927. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7928. // Test chunked encoding with payload exceeding the 8-byte limit
  7929. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7930. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7931. ASSERT_TRUE(res);
  7932. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7933. }
  7934. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7935. // Test chunked encoding with payload within the 8-byte limit
  7936. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7937. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7938. ASSERT_TRUE(res);
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. }
  7941. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7942. // Test using send_request to send chunked data exceeding payload limit
  7943. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7944. "Host: " +
  7945. std::string(HOST) + ":" + std::to_string(PORT) +
  7946. "\r\n"
  7947. "Transfer-Encoding: chunked\r\n"
  7948. "Connection: close\r\n"
  7949. "\r\n"
  7950. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7951. "0123456789\r\n"
  7952. "0\r\n" // End chunk
  7953. "\r\n";
  7954. std::string response;
  7955. bool result = send_request(1, chunked_request, &response);
  7956. if (!result) {
  7957. // If send_request fails, it might be because the server closed the
  7958. // connection due to payload limit enforcement, which is acceptable
  7959. SUCCEED()
  7960. << "Server rejected oversized chunked request (connection closed)";
  7961. } else {
  7962. // If we got a response, check if it's an error response or connection was
  7963. // closed early Short response length indicates connection was closed due to
  7964. // payload limit
  7965. if (response.length() <= 10) {
  7966. SUCCEED() << "Server closed connection for oversized chunked request";
  7967. } else {
  7968. // Check for error status codes
  7969. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7970. response.find("Payload Too Large") != std::string::npos ||
  7971. response.find("400") != std::string::npos);
  7972. }
  7973. }
  7974. }
  7975. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7976. // Test request without Content-Length header exceeding payload limit
  7977. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7978. "Host: " +
  7979. std::string(HOST) + ":" +
  7980. std::to_string(PORT) +
  7981. "\r\n"
  7982. "Connection: close\r\n"
  7983. "\r\n";
  7984. // Add payload exceeding the 8-byte limit
  7985. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7986. request_without_content_length += large_payload;
  7987. std::string response;
  7988. bool result = send_request(1, request_without_content_length, &response);
  7989. if (!result) {
  7990. // If send_request fails, server likely closed connection due to payload
  7991. // limit
  7992. SUCCEED() << "Server rejected oversized request without Content-Length "
  7993. "(connection closed)";
  7994. } else {
  7995. // Check if server responded with error or closed connection early
  7996. if (response.length() <= 10) {
  7997. SUCCEED() << "Server closed connection for oversized request without "
  7998. "Content-Length";
  7999. } else {
  8000. // Check for error status codes
  8001. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8002. response.find("Payload Too Large") != std::string::npos ||
  8003. response.find("400") != std::string::npos);
  8004. }
  8005. }
  8006. }
  8007. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8008. // Test request without Content-Length header within payload limit
  8009. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8010. "Host: " +
  8011. std::string(HOST) + ":" +
  8012. std::to_string(PORT) +
  8013. "\r\n"
  8014. "Connection: close\r\n"
  8015. "\r\n";
  8016. // Add payload within the 8-byte limit
  8017. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8018. request_without_content_length += small_payload;
  8019. std::string response;
  8020. bool result = send_request(1, request_without_content_length, &response);
  8021. // For requests without Content-Length, the server may have different behavior
  8022. // The key is that it should not reject due to payload limit for small
  8023. // payloads
  8024. if (result) {
  8025. // Check for any HTTP response (success or error, but not connection closed)
  8026. if (response.length() > 10) {
  8027. SUCCEED()
  8028. << "Server processed request without Content-Length within limit";
  8029. } else {
  8030. // Short response might indicate connection closed, which is acceptable
  8031. SUCCEED() << "Server closed connection for request without "
  8032. "Content-Length (acceptable behavior)";
  8033. }
  8034. } else {
  8035. // Connection failure might be due to protocol requirements
  8036. SUCCEED() << "Connection issue with request without Content-Length "
  8037. "(environment-specific)";
  8038. }
  8039. }
  8040. class LargePayloadMaxLengthTest : public ::testing::Test {
  8041. protected:
  8042. LargePayloadMaxLengthTest()
  8043. : cli_(HOST, PORT)
  8044. #ifdef CPPHTTPLIB_SSL_ENABLED
  8045. ,
  8046. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8047. #endif
  8048. {
  8049. #ifdef CPPHTTPLIB_SSL_ENABLED
  8050. cli_.enable_server_certificate_verification(false);
  8051. #endif
  8052. }
  8053. virtual void SetUp() {
  8054. // Set 10MB payload limit
  8055. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8056. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8057. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8058. res.set_content("Large payload test", "text/plain");
  8059. });
  8060. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8061. svr_.wait_until_ready();
  8062. }
  8063. virtual void TearDown() {
  8064. svr_.stop();
  8065. t_.join();
  8066. }
  8067. #ifdef CPPHTTPLIB_SSL_ENABLED
  8068. SSLClient cli_;
  8069. SSLServer svr_;
  8070. #else
  8071. Client cli_;
  8072. Server svr_;
  8073. #endif
  8074. thread t_;
  8075. };
  8076. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8077. // Test chunked encoding with payload within 10MB limit
  8078. std::string medium_payload(5 * 1024 * 1024,
  8079. 'A'); // 5MB payload, within 10MB limit
  8080. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8081. ASSERT_TRUE(res);
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8085. // Test chunked encoding with payload exceeding 10MB limit
  8086. std::string large_payload(12 * 1024 * 1024,
  8087. 'B'); // 12MB payload, exceeds 10MB limit
  8088. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8089. // Server may either return 413 or close the connection
  8090. if (res) {
  8091. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8092. } else {
  8093. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8094. }
  8095. }
  8096. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8097. // Test request without Content-Length header within 10MB limit
  8098. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8099. "Host: " +
  8100. std::string(HOST) + ":" +
  8101. std::to_string(PORT) +
  8102. "\r\n"
  8103. "Connection: close\r\n"
  8104. "\r\n";
  8105. // Add 1MB payload (within 10MB limit)
  8106. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8107. request_without_content_length += medium_payload;
  8108. std::string response;
  8109. bool result = send_request(5, request_without_content_length, &response);
  8110. if (result) {
  8111. // Should get a proper HTTP response for payloads within limit
  8112. if (response.length() > 10) {
  8113. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8114. "10MB limit";
  8115. } else {
  8116. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8117. "Content-Length)";
  8118. }
  8119. } else {
  8120. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8121. }
  8122. }
  8123. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8124. // Test request without Content-Length header exceeding 10MB limit
  8125. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8126. "Host: " +
  8127. std::string(HOST) + ":" +
  8128. std::to_string(PORT) +
  8129. "\r\n"
  8130. "Connection: close\r\n"
  8131. "\r\n";
  8132. // Add 12MB payload (exceeds 10MB limit)
  8133. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8134. request_without_content_length += large_payload;
  8135. std::string response;
  8136. bool result = send_request(10, request_without_content_length, &response);
  8137. if (!result) {
  8138. // Server should close connection due to payload limit
  8139. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8140. "(connection closed)";
  8141. } else {
  8142. // Check for error response
  8143. if (response.length() <= 10) {
  8144. SUCCEED()
  8145. << "Server closed connection for 12MB request exceeding 10MB limit";
  8146. } else {
  8147. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8148. response.find("Payload Too Large") != std::string::npos ||
  8149. response.find("400") != std::string::npos);
  8150. }
  8151. }
  8152. }
  8153. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8154. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8155. // path.
  8156. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8157. Server svr;
  8158. const size_t LIMIT = 64 * 1024; // 64KB
  8159. svr.set_payload_max_length(LIMIT);
  8160. size_t total = 0;
  8161. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8162. const ContentReader &content_reader) {
  8163. content_reader([&](const char * /*data*/, size_t len) {
  8164. total += len;
  8165. return true;
  8166. });
  8167. res.status = 200;
  8168. res.set_content("stream_ok", "text/plain");
  8169. });
  8170. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8171. auto se = detail::scope_exit([&] {
  8172. svr.stop();
  8173. thread.join();
  8174. ASSERT_FALSE(svr.is_running());
  8175. });
  8176. svr.wait_until_ready();
  8177. // Prepare 256KB raw data and gzip-compress it
  8178. std::string raw(256 * 1024, 'A');
  8179. std::string gz;
  8180. {
  8181. z_stream zs{};
  8182. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8183. Z_DEFAULT_STRATEGY);
  8184. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8185. zs.avail_in = static_cast<uInt>(raw.size());
  8186. char outbuf[4096];
  8187. int ret;
  8188. do {
  8189. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8190. zs.avail_out = sizeof(outbuf);
  8191. ret = deflate(&zs, Z_FINISH);
  8192. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8193. } while (ret != Z_STREAM_END);
  8194. deflateEnd(&zs);
  8195. }
  8196. Client cli(HOST, PORT);
  8197. cli.set_connection_timeout(std::chrono::seconds(5));
  8198. Headers headers = {{"Content-Encoding", "gzip"}};
  8199. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8200. "application/octet-stream");
  8201. ASSERT_TRUE(res);
  8202. // Server must reject oversized decompressed payloads with 413.
  8203. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8204. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8205. EXPECT_LE(total, LIMIT);
  8206. }
  8207. #endif
  8208. // Regression test for DoS vulnerability: a malicious server sending a response
  8209. // without Content-Length header must not cause unbounded memory consumption on
  8210. // the client side. The client should stop reading after a reasonable limit,
  8211. // similar to the server-side set_payload_max_length protection.
  8212. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8213. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8214. #ifndef _WIN32
  8215. signal(SIGPIPE, SIG_IGN);
  8216. #endif
  8217. auto server_thread = std::thread([] {
  8218. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8219. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8220. default_socket_options(srv);
  8221. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8222. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8223. sockaddr_in addr{};
  8224. addr.sin_family = AF_INET;
  8225. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8226. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8227. int opt = 1;
  8228. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8229. #ifdef _WIN32
  8230. reinterpret_cast<const char *>(&opt),
  8231. #else
  8232. &opt,
  8233. #endif
  8234. sizeof(opt));
  8235. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8236. ::listen(srv, 1);
  8237. sockaddr_in cli_addr{};
  8238. socklen_t cli_len = sizeof(cli_addr);
  8239. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8240. if (cli != INVALID_SOCKET) {
  8241. char buf[4096];
  8242. ::recv(cli, buf, sizeof(buf), 0);
  8243. // Malicious response: no Content-Length, no chunked encoding
  8244. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8245. "Connection: close\r\n"
  8246. "\r\n";
  8247. ::send(cli,
  8248. #ifdef _WIN32
  8249. static_cast<const char *>(response_header.c_str()),
  8250. static_cast<int>(response_header.size()),
  8251. #else
  8252. response_header.c_str(), response_header.size(),
  8253. #endif
  8254. 0);
  8255. // Send 10MB of data
  8256. std::string chunk(64 * 1024, 'A');
  8257. size_t total_sent = 0;
  8258. while (total_sent < MALICIOUS_DATA_SIZE) {
  8259. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8260. auto sent = ::send(cli,
  8261. #ifdef _WIN32
  8262. static_cast<const char *>(chunk.c_str()),
  8263. static_cast<int>(to_send),
  8264. #else
  8265. chunk.c_str(), to_send,
  8266. #endif
  8267. 0);
  8268. if (sent <= 0) break;
  8269. total_sent += static_cast<size_t>(sent);
  8270. }
  8271. detail::close_socket(cli);
  8272. }
  8273. detail::close_socket(srv);
  8274. });
  8275. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8276. size_t total_read = 0;
  8277. {
  8278. Client cli("127.0.0.1", PORT + 2);
  8279. cli.set_read_timeout(5, 0);
  8280. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8281. auto stream = cli.open_stream("GET", "/malicious");
  8282. ASSERT_TRUE(stream.is_valid());
  8283. char buffer[64 * 1024];
  8284. ssize_t n;
  8285. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8286. total_read += static_cast<size_t>(n);
  8287. }
  8288. } // StreamHandle and Client destroyed here, closing the socket
  8289. server_thread.join();
  8290. // With set_payload_max_length, the client must stop reading before consuming
  8291. // all 10MB. The read loop should be cut off at or near the configured limit.
  8292. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8293. << "Client read " << total_read << " bytes, exceeding the configured "
  8294. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8295. }
  8296. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8297. // the entire response body without truncation.
  8298. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8299. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8300. #ifndef _WIN32
  8301. signal(SIGPIPE, SIG_IGN);
  8302. #endif
  8303. auto server_thread = std::thread([] {
  8304. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8305. default_socket_options(srv);
  8306. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8307. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8308. sockaddr_in addr{};
  8309. addr.sin_family = AF_INET;
  8310. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8311. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8312. int opt = 1;
  8313. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8314. #ifdef _WIN32
  8315. reinterpret_cast<const char *>(&opt),
  8316. #else
  8317. &opt,
  8318. #endif
  8319. sizeof(opt));
  8320. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8321. ::listen(srv, 1);
  8322. sockaddr_in cli_addr{};
  8323. socklen_t cli_len = sizeof(cli_addr);
  8324. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8325. if (cli != INVALID_SOCKET) {
  8326. char buf[4096];
  8327. ::recv(cli, buf, sizeof(buf), 0);
  8328. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8329. "Connection: close\r\n"
  8330. "\r\n";
  8331. ::send(cli,
  8332. #ifdef _WIN32
  8333. static_cast<const char *>(response_header.c_str()),
  8334. static_cast<int>(response_header.size()),
  8335. #else
  8336. response_header.c_str(), response_header.size(),
  8337. #endif
  8338. 0);
  8339. std::string chunk(64 * 1024, 'A');
  8340. size_t total_sent = 0;
  8341. while (total_sent < DATA_SIZE) {
  8342. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8343. auto sent = ::send(cli,
  8344. #ifdef _WIN32
  8345. static_cast<const char *>(chunk.c_str()),
  8346. static_cast<int>(to_send),
  8347. #else
  8348. chunk.c_str(), to_send,
  8349. #endif
  8350. 0);
  8351. if (sent <= 0) break;
  8352. total_sent += static_cast<size_t>(sent);
  8353. }
  8354. #ifdef _WIN32
  8355. ::shutdown(cli, SD_SEND);
  8356. #else
  8357. ::shutdown(cli, SHUT_WR);
  8358. #endif
  8359. // Drain until the client closes its end, ensuring all data is delivered
  8360. char drain[1024];
  8361. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8362. detail::close_socket(cli);
  8363. }
  8364. detail::close_socket(srv);
  8365. });
  8366. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8367. size_t total_read = 0;
  8368. {
  8369. Client cli("127.0.0.1", PORT + 2);
  8370. cli.set_read_timeout(5, 0);
  8371. cli.set_payload_max_length(0); // 0 means no limit
  8372. auto stream = cli.open_stream("GET", "/data");
  8373. ASSERT_TRUE(stream.is_valid());
  8374. char buffer[64 * 1024];
  8375. ssize_t n;
  8376. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8377. total_read += static_cast<size_t>(n);
  8378. }
  8379. }
  8380. server_thread.join();
  8381. EXPECT_EQ(total_read, DATA_SIZE)
  8382. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8383. << " bytes without truncation, but only read " << total_read << " bytes.";
  8384. }
  8385. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8386. // enormous Content-Length must not cause the client to pre-allocate a huge
  8387. // response body buffer. The reservation is capped at payload_max_length_, and
  8388. // the read itself fails when the body exceeds the limit.
  8389. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8390. #ifndef _WIN32
  8391. signal(SIGPIPE, SIG_IGN);
  8392. #endif
  8393. auto server_thread = std::thread([] {
  8394. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8395. default_socket_options(srv);
  8396. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8397. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8398. sockaddr_in addr{};
  8399. addr.sin_family = AF_INET;
  8400. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8401. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8402. int opt = 1;
  8403. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8404. #ifdef _WIN32
  8405. reinterpret_cast<const char *>(&opt),
  8406. #else
  8407. &opt,
  8408. #endif
  8409. sizeof(opt));
  8410. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8411. ::listen(srv, 1);
  8412. sockaddr_in cli_addr{};
  8413. socklen_t cli_len = sizeof(cli_addr);
  8414. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8415. if (cli != INVALID_SOCKET) {
  8416. char buf[4096];
  8417. ::recv(cli, buf, sizeof(buf), 0);
  8418. // Malicious response: claim a 20GB body but send only a tiny payload.
  8419. std::string response = "HTTP/1.1 200 OK\r\n"
  8420. "Content-Length: 20000000000\r\n"
  8421. "\r\n"
  8422. "abc";
  8423. ::send(cli,
  8424. #ifdef _WIN32
  8425. static_cast<const char *>(response.c_str()),
  8426. static_cast<int>(response.size()),
  8427. #else
  8428. response.c_str(), response.size(),
  8429. #endif
  8430. 0);
  8431. detail::close_socket(cli);
  8432. }
  8433. detail::close_socket(srv);
  8434. });
  8435. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8436. {
  8437. Client cli("127.0.0.1", PORT + 2);
  8438. cli.set_read_timeout(5, 0);
  8439. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8440. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8441. // (server claims more bytes than payload_max_length permits), but it must
  8442. // not exhaust memory before getting there.
  8443. auto res = cli.Get("/malicious");
  8444. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8445. }
  8446. server_thread.join();
  8447. }
  8448. // Verify that content_receiver bypasses the default payload_max_length,
  8449. // allowing streaming downloads larger than 100MB without requiring an explicit
  8450. // set_payload_max_length call.
  8451. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8452. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8453. #ifndef _WIN32
  8454. signal(SIGPIPE, SIG_IGN);
  8455. #endif
  8456. auto server_thread = std::thread([] {
  8457. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8458. default_socket_options(srv);
  8459. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8460. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8461. sockaddr_in addr{};
  8462. addr.sin_family = AF_INET;
  8463. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8464. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8465. int opt = 1;
  8466. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8467. #ifdef _WIN32
  8468. reinterpret_cast<const char *>(&opt),
  8469. #else
  8470. &opt,
  8471. #endif
  8472. sizeof(opt));
  8473. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8474. ::listen(srv, 1);
  8475. sockaddr_in cli_addr{};
  8476. socklen_t cli_len = sizeof(cli_addr);
  8477. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8478. if (cli != INVALID_SOCKET) {
  8479. char buf[4096];
  8480. ::recv(cli, buf, sizeof(buf), 0);
  8481. // Response with Content-Length larger than default 100MB limit
  8482. auto content_length = std::to_string(DATA_SIZE);
  8483. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8484. "Content-Length: " +
  8485. content_length +
  8486. "\r\n"
  8487. "Connection: close\r\n"
  8488. "\r\n";
  8489. ::send(cli,
  8490. #ifdef _WIN32
  8491. static_cast<const char *>(response_header.c_str()),
  8492. static_cast<int>(response_header.size()),
  8493. #else
  8494. response_header.c_str(), response_header.size(),
  8495. #endif
  8496. 0);
  8497. std::string chunk(64 * 1024, 'A');
  8498. size_t total_sent = 0;
  8499. while (total_sent < DATA_SIZE) {
  8500. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8501. auto sent = ::send(cli,
  8502. #ifdef _WIN32
  8503. static_cast<const char *>(chunk.c_str()),
  8504. static_cast<int>(to_send),
  8505. #else
  8506. chunk.c_str(), to_send,
  8507. #endif
  8508. 0);
  8509. if (sent <= 0) break;
  8510. total_sent += static_cast<size_t>(sent);
  8511. }
  8512. detail::close_socket(cli);
  8513. }
  8514. detail::close_socket(srv);
  8515. });
  8516. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8517. size_t total_received = 0;
  8518. {
  8519. Client cli("127.0.0.1", PORT + 2);
  8520. cli.set_read_timeout(10, 0);
  8521. // Do NOT call set_payload_max_length — use the default 100MB limit
  8522. auto res =
  8523. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8524. total_received += data_length;
  8525. return true;
  8526. });
  8527. ASSERT_TRUE(res);
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. }
  8530. server_thread.join();
  8531. EXPECT_EQ(total_received, DATA_SIZE)
  8532. << "With content_receiver, the client should read all " << DATA_SIZE
  8533. << " bytes despite the default 100MB payload_max_length, but only read "
  8534. << total_received << " bytes.";
  8535. }
  8536. // Verify that an explicit set_payload_max_length smaller than the response is
  8537. // enforced even when a content_receiver is used.
  8538. TEST(ClientVulnerabilityTest,
  8539. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8540. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8541. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8542. #ifndef _WIN32
  8543. signal(SIGPIPE, SIG_IGN);
  8544. #endif
  8545. auto server_thread = std::thread([] {
  8546. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8547. default_socket_options(srv);
  8548. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8549. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8550. sockaddr_in addr{};
  8551. addr.sin_family = AF_INET;
  8552. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8553. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8554. int opt = 1;
  8555. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8556. #ifdef _WIN32
  8557. reinterpret_cast<const char *>(&opt),
  8558. #else
  8559. &opt,
  8560. #endif
  8561. sizeof(opt));
  8562. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8563. ::listen(srv, 1);
  8564. sockaddr_in cli_addr{};
  8565. socklen_t cli_len = sizeof(cli_addr);
  8566. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8567. if (cli != INVALID_SOCKET) {
  8568. char buf[4096];
  8569. ::recv(cli, buf, sizeof(buf), 0);
  8570. auto content_length = std::to_string(DATA_SIZE);
  8571. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8572. "Content-Length: " +
  8573. content_length +
  8574. "\r\n"
  8575. "Connection: close\r\n"
  8576. "\r\n";
  8577. ::send(cli,
  8578. #ifdef _WIN32
  8579. static_cast<const char *>(response_header.c_str()),
  8580. static_cast<int>(response_header.size()),
  8581. #else
  8582. response_header.c_str(), response_header.size(),
  8583. #endif
  8584. 0);
  8585. std::string chunk(64 * 1024, 'A');
  8586. size_t total_sent = 0;
  8587. while (total_sent < DATA_SIZE) {
  8588. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8589. auto sent = ::send(cli,
  8590. #ifdef _WIN32
  8591. static_cast<const char *>(chunk.c_str()),
  8592. static_cast<int>(to_send),
  8593. #else
  8594. chunk.c_str(), to_send,
  8595. #endif
  8596. 0);
  8597. if (sent <= 0) break;
  8598. total_sent += static_cast<size_t>(sent);
  8599. }
  8600. detail::close_socket(cli);
  8601. }
  8602. detail::close_socket(srv);
  8603. });
  8604. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8605. size_t total_received = 0;
  8606. {
  8607. Client cli("127.0.0.1", PORT + 2);
  8608. cli.set_read_timeout(10, 0);
  8609. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8610. auto res =
  8611. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8612. total_received += data_length;
  8613. return true;
  8614. });
  8615. // Should fail because 200MB exceeds the explicit 150MB limit
  8616. EXPECT_FALSE(res);
  8617. }
  8618. server_thread.join();
  8619. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8620. << "Client with content_receiver should respect the explicit "
  8621. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8622. << total_received << " bytes.";
  8623. }
  8624. // Verify that an explicit set_payload_max_length larger than the response
  8625. // allows the content_receiver to read all data successfully.
  8626. TEST(ClientVulnerabilityTest,
  8627. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8628. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8629. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8630. #ifndef _WIN32
  8631. signal(SIGPIPE, SIG_IGN);
  8632. #endif
  8633. auto server_thread = std::thread([] {
  8634. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8635. default_socket_options(srv);
  8636. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8637. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8638. sockaddr_in addr{};
  8639. addr.sin_family = AF_INET;
  8640. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8641. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8642. int opt = 1;
  8643. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8644. #ifdef _WIN32
  8645. reinterpret_cast<const char *>(&opt),
  8646. #else
  8647. &opt,
  8648. #endif
  8649. sizeof(opt));
  8650. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8651. ::listen(srv, 1);
  8652. sockaddr_in cli_addr{};
  8653. socklen_t cli_len = sizeof(cli_addr);
  8654. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8655. if (cli != INVALID_SOCKET) {
  8656. char buf[4096];
  8657. ::recv(cli, buf, sizeof(buf), 0);
  8658. auto content_length = std::to_string(DATA_SIZE);
  8659. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8660. "Content-Length: " +
  8661. content_length +
  8662. "\r\n"
  8663. "Connection: close\r\n"
  8664. "\r\n";
  8665. ::send(cli,
  8666. #ifdef _WIN32
  8667. static_cast<const char *>(response_header.c_str()),
  8668. static_cast<int>(response_header.size()),
  8669. #else
  8670. response_header.c_str(), response_header.size(),
  8671. #endif
  8672. 0);
  8673. std::string chunk(64 * 1024, 'A');
  8674. size_t total_sent = 0;
  8675. while (total_sent < DATA_SIZE) {
  8676. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8677. auto sent = ::send(cli,
  8678. #ifdef _WIN32
  8679. static_cast<const char *>(chunk.c_str()),
  8680. static_cast<int>(to_send),
  8681. #else
  8682. chunk.c_str(), to_send,
  8683. #endif
  8684. 0);
  8685. if (sent <= 0) break;
  8686. total_sent += static_cast<size_t>(sent);
  8687. }
  8688. #ifdef _WIN32
  8689. ::shutdown(cli, SD_SEND);
  8690. #else
  8691. ::shutdown(cli, SHUT_WR);
  8692. #endif
  8693. char drain[1024];
  8694. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8695. detail::close_socket(cli);
  8696. }
  8697. detail::close_socket(srv);
  8698. });
  8699. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8700. size_t total_received = 0;
  8701. {
  8702. Client cli("127.0.0.1", PORT + 2);
  8703. cli.set_read_timeout(10, 0);
  8704. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8705. auto res =
  8706. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8707. total_received += data_length;
  8708. return true;
  8709. });
  8710. ASSERT_TRUE(res);
  8711. EXPECT_EQ(StatusCode::OK_200, res->status);
  8712. }
  8713. server_thread.join();
  8714. EXPECT_EQ(total_received, DATA_SIZE)
  8715. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8716. << " bytes (larger than " << DATA_SIZE
  8717. << " bytes response), content_receiver should read all data, but only "
  8718. "read "
  8719. << total_received << " bytes.";
  8720. }
  8721. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8722. // Regression test for "zip bomb" attack on the client side: a malicious server
  8723. // sends a small gzip-compressed response that decompresses to a huge payload.
  8724. // The client must enforce payload_max_length on the decompressed size.
  8725. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8726. constexpr size_t DECOMPRESSED_SIZE =
  8727. 10 * 1024 * 1024; // 10MB after decompression
  8728. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8729. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8730. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8731. std::string compressed;
  8732. {
  8733. httplib::detail::gzip_compressor compressor;
  8734. bool ok =
  8735. compressor.compress(uncompressed.data(), uncompressed.size(),
  8736. /*last=*/true, [&](const char *buf, size_t len) {
  8737. compressed.append(buf, len);
  8738. return true;
  8739. });
  8740. ASSERT_TRUE(ok);
  8741. }
  8742. // Sanity: compressed data should be much smaller than the decompressed size
  8743. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8744. #ifndef _WIN32
  8745. signal(SIGPIPE, SIG_IGN);
  8746. #endif
  8747. // Set up the listening socket in the main thread so the server is guaranteed
  8748. // to be ready before the client connects (eliminates race condition).
  8749. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8750. default_socket_options(srv);
  8751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8752. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8753. sockaddr_in addr{};
  8754. addr.sin_family = AF_INET;
  8755. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8756. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8757. int opt = 1;
  8758. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8759. #ifdef _WIN32
  8760. reinterpret_cast<const char *>(&opt),
  8761. #else
  8762. &opt,
  8763. #endif
  8764. sizeof(opt));
  8765. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8766. ASSERT_EQ(0, ::listen(srv, 1));
  8767. auto server_thread = std::thread([&compressed, srv] {
  8768. sockaddr_in cli_addr{};
  8769. socklen_t cli_len = sizeof(cli_addr);
  8770. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8771. if (cli != INVALID_SOCKET) {
  8772. // Read the full HTTP request (until \r\n\r\n)
  8773. char buf[4096];
  8774. size_t total = 0;
  8775. while (total < sizeof(buf)) {
  8776. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8777. if (n <= 0) break;
  8778. total += static_cast<size_t>(n);
  8779. // Check for end of headers
  8780. if (total >= 4) {
  8781. std::string req(buf, total);
  8782. if (req.find("\r\n\r\n") != std::string::npos) break;
  8783. }
  8784. }
  8785. // Malicious response: gzip-compressed body, no Content-Length
  8786. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8787. "Content-Encoding: gzip\r\n"
  8788. "Connection: close\r\n"
  8789. "\r\n";
  8790. ::send(cli,
  8791. #ifdef _WIN32
  8792. static_cast<const char *>(response_header.c_str()),
  8793. static_cast<int>(response_header.size()),
  8794. #else
  8795. response_header.c_str(), response_header.size(),
  8796. #endif
  8797. 0);
  8798. // Send the compressed payload (small on the wire, huge when decompressed)
  8799. size_t total_sent = 0;
  8800. while (total_sent < compressed.size()) {
  8801. auto to_send = std::min(compressed.size() - total_sent,
  8802. static_cast<size_t>(64 * 1024));
  8803. auto sent =
  8804. ::send(cli,
  8805. #ifdef _WIN32
  8806. static_cast<const char *>(compressed.c_str() + total_sent),
  8807. static_cast<int>(to_send),
  8808. #else
  8809. compressed.c_str() + total_sent, to_send,
  8810. #endif
  8811. 0);
  8812. if (sent <= 0) break;
  8813. total_sent += static_cast<size_t>(sent);
  8814. }
  8815. detail::close_socket(cli);
  8816. }
  8817. });
  8818. auto se = detail::scope_exit([&] {
  8819. detail::close_socket(srv);
  8820. server_thread.join();
  8821. });
  8822. size_t total_decompressed = 0;
  8823. {
  8824. Client cli("127.0.0.1", PORT + 3);
  8825. cli.set_read_timeout(5, 0);
  8826. cli.set_decompress(true);
  8827. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8828. auto stream = cli.open_stream("GET", "/zipbomb");
  8829. ASSERT_TRUE(stream.is_valid());
  8830. char buffer[64 * 1024];
  8831. ssize_t n;
  8832. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8833. total_decompressed += static_cast<size_t>(n);
  8834. }
  8835. }
  8836. // The decompressed size must be capped by payload_max_length. Without
  8837. // protection, the client would decompress the full 10MB from a tiny
  8838. // compressed payload, enabling a zip bomb DoS attack.
  8839. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8840. << "Client decompressed " << total_decompressed
  8841. << " bytes from a gzip response. The decompressed size should be "
  8842. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8843. }
  8844. #endif
  8845. TEST(HostAndPortPropertiesTest, NoSSL) {
  8846. httplib::Client cli("www.google.com", 1234);
  8847. ASSERT_EQ("www.google.com", cli.host());
  8848. ASSERT_EQ(1234, cli.port());
  8849. }
  8850. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8851. httplib::Client cli("www.google.com:1234");
  8852. ASSERT_EQ("www.google.com", cli.host());
  8853. ASSERT_EQ(1234, cli.port());
  8854. }
  8855. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8856. // Port number that overflows int — should not crash, client becomes invalid
  8857. httplib::Client cli("http://www.google.com:99999999999999999999");
  8858. ASSERT_FALSE(cli.is_valid());
  8859. }
  8860. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8861. // Port 99999 exceeds valid range (1-65535) — should not crash
  8862. httplib::Client cli("http://www.google.com:99999");
  8863. ASSERT_FALSE(cli.is_valid());
  8864. }
  8865. #ifdef CPPHTTPLIB_SSL_ENABLED
  8866. TEST(HostAndPortPropertiesTest, SSL) {
  8867. httplib::SSLClient cli("www.google.com");
  8868. ASSERT_EQ("www.google.com", cli.host());
  8869. ASSERT_EQ(443, cli.port());
  8870. }
  8871. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8872. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8873. std::string cert;
  8874. read_file(CA_CERT_FILE, cert);
  8875. httplib::SSLClient httplib_client("www.google.com");
  8876. // Load CA store first time
  8877. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8878. // Load CA store second time (update)
  8879. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8880. // Verify client is still valid and can make connections
  8881. httplib_client.enable_server_certificate_verification(true);
  8882. auto res = httplib_client.Get("/");
  8883. ASSERT_TRUE(res);
  8884. // Google may return 200 or 301 depending on various factors
  8885. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8886. res->status == StatusCode::MovedPermanently_301);
  8887. }
  8888. TEST(SSLClientTest, ServerNameIndication_Online) {
  8889. auto host = "httpbingo.org";
  8890. auto path = std::string{"/get"};
  8891. SSLClient cli(host, 443);
  8892. auto res = cli.Get(path);
  8893. ASSERT_TRUE(res);
  8894. ASSERT_EQ(StatusCode::OK_200, res->status);
  8895. }
  8896. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8897. // Use a site that will cause SSL verification failure due to self-signed cert
  8898. SSLClient cli("self-signed.badssl.com", 443);
  8899. cli.enable_server_certificate_verification(true);
  8900. auto res = cli.Get("/");
  8901. ASSERT_TRUE(!res);
  8902. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8903. // Verify backend error is captured for SSLServerVerification
  8904. // This occurs when certificate verification fails
  8905. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8906. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8907. EXPECT_NE(0UL, res.ssl_backend_error());
  8908. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8909. // For OpenSSL, ssl_error is 0 for verification errors
  8910. EXPECT_EQ(0, res.ssl_error());
  8911. #if !defined(_WIN32) || \
  8912. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8913. // On non-Windows or when Windows Schannel is disabled, the error comes
  8914. // from OpenSSL's verification
  8915. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8916. res.ssl_backend_error());
  8917. #endif
  8918. #endif
  8919. }
  8920. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8921. // Use a site where hostname doesn't match the certificate
  8922. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8923. SSLClient cli("wrong.host.badssl.com", 443);
  8924. cli.enable_server_certificate_verification(true);
  8925. cli.enable_server_hostname_verification(true);
  8926. auto res = cli.Get("/");
  8927. ASSERT_TRUE(!res);
  8928. // The error type depends on when hostname verification occurs:
  8929. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8930. // - Mbed TLS: SSLServerVerification (during handshake)
  8931. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8932. res.error() == Error::SSLServerVerification);
  8933. // Verify backend error is captured for hostname verification failure
  8934. EXPECT_NE(0UL, res.ssl_backend_error());
  8935. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8936. // For OpenSSL, ssl_error is 0 for verification errors
  8937. EXPECT_EQ(0, res.ssl_error());
  8938. #if !defined(_WIN32) || \
  8939. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8940. // On non-Windows or when Windows Schannel is disabled, the error comes
  8941. // from OpenSSL's hostname verification
  8942. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8943. res.ssl_backend_error());
  8944. #endif
  8945. #endif
  8946. }
  8947. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8948. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8949. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8950. SSLClient cli("www.google.com", 443);
  8951. cli.enable_server_certificate_verification(true);
  8952. auto res = cli.Get("/");
  8953. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8954. }
  8955. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8956. SSLClient cli("www.google.com", 443);
  8957. cli.enable_server_certificate_verification(true);
  8958. cli.enable_windows_certificate_verification(false);
  8959. auto res = cli.Get("/");
  8960. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8961. }
  8962. #endif
  8963. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8964. Client cli("https://google.com");
  8965. auto res = cli.Get("/");
  8966. ASSERT_TRUE(res);
  8967. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8968. }
  8969. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8970. SSLClient cli("google.com");
  8971. cli.set_ca_cert_path(CA_CERT_FILE);
  8972. auto res = cli.Get("/");
  8973. ASSERT_TRUE(res);
  8974. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8975. }
  8976. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8977. SSLClient cli("google.com");
  8978. cli.enable_server_certificate_verification(true);
  8979. cli.set_ca_cert_path("hello");
  8980. auto res = cli.Get("/");
  8981. ASSERT_TRUE(!res);
  8982. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8983. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8984. // should be set
  8985. EXPECT_EQ(0, res.ssl_error());
  8986. // Verify backend error is captured for SSLLoadingCerts
  8987. // This error occurs when loading CA certificates fails
  8988. EXPECT_NE(0UL, res.ssl_backend_error());
  8989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8990. // OpenSSL specific error codes:
  8991. // > openssl errstr 0x80000002
  8992. // error:80000002:system library::No such file or directory
  8993. // > openssl errstr 0xA000126
  8994. // error:0A000126:SSL routines::unexpected eof while reading
  8995. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8996. res.ssl_backend_error() == 0xA000126);
  8997. #endif
  8998. }
  8999. TEST(SSLClientTest, ServerCertificateVerification4) {
  9000. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9001. ASSERT_TRUE(svr.is_valid());
  9002. svr.Get("/test", [&](const Request &, Response &res) {
  9003. res.set_content("test", "text/plain");
  9004. svr.stop();
  9005. ASSERT_TRUE(true);
  9006. });
  9007. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9008. auto se = detail::scope_exit([&] {
  9009. t.join();
  9010. ASSERT_FALSE(svr.is_running());
  9011. });
  9012. svr.wait_until_ready();
  9013. SSLClient cli("127.0.0.1", PORT);
  9014. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9015. cli.enable_server_certificate_verification(true);
  9016. cli.set_connection_timeout(30);
  9017. auto res = cli.Get("/test");
  9018. ASSERT_TRUE(res);
  9019. ASSERT_EQ(StatusCode::OK_200, res->status);
  9020. }
  9021. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9022. std::string cert;
  9023. read_file(CA_CERT_FILE, cert);
  9024. SSLClient cli("google.com");
  9025. cli.load_ca_cert_store(cert.data(), cert.size());
  9026. const auto res = cli.Get("/");
  9027. ASSERT_TRUE(res);
  9028. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9029. }
  9030. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9031. // clang-format off
  9032. static constexpr char cert[] =
  9033. "GlobalSign Root CA\n"
  9034. "==================\n"
  9035. "-----BEGIN CERTIFICATE-----\n"
  9036. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9037. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9038. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9039. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9040. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9041. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9042. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9043. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9044. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9045. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9046. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9047. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9048. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9049. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9050. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9051. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9052. "-----END CERTIFICATE-----\n";
  9053. // clang-format on
  9054. SSLClient cli("google.com");
  9055. cli.load_ca_cert_store(cert, sizeof(cert));
  9056. const auto res = cli.Get("/");
  9057. ASSERT_TRUE(res);
  9058. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9059. }
  9060. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9061. SSLClient cli("www.youtube.com");
  9062. cli.set_ca_cert_path(CA_CERT_FILE);
  9063. cli.enable_server_certificate_verification(true);
  9064. cli.set_follow_location(true);
  9065. auto res = cli.Get("/");
  9066. ASSERT_TRUE(res);
  9067. ASSERT_EQ(StatusCode::OK_200, res->status);
  9068. }
  9069. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9070. SSLClient cli("wWw.YouTube.Com");
  9071. cli.set_ca_cert_path(CA_CERT_FILE);
  9072. cli.enable_server_certificate_verification(true);
  9073. cli.enable_server_hostname_verification(true);
  9074. cli.set_follow_location(true);
  9075. auto res = cli.Get("/");
  9076. ASSERT_TRUE(res);
  9077. ASSERT_EQ(StatusCode::OK_200, res->status);
  9078. }
  9079. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9080. SSLClient cli("gOoGlE.COm");
  9081. cli.enable_server_certificate_verification(true);
  9082. cli.enable_server_hostname_verification(true);
  9083. cli.set_follow_location(true);
  9084. auto res = cli.Get("/");
  9085. ASSERT_TRUE(res);
  9086. ASSERT_EQ(StatusCode::OK_200, res->status);
  9087. }
  9088. TEST(SSLClientTest, Issue2004_Online) {
  9089. Client client("https://google.com");
  9090. client.set_follow_location(true);
  9091. auto res = client.Get("/");
  9092. ASSERT_TRUE(res);
  9093. ASSERT_EQ(StatusCode::OK_200, res->status);
  9094. auto body = res->body;
  9095. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9096. }
  9097. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9098. // Create SSLClient with invalid cert/key to make is_valid() return false
  9099. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9100. "nonexistent_key.pem");
  9101. // is_valid() should be false due to cert loading failure
  9102. ASSERT_FALSE(cli.is_valid());
  9103. auto res = cli.Get("/");
  9104. ASSERT_FALSE(res);
  9105. EXPECT_EQ(Error::SSLConnection, res.error());
  9106. }
  9107. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9108. // Test for Issue #2251: SSL error not properly reported when client cert
  9109. // and key paths are swapped or mismatched
  9110. // This simulates the scenario where user accidentally swaps the cert and key
  9111. // files
  9112. // Using client cert file as private key and vice versa (completely wrong)
  9113. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9114. // Should fail validation due to cert/key mismatch
  9115. ASSERT_FALSE(cli.is_valid());
  9116. // Attempt to make a request should fail with proper error
  9117. auto res = cli.Get("/");
  9118. ASSERT_FALSE(res);
  9119. EXPECT_EQ(Error::SSLConnection, res.error());
  9120. // SSL error should be recorded in the Result object (this is the key fix for
  9121. // Issue #2251)
  9122. auto backend_error = res.ssl_backend_error();
  9123. EXPECT_NE(0u, backend_error);
  9124. }
  9125. // Tests cert/key mismatch detection at the TLS context level
  9126. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9127. // Test that using mismatched cert/key causes connection failure.
  9128. // We verify this at the SSLClient level rather than through internal
  9129. // TLS API functions.
  9130. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9131. cli.enable_server_certificate_verification(false);
  9132. cli.set_connection_timeout(2);
  9133. // The mismatch should cause a connection or handshake error
  9134. auto res = cli.Get("/test");
  9135. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9136. // Either way, the request should fail
  9137. EXPECT_FALSE(res);
  9138. }
  9139. #endif
  9140. #if 0
  9141. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9142. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9143. ASSERT_TRUE(cli != nullptr);
  9144. cli->set_address_family(AF_INET6);
  9145. cli->set_interface("en0");
  9146. auto res = cli->Get("/get");
  9147. ASSERT_TRUE(res);
  9148. ASSERT_EQ(StatusCode::OK_200, res->status);
  9149. }
  9150. #endif
  9151. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9152. #ifdef CPPHTTPLIB_SSL_ENABLED
  9153. void ClientCertPresent(
  9154. const std::string &client_cert_file,
  9155. const std::string &client_private_key_file,
  9156. const std::string &client_encrypted_private_key_pass = std::string()) {
  9157. using namespace httplib::tls;
  9158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9159. CLIENT_CA_CERT_DIR);
  9160. ASSERT_TRUE(svr.is_valid());
  9161. svr.Get("/test", [&](const Request &req, Response &res) {
  9162. res.set_content("test", "text/plain");
  9163. auto cert = req.peer_cert();
  9164. ASSERT_TRUE(static_cast<bool>(cert));
  9165. std::string common_name = cert.subject_cn();
  9166. EXPECT_EQ("Common Name", common_name);
  9167. });
  9168. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9169. auto se = detail::scope_exit([&] {
  9170. svr.stop();
  9171. t.join();
  9172. ASSERT_FALSE(svr.is_running());
  9173. });
  9174. svr.wait_until_ready();
  9175. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9176. client_encrypted_private_key_pass);
  9177. cli.enable_server_certificate_verification(false);
  9178. cli.set_connection_timeout(30);
  9179. auto res = cli.Get("/test");
  9180. ASSERT_TRUE(res);
  9181. ASSERT_EQ(StatusCode::OK_200, res->status);
  9182. }
  9183. TEST(SSLClientServerTest, ClientCertPresent) {
  9184. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9185. }
  9186. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9187. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9188. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9189. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9190. }
  9191. // PEM memory-based constructor tests (works with all TLS backends)
  9192. void PemMemoryClientCertPresent(
  9193. const std::string &client_cert_file,
  9194. const std::string &client_private_key_file,
  9195. const std::string &client_encrypted_private_key_pass = std::string()) {
  9196. // Read PEM files into memory
  9197. std::string server_cert_pem, server_key_pem;
  9198. std::string client_ca_pem;
  9199. std::string client_cert_pem, client_key_pem;
  9200. read_file(SERVER_CERT_FILE, server_cert_pem);
  9201. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9202. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9203. read_file(client_cert_file, client_cert_pem);
  9204. read_file(client_private_key_file, client_key_pem);
  9205. // Create server with PEM memory
  9206. SSLServer::PemMemory server_pem = {
  9207. server_cert_pem.c_str(),
  9208. server_cert_pem.size(),
  9209. server_key_pem.c_str(),
  9210. server_key_pem.size(),
  9211. client_ca_pem.c_str(),
  9212. client_ca_pem.size(),
  9213. nullptr // no password for server key
  9214. };
  9215. SSLServer svr(server_pem);
  9216. ASSERT_TRUE(svr.is_valid());
  9217. svr.Get("/test", [&](const Request &, Response &res) {
  9218. res.set_content("test", "text/plain");
  9219. });
  9220. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9221. auto se = detail::scope_exit([&] {
  9222. svr.stop();
  9223. t.join();
  9224. ASSERT_FALSE(svr.is_running());
  9225. });
  9226. svr.wait_until_ready();
  9227. // Create client with PEM memory
  9228. const char *password = client_encrypted_private_key_pass.empty()
  9229. ? nullptr
  9230. : client_encrypted_private_key_pass.c_str();
  9231. SSLClient::PemMemory client_pem = {
  9232. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9233. client_key_pem.size(), password};
  9234. SSLClient cli(HOST, PORT, client_pem);
  9235. cli.enable_server_certificate_verification(false);
  9236. cli.set_connection_timeout(30);
  9237. auto res = cli.Get("/test");
  9238. ASSERT_TRUE(res);
  9239. ASSERT_EQ(StatusCode::OK_200, res->status);
  9240. }
  9241. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9242. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9243. }
  9244. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9245. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9246. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9247. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9248. }
  9249. TEST(SSLClientServerTest, ClientCertMissing) {
  9250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9251. CLIENT_CA_CERT_DIR);
  9252. ASSERT_TRUE(svr.is_valid());
  9253. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9255. auto se = detail::scope_exit([&] {
  9256. svr.stop();
  9257. t.join();
  9258. ASSERT_FALSE(svr.is_running());
  9259. });
  9260. svr.wait_until_ready();
  9261. SSLClient cli(HOST, PORT);
  9262. cli.set_connection_timeout(30);
  9263. auto res = cli.Get("/test");
  9264. ASSERT_TRUE(!res);
  9265. // When client cert is missing and server requires it, connection fails
  9266. // Error type depends on backend implementation
  9267. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9268. res.error() == Error::SSLConnection);
  9269. // Verify backend error is captured
  9270. // Note: This test may have different error codes depending on the exact
  9271. // verification failure
  9272. EXPECT_NE(0UL, res.ssl_backend_error());
  9273. }
  9274. TEST(SSLClientServerTest, TrustDirOptional) {
  9275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9276. ASSERT_TRUE(svr.is_valid());
  9277. svr.Get("/test", [&](const Request &, Response &res) {
  9278. res.set_content("test", "text/plain");
  9279. });
  9280. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9281. auto se = detail::scope_exit([&] {
  9282. svr.stop();
  9283. t.join();
  9284. ASSERT_FALSE(svr.is_running());
  9285. });
  9286. svr.wait_until_ready();
  9287. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9288. cli.enable_server_certificate_verification(false);
  9289. cli.set_connection_timeout(30);
  9290. auto res = cli.Get("/test");
  9291. ASSERT_TRUE(res);
  9292. ASSERT_EQ(StatusCode::OK_200, res->status);
  9293. }
  9294. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9295. class NoListenSSLServer : public SSLServer {
  9296. public:
  9297. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9298. const char *client_ca_cert_file_path,
  9299. const char *client_ca_cert_dir_path = nullptr)
  9300. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9301. client_ca_cert_dir_path),
  9302. stop_(false) {}
  9303. std::atomic_bool stop_;
  9304. private:
  9305. bool process_and_close_socket(socket_t /*sock*/) override {
  9306. // Don't create SSL context
  9307. while (!stop_.load()) {
  9308. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9309. }
  9310. return true;
  9311. }
  9312. };
  9313. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9314. CLIENT_CA_CERT_FILE);
  9315. ASSERT_TRUE(svr.is_valid());
  9316. svr.Get("/test", [&](const Request &, Response &res) {
  9317. res.set_content("test", "text/plain");
  9318. });
  9319. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9320. auto se = detail::scope_exit([&] {
  9321. svr.stop_ = true;
  9322. svr.stop();
  9323. t.join();
  9324. ASSERT_FALSE(svr.is_running());
  9325. });
  9326. svr.wait_until_ready();
  9327. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9328. cli.enable_server_certificate_verification(false);
  9329. cli.set_connection_timeout(1);
  9330. auto res = cli.Get("/test");
  9331. ASSERT_TRUE(!res);
  9332. EXPECT_EQ(Error::SSLConnection, res.error());
  9333. // Timeout results in WantRead error code (maps to backend-specific value)
  9334. EXPECT_NE(0, res.ssl_error());
  9335. }
  9336. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9337. // Test SSLServer with client certificate verification using the standard
  9338. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9340. CLIENT_CA_CERT_DIR);
  9341. ASSERT_TRUE(svr.is_valid());
  9342. svr.Get("/test", [&](const Request &req, Response &res) {
  9343. res.set_content("test", "text/plain");
  9344. auto cert = req.peer_cert();
  9345. ASSERT_TRUE(static_cast<bool>(cert));
  9346. auto common_name = cert.subject_cn();
  9347. EXPECT_EQ("Common Name", common_name);
  9348. });
  9349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9350. auto se = detail::scope_exit([&] {
  9351. svr.stop();
  9352. t.join();
  9353. ASSERT_FALSE(svr.is_running());
  9354. });
  9355. svr.wait_until_ready();
  9356. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9357. cli.enable_server_certificate_verification(false);
  9358. cli.set_connection_timeout(30);
  9359. auto res = cli.Get("/test");
  9360. ASSERT_TRUE(res);
  9361. ASSERT_EQ(StatusCode::OK_200, res->status);
  9362. }
  9363. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9364. // Verifies that wildcard matching and exact matching work consistently
  9365. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9366. using namespace httplib::tls;
  9367. // We need a running server to test against
  9368. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9369. ASSERT_TRUE(svr.is_valid());
  9370. svr.Get("/test", [](const Request &, Response &res) {
  9371. res.set_content("ok", "text/plain");
  9372. });
  9373. thread t([&]() { svr.listen(HOST, PORT); });
  9374. auto se = detail::scope_exit([&] {
  9375. svr.stop();
  9376. t.join();
  9377. });
  9378. svr.wait_until_ready();
  9379. bool verify_callback_called = false;
  9380. bool verify_result_wrong = false;
  9381. SSLClient cli(HOST, PORT);
  9382. cli.enable_server_certificate_verification(true);
  9383. cli.set_ca_cert_path(CA_CERT_FILE);
  9384. cli.set_connection_timeout(5);
  9385. // Note: Test certificate has CN="Common Name", not "localhost"
  9386. bool verify_result_cn = false;
  9387. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9388. verify_callback_called = true;
  9389. if (!ctx.cert) return false;
  9390. // Test 1: "Common Name" should match (our test server cert CN)
  9391. verify_result_cn = ctx.check_hostname("Common Name");
  9392. // Test 2: wrong hostname should not match
  9393. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9394. return true; // Accept for the purpose of this test
  9395. });
  9396. auto res = cli.Get("/test");
  9397. // The request may succeed or fail depending on cert configuration
  9398. // but the callback should have been called
  9399. ASSERT_TRUE(verify_callback_called)
  9400. << "Verify callback should have been called";
  9401. // CN="Common Name" should match our test certificate
  9402. //
  9403. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9404. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9405. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9406. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9407. // <openssl/base.h>, which is included transitively when
  9408. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9409. #if defined(OPENSSL_IS_BORINGSSL)
  9410. EXPECT_FALSE(verify_result_cn)
  9411. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9412. #else
  9413. EXPECT_TRUE(verify_result_cn)
  9414. << "verify_hostname should match 'Common Name' (certificate CN)";
  9415. #endif
  9416. // Wrong hostname should not match
  9417. EXPECT_FALSE(verify_result_wrong)
  9418. << "verify_hostname should not match 'wronghost.example.com'";
  9419. }
  9420. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9421. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9422. // X509_check_ip behavior and must hold for every backend.
  9423. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9424. using namespace httplib::tls;
  9425. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9426. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9427. ASSERT_TRUE(svr.is_valid());
  9428. svr.Get("/test", [](const Request &, Response &res) {
  9429. res.set_content("ok", "text/plain");
  9430. });
  9431. thread t([&]() { svr.listen(HOST, PORT); });
  9432. auto se = detail::scope_exit([&] {
  9433. svr.stop();
  9434. t.join();
  9435. });
  9436. svr.wait_until_ready();
  9437. bool verify_callback_called = false;
  9438. bool ip_matched_via_cn = true;
  9439. SSLClient cli(HOST, PORT);
  9440. cli.enable_server_certificate_verification(true);
  9441. cli.set_ca_cert_path(CA_CERT_FILE);
  9442. cli.set_connection_timeout(5);
  9443. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9444. verify_callback_called = true;
  9445. if (!ctx.cert) return false;
  9446. // The IP appears only in the CN, so it must NOT be accepted.
  9447. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9448. return true; // Accept for the purpose of this test
  9449. });
  9450. cli.Get("/test");
  9451. ASSERT_TRUE(verify_callback_called)
  9452. << "Verify callback should have been called";
  9453. EXPECT_FALSE(ip_matched_via_cn)
  9454. << "An IP host must not be authenticated via the certificate CN";
  9455. }
  9456. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9457. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9458. using namespace httplib::tls;
  9459. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9460. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9461. ASSERT_TRUE(svr.is_valid());
  9462. svr.Get("/test", [](const Request &, Response &res) {
  9463. res.set_content("ok", "text/plain");
  9464. });
  9465. thread t([&]() { svr.listen(HOST, PORT); });
  9466. auto se = detail::scope_exit([&] {
  9467. svr.stop();
  9468. t.join();
  9469. });
  9470. svr.wait_until_ready();
  9471. bool verify_callback_called = false;
  9472. bool san_matched = false;
  9473. bool wrong_ipv6_matched = true;
  9474. bool cn_ipv6_matched = true;
  9475. SSLClient cli(HOST, PORT);
  9476. cli.enable_server_certificate_verification(true);
  9477. cli.set_ca_cert_path(CA_CERT_FILE);
  9478. cli.set_connection_timeout(5);
  9479. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9480. verify_callback_called = true;
  9481. if (!ctx.cert) return false;
  9482. // Matches the IPv6 iPAddress SAN.
  9483. san_matched = ctx.check_hostname("2001:db8::1");
  9484. // A different IPv6 address must not match.
  9485. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9486. // "::1" lives only in the CN, so it must not be accepted.
  9487. cn_ipv6_matched = ctx.check_hostname("::1");
  9488. return true; // Accept for the purpose of this test
  9489. });
  9490. cli.Get("/test");
  9491. ASSERT_TRUE(verify_callback_called)
  9492. << "Verify callback should have been called";
  9493. EXPECT_TRUE(san_matched)
  9494. << "verify_hostname should match an IPv6 iPAddress SAN";
  9495. EXPECT_FALSE(wrong_ipv6_matched)
  9496. << "verify_hostname should not match a non-matching IPv6 address";
  9497. EXPECT_FALSE(cn_ipv6_matched)
  9498. << "An IPv6 host must not be authenticated via the certificate CN";
  9499. }
  9500. #endif
  9501. // mbedTLS-specific callback constructor test
  9502. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9503. #ifdef CPPHTTPLIB_SSL_ENABLED
  9504. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9505. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9506. ASSERT_TRUE(svr.is_valid());
  9507. // Set up a handler to verify client certificate is present
  9508. bool client_cert_verified = false;
  9509. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9510. // Verify that client certificate was provided
  9511. client_cert_verified = true;
  9512. res.set_content("success", "text/plain");
  9513. });
  9514. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. t.join();
  9518. ASSERT_FALSE(svr.is_running());
  9519. });
  9520. svr.wait_until_ready();
  9521. // Client with certificate
  9522. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9523. cli.enable_server_certificate_verification(false);
  9524. cli.set_connection_timeout(30);
  9525. auto res = cli.Get("/test");
  9526. ASSERT_TRUE(res);
  9527. ASSERT_EQ(StatusCode::OK_200, res->status);
  9528. ASSERT_TRUE(client_cert_verified);
  9529. EXPECT_EQ("success", res->body);
  9530. }
  9531. #endif
  9532. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9533. // backends
  9534. #ifdef CPPHTTPLIB_SSL_ENABLED
  9535. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9536. using namespace httplib::tls;
  9537. // Test that when client CA cert file is provided,
  9538. // the server properly requests and validates client certificates
  9539. // Create a server with client authentication
  9540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9541. ASSERT_TRUE(svr.is_valid());
  9542. bool handler_called = false;
  9543. svr.Get("/test", [&](const Request &req, Response &res) {
  9544. handler_called = true;
  9545. // Verify that a client certificate was provided
  9546. auto cert = req.peer_cert();
  9547. ASSERT_TRUE(static_cast<bool>(cert));
  9548. // Get the issuer name
  9549. std::string issuer_str = cert.issuer_name();
  9550. ASSERT_FALSE(issuer_str.empty());
  9551. // The client certificate should be issued by our test CA
  9552. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9553. res.set_content("authenticated", "text/plain");
  9554. });
  9555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9556. auto se = detail::scope_exit([&] {
  9557. svr.stop();
  9558. t.join();
  9559. ASSERT_FALSE(svr.is_running());
  9560. });
  9561. svr.wait_until_ready();
  9562. // Connect with a client certificate issued by the CA
  9563. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9564. cli.enable_server_certificate_verification(false);
  9565. cli.set_connection_timeout(30);
  9566. auto res = cli.Get("/test");
  9567. ASSERT_TRUE(res);
  9568. ASSERT_EQ(StatusCode::OK_200, res->status);
  9569. ASSERT_TRUE(handler_called);
  9570. EXPECT_EQ("authenticated", res->body);
  9571. }
  9572. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9573. using namespace httplib::tls;
  9574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9575. ASSERT_TRUE(svr.is_valid());
  9576. svr.Get("/test", [](const Request &, Response &res) {
  9577. res.set_content("ok", "text/plain");
  9578. });
  9579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9580. auto se = detail::scope_exit([&] {
  9581. svr.stop();
  9582. t.join();
  9583. });
  9584. svr.wait_until_ready();
  9585. SSLClient cli(HOST, PORT);
  9586. cli.enable_server_certificate_verification(false);
  9587. cli.set_connection_timeout(30);
  9588. bool cert_checked = false;
  9589. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9590. if (ctx.cert) {
  9591. auto sans = ctx.sans();
  9592. // Test certificate may or may not have SANs - just verify the API
  9593. // works If SANs exist, verify the types are valid
  9594. for (const auto &san : sans) {
  9595. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9596. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9597. san.type == SanType::OTHER);
  9598. EXPECT_FALSE(san.value.empty());
  9599. }
  9600. cert_checked = true;
  9601. }
  9602. return true;
  9603. });
  9604. auto res = cli.Get("/test");
  9605. ASSERT_TRUE(res);
  9606. EXPECT_TRUE(cert_checked);
  9607. }
  9608. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9609. using namespace httplib::tls;
  9610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9611. ASSERT_TRUE(svr.is_valid());
  9612. svr.Get("/test", [](const Request &, Response &res) {
  9613. res.set_content("ok", "text/plain");
  9614. });
  9615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9616. auto se = detail::scope_exit([&] {
  9617. svr.stop();
  9618. t.join();
  9619. });
  9620. svr.wait_until_ready();
  9621. SSLClient cli(HOST, PORT);
  9622. cli.enable_server_certificate_verification(false);
  9623. cli.set_connection_timeout(30);
  9624. bool validity_checked = false;
  9625. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9626. if (ctx.cert) {
  9627. time_t not_before = 0, not_after = 0;
  9628. bool result = ctx.validity(not_before, not_after);
  9629. EXPECT_TRUE(result);
  9630. // Verify that not_before < now < not_after for a valid cert
  9631. time_t now = time(nullptr);
  9632. EXPECT_LT(not_before, now);
  9633. EXPECT_GT(not_after, now);
  9634. validity_checked = true;
  9635. }
  9636. return true;
  9637. });
  9638. auto res = cli.Get("/test");
  9639. ASSERT_TRUE(res);
  9640. EXPECT_TRUE(validity_checked);
  9641. }
  9642. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9643. using namespace httplib::tls;
  9644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9645. ASSERT_TRUE(svr.is_valid());
  9646. svr.Get("/test", [](const Request &, Response &res) {
  9647. res.set_content("ok", "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. });
  9654. svr.wait_until_ready();
  9655. SSLClient cli(HOST, PORT);
  9656. cli.enable_server_certificate_verification(false);
  9657. cli.set_connection_timeout(30);
  9658. bool serial_checked = false;
  9659. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9660. if (ctx.cert) {
  9661. std::string serial = ctx.serial();
  9662. EXPECT_FALSE(serial.empty());
  9663. // Serial should be a hex string
  9664. for (char c : serial) {
  9665. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9666. (c >= 'a' && c <= 'f'));
  9667. }
  9668. serial_checked = true;
  9669. }
  9670. return true;
  9671. });
  9672. auto res = cli.Get("/test");
  9673. ASSERT_TRUE(res);
  9674. EXPECT_TRUE(serial_checked);
  9675. }
  9676. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9677. // Test 1: Valid CA file - no error should be recorded
  9678. {
  9679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9680. CLIENT_CA_CERT_FILE);
  9681. ASSERT_TRUE(svr.is_valid());
  9682. // With valid setup, last_ssl_error should be 0
  9683. EXPECT_EQ(0, svr.ssl_last_error());
  9684. }
  9685. // Test 2: Invalid CA file content
  9686. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9687. {
  9688. // Create a temporary file with completely invalid content
  9689. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9690. {
  9691. std::ofstream ofs(temp_invalid_ca);
  9692. ofs << "This is not a certificate file at all\n";
  9693. ofs << "Just plain text content\n";
  9694. }
  9695. // Create server with invalid CA file
  9696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9697. // Clean up temporary file
  9698. std::remove(temp_invalid_ca);
  9699. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9700. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9701. // Note: SSL_CTX_load_verify_locations typically fails first,
  9702. // but our error handling code path is still exercised
  9703. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9704. }
  9705. }
  9706. TEST(VerifyCallbackTest, VerifyContextFields) {
  9707. using namespace httplib::tls;
  9708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9709. ASSERT_TRUE(svr.is_valid());
  9710. svr.Get("/test", [](const Request &, Response &res) {
  9711. res.set_content("ok", "text/plain");
  9712. });
  9713. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9714. auto se = detail::scope_exit([&] {
  9715. svr.stop();
  9716. t.join();
  9717. });
  9718. svr.wait_until_ready();
  9719. SSLClient cli(HOST, PORT);
  9720. cli.enable_server_certificate_verification(false);
  9721. cli.set_connection_timeout(30);
  9722. int callback_count = 0;
  9723. bool saw_leaf_cert = false;
  9724. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9725. if (ctx.cert) {
  9726. callback_count++;
  9727. // We should see at least one certificate (the leaf)
  9728. std::string cn = ctx.subject_cn();
  9729. if (!cn.empty()) { saw_leaf_cert = true; }
  9730. // Verify context fields are populated
  9731. EXPECT_NE(ctx.session, nullptr);
  9732. EXPECT_GE(ctx.depth, 0);
  9733. }
  9734. return true;
  9735. });
  9736. auto res = cli.Get("/test");
  9737. ASSERT_TRUE(res);
  9738. EXPECT_GT(callback_count, 0);
  9739. EXPECT_TRUE(saw_leaf_cert);
  9740. }
  9741. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9742. using httplib::tls::TlsError;
  9743. // Test that verify_error_to_string returns empty for success
  9744. std::string success_str = TlsError::verify_error_to_string(0);
  9745. EXPECT_TRUE(success_str.empty());
  9746. // Test that verify_error_to_string returns non-empty for error codes
  9747. // Using a common error code (certificate expired)
  9748. std::string error_str =
  9749. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9750. EXPECT_FALSE(error_str.empty());
  9751. }
  9752. TEST(SessionVerifierTest, CertificateAccepted) {
  9753. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9754. ASSERT_TRUE(svr.is_valid());
  9755. svr.Get("/test", [](const Request &, Response &res) {
  9756. res.set_content("ok", "text/plain");
  9757. });
  9758. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9759. auto se = detail::scope_exit([&] {
  9760. svr.stop();
  9761. t.join();
  9762. });
  9763. svr.wait_until_ready();
  9764. SSLClient cli(HOST, PORT);
  9765. cli.enable_server_certificate_verification(false);
  9766. cli.set_connection_timeout(30);
  9767. bool callback_called = false;
  9768. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9769. EXPECT_NE(session, nullptr);
  9770. callback_called = true;
  9771. return SSLVerifierResponse::CertificateAccepted;
  9772. });
  9773. auto res = cli.Get("/test");
  9774. ASSERT_TRUE(res);
  9775. EXPECT_EQ(200, res->status);
  9776. EXPECT_TRUE(callback_called);
  9777. }
  9778. TEST(SessionVerifierTest, CertificateRejected) {
  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 callback_called = false;
  9794. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9795. EXPECT_NE(session, nullptr);
  9796. callback_called = true;
  9797. return SSLVerifierResponse::CertificateRejected;
  9798. });
  9799. auto res = cli.Get("/test");
  9800. EXPECT_FALSE(res);
  9801. EXPECT_TRUE(callback_called);
  9802. }
  9803. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9804. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9805. ASSERT_TRUE(svr.is_valid());
  9806. svr.Get("/test", [](const Request &, Response &res) {
  9807. res.set_content("ok", "text/plain");
  9808. });
  9809. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9810. auto se = detail::scope_exit([&] {
  9811. svr.stop();
  9812. t.join();
  9813. });
  9814. svr.wait_until_ready();
  9815. // NoDecisionMade with verification disabled should succeed (no default check)
  9816. SSLClient cli(HOST, PORT);
  9817. cli.enable_server_certificate_verification(false);
  9818. cli.set_connection_timeout(30);
  9819. bool callback_called = false;
  9820. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9821. EXPECT_NE(session, nullptr);
  9822. callback_called = true;
  9823. return SSLVerifierResponse::NoDecisionMade;
  9824. });
  9825. auto res = cli.Get("/test");
  9826. ASSERT_TRUE(res);
  9827. EXPECT_EQ(200, res->status);
  9828. EXPECT_TRUE(callback_called);
  9829. }
  9830. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9832. ASSERT_TRUE(svr.is_valid());
  9833. svr.Get("/test", [](const Request &, Response &res) {
  9834. res.set_content("ok", "text/plain");
  9835. });
  9836. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9837. auto se = detail::scope_exit([&] {
  9838. svr.stop();
  9839. t.join();
  9840. });
  9841. svr.wait_until_ready();
  9842. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9843. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9844. // so we only check that the request fails, not whether the callback was
  9845. // called.
  9846. SSLClient cli(HOST, PORT);
  9847. cli.enable_server_certificate_verification(true);
  9848. cli.set_connection_timeout(30);
  9849. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9850. EXPECT_NE(session, nullptr);
  9851. return SSLVerifierResponse::NoDecisionMade;
  9852. });
  9853. auto res = cli.Get("/test");
  9854. EXPECT_FALSE(res);
  9855. }
  9856. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9857. // Test SSL server using PemMemory constructor with client CA certificates
  9858. // Read PEM files
  9859. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9860. read_file(SERVER_CERT_FILE, server_cert_pem);
  9861. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9862. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9863. // Create SSLServer with PemMemory constructor including client CA
  9864. SSLServer::PemMemory server_pem = {
  9865. server_cert_pem.c_str(),
  9866. server_cert_pem.size(),
  9867. server_key_pem.c_str(),
  9868. server_key_pem.size(),
  9869. client_ca_pem.c_str(),
  9870. client_ca_pem.size(),
  9871. nullptr // no password for server key
  9872. };
  9873. SSLServer svr(server_pem);
  9874. ASSERT_TRUE(svr.is_valid());
  9875. // No SSL error should be recorded for valid setup
  9876. EXPECT_EQ(0, svr.ssl_last_error());
  9877. // Set up server endpoints
  9878. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9879. res.set_content("ok", "text/plain");
  9880. });
  9881. // Start server in a thread
  9882. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9883. svr.wait_until_ready();
  9884. // Connect with client certificate (using constructor with paths)
  9885. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9886. cli.enable_server_certificate_verification(false);
  9887. auto res = cli.Get("/test-pem-ca");
  9888. ASSERT_TRUE(res);
  9889. EXPECT_EQ(200, res->status);
  9890. EXPECT_EQ("ok", res->body);
  9891. svr.stop();
  9892. server_thread.join();
  9893. }
  9894. #endif
  9895. #ifdef _WIN32
  9896. TEST(CleanupTest, WSACleanup) {
  9897. int ret = WSACleanup();
  9898. ASSERT_EQ(0, ret);
  9899. }
  9900. #endif
  9901. #ifndef CPPHTTPLIB_SSL_ENABLED
  9902. TEST(NoSSLSupport, SimpleInterface) {
  9903. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9904. }
  9905. #endif
  9906. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9907. TEST(InvalidScheme, SimpleInterface) {
  9908. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9909. }
  9910. #endif
  9911. TEST(NoScheme, SimpleInterface) {
  9912. Client cli("yahoo.com:80");
  9913. ASSERT_TRUE(cli.is_valid());
  9914. }
  9915. TEST(SendAPI, SimpleInterface_Online) {
  9916. Client cli("http://yahoo.com");
  9917. Request req;
  9918. req.method = "GET";
  9919. req.path = "/";
  9920. auto res = cli.send(req);
  9921. ASSERT_TRUE(res);
  9922. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9923. }
  9924. TEST(SendAPI, WithParamsInRequest) {
  9925. Server svr;
  9926. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9927. EXPECT_TRUE(req.has_param("test"));
  9928. EXPECT_EQ("test_value", req.get_param_value("test"));
  9929. });
  9930. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9931. auto se = detail::scope_exit([&] {
  9932. svr.stop();
  9933. t.join();
  9934. ASSERT_FALSE(svr.is_running());
  9935. });
  9936. svr.wait_until_ready();
  9937. Client cli(HOST, PORT);
  9938. {
  9939. Request req;
  9940. req.method = "GET";
  9941. req.path = "/";
  9942. req.params.emplace("test", "test_value");
  9943. auto res = cli.send(req);
  9944. ASSERT_TRUE(res);
  9945. }
  9946. {
  9947. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9948. ASSERT_TRUE(res);
  9949. }
  9950. }
  9951. TEST(ClientImplMethods, GetSocketTest) {
  9952. httplib::Server svr;
  9953. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9954. res.status = StatusCode::OK_200;
  9955. });
  9956. auto port = svr.bind_to_any_port("127.0.0.1");
  9957. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9958. auto se = detail::scope_exit([&] {
  9959. svr.stop();
  9960. thread.join();
  9961. ASSERT_FALSE(svr.is_running());
  9962. });
  9963. svr.wait_until_ready();
  9964. {
  9965. httplib::Client cli("127.0.0.1", port);
  9966. cli.set_keep_alive(true);
  9967. // Use the behavior of cpp-httplib of opening the connection
  9968. // only when the first request happens. If that changes,
  9969. // this test would be obsolete.
  9970. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9971. // This also implicitly tests the server. But other tests would fail much
  9972. // earlier than this one to be considered.
  9973. auto res = cli.Get("/");
  9974. ASSERT_TRUE(res);
  9975. EXPECT_EQ(StatusCode::OK_200, res->status);
  9976. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9977. }
  9978. }
  9979. #ifdef CPPHTTPLIB_SSL_ENABLED
  9980. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9981. Client cli("http://yahoo.com");
  9982. auto res = cli.Get("/");
  9983. ASSERT_TRUE(res);
  9984. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9985. cli.set_follow_location(true);
  9986. res = cli.Get("/");
  9987. ASSERT_TRUE(res);
  9988. EXPECT_EQ(StatusCode::OK_200, res->status);
  9989. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9990. }
  9991. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9992. Client cli("https://yahoo.com");
  9993. auto res = cli.Get("/");
  9994. ASSERT_TRUE(res);
  9995. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9996. cli.set_follow_location(true);
  9997. res = cli.Get("/");
  9998. ASSERT_TRUE(res);
  9999. EXPECT_EQ(StatusCode::OK_200, res->status);
  10000. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10001. }
  10002. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10003. Client cli("https://yahoo.com");
  10004. auto res = cli.Get("/");
  10005. ASSERT_TRUE(res);
  10006. ASSERT_FALSE(!res);
  10007. ASSERT_TRUE(res);
  10008. ASSERT_FALSE(res == nullptr);
  10009. ASSERT_TRUE(res != nullptr);
  10010. EXPECT_EQ(Error::Success, res.error());
  10011. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10012. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10013. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10014. cli.set_follow_location(true);
  10015. res = cli.Get("/");
  10016. ASSERT_TRUE(res);
  10017. EXPECT_EQ(Error::Success, res.error());
  10018. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10019. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10020. EXPECT_EQ(StatusCode::OK_200, res->status);
  10021. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10022. }
  10023. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10024. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10025. Client cli("https://cdnjs.cloudflare.com");
  10026. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10027. Headers{{"Accept-Encoding", "br"}});
  10028. ASSERT_TRUE(res);
  10029. EXPECT_EQ(StatusCode::OK_200, res->status);
  10030. EXPECT_EQ(287630U, res->body.size());
  10031. EXPECT_EQ("application/javascript; charset=utf-8",
  10032. res->get_header_value("Content-Type"));
  10033. }
  10034. #endif
  10035. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10036. #undef REDIR_HOST // Silence compiler warning
  10037. #define REDIR_HOST "https://httpbingo.org"
  10038. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10039. Client cli(REDIR_HOST);
  10040. cli.set_follow_location(true);
  10041. auto res =
  10042. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10043. ASSERT_TRUE(res);
  10044. EXPECT_EQ(StatusCode::OK_200, res->status);
  10045. }
  10046. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10047. Client cli(REDIR_HOST);
  10048. cli.set_follow_location(true);
  10049. Params params;
  10050. params.emplace("url", "http://example.com");
  10051. params.emplace("status_code", "302");
  10052. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10053. ASSERT_TRUE(res);
  10054. EXPECT_EQ(StatusCode::OK_200, res->status);
  10055. }
  10056. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10057. Client cli(REDIR_HOST);
  10058. cli.set_follow_location(true);
  10059. Params params;
  10060. params.emplace("url", "http://example.com");
  10061. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10062. ASSERT_TRUE(res);
  10063. EXPECT_EQ(StatusCode::OK_200, res->status);
  10064. }
  10065. TEST(HttpToHttpsRedirectTest, CertFile) {
  10066. auto ssl_port = PORT + 1;
  10067. Server svr;
  10068. ASSERT_TRUE(svr.is_valid());
  10069. svr.Get("/index", [&](const Request &, Response &res) {
  10070. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10071. "/index");
  10072. svr.stop();
  10073. });
  10074. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10075. ASSERT_TRUE(ssl_svr.is_valid());
  10076. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10077. res.set_content("test", "text/plain");
  10078. ssl_svr.stop();
  10079. });
  10080. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10081. thread t2 =
  10082. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10083. auto se = detail::scope_exit([&] {
  10084. t2.join();
  10085. t.join();
  10086. ASSERT_FALSE(svr.is_running());
  10087. });
  10088. svr.wait_until_ready();
  10089. ssl_svr.wait_until_ready();
  10090. Client cli("127.0.0.1", PORT);
  10091. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10092. cli.enable_server_certificate_verification(true);
  10093. cli.set_follow_location(true);
  10094. cli.set_connection_timeout(30);
  10095. auto res = cli.Get("/index");
  10096. ASSERT_TRUE(res);
  10097. ASSERT_EQ(StatusCode::OK_200, res->status);
  10098. }
  10099. TEST(SSLClientRedirectTest, CertFile) {
  10100. auto ssl_port = PORT + 1;
  10101. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10102. ASSERT_TRUE(ssl_svr1.is_valid());
  10103. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10104. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10105. "/index");
  10106. ssl_svr1.stop();
  10107. });
  10108. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10109. ASSERT_TRUE(ssl_svr2.is_valid());
  10110. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10111. res.set_content("test", "text/plain");
  10112. ssl_svr2.stop();
  10113. });
  10114. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10115. thread t2 =
  10116. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10117. auto se = detail::scope_exit([&] {
  10118. t2.join();
  10119. t.join();
  10120. ASSERT_FALSE(ssl_svr1.is_running());
  10121. });
  10122. ssl_svr1.wait_until_ready();
  10123. ssl_svr2.wait_until_ready();
  10124. SSLClient cli("127.0.0.1", PORT);
  10125. std::string cert;
  10126. read_file(SERVER_CERT2_FILE, cert);
  10127. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10128. cli.enable_server_certificate_verification(true);
  10129. cli.set_follow_location(true);
  10130. cli.set_connection_timeout(30);
  10131. auto res = cli.Get("/index");
  10132. ASSERT_TRUE(res);
  10133. ASSERT_EQ(StatusCode::OK_200, res->status);
  10134. }
  10135. #endif
  10136. #ifdef CPPHTTPLIB_SSL_ENABLED
  10137. // Test that set_ca_cert_store() skips system certs (consistent with
  10138. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10139. // should be trusted - system certs should NOT be loaded.
  10140. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10141. // Load a specific cert that is NOT a system CA cert
  10142. std::string cert;
  10143. read_file(SERVER_CERT2_FILE, cert);
  10144. SSLClient cli("google.com");
  10145. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10146. cli.enable_server_certificate_verification(true);
  10147. // This should FAIL because:
  10148. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10149. // 2. System certs should NOT be loaded when custom store is set
  10150. // If system certs WERE loaded, this would succeed
  10151. auto res = cli.Get("/");
  10152. ASSERT_FALSE(res);
  10153. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10154. }
  10155. // Same as above, but through the native store handle path. Regression test:
  10156. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10157. // merged system certs into the user-provided store.
  10158. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10159. std::string cert;
  10160. read_file(SERVER_CERT2_FILE, cert);
  10161. SSLClient cli("google.com");
  10162. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10163. cli.enable_server_certificate_verification(true);
  10164. auto res = cli.Get("/");
  10165. ASSERT_FALSE(res);
  10166. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10167. }
  10168. // A custom store set via the native handle must still verify a server whose
  10169. // cert it does contain.
  10170. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10171. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10172. ASSERT_TRUE(svr.is_valid());
  10173. svr.Get("/test", [&](const Request &, Response &res) {
  10174. res.set_content("test", "text/plain");
  10175. });
  10176. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10177. auto se = detail::scope_exit([&] {
  10178. svr.stop();
  10179. t.join();
  10180. ASSERT_FALSE(svr.is_running());
  10181. });
  10182. svr.wait_until_ready();
  10183. SSLClient cli("127.0.0.1", PORT);
  10184. std::string cert;
  10185. read_file(SERVER_CERT2_FILE, cert);
  10186. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10187. cli.enable_server_certificate_verification(true);
  10188. cli.set_connection_timeout(30);
  10189. auto res = cli.Get("/test");
  10190. ASSERT_TRUE(res);
  10191. ASSERT_EQ(StatusCode::OK_200, res->status);
  10192. }
  10193. // CA certs loaded through the universal Client must be transferred to the
  10194. // client created internally for following an HTTPS redirect. Regression test:
  10195. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10196. // the CA data for redirect transfer.
  10197. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10198. auto ssl_port = PORT + 1;
  10199. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10200. ASSERT_TRUE(ssl_svr1.is_valid());
  10201. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10202. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10203. "/index");
  10204. });
  10205. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10206. ASSERT_TRUE(ssl_svr2.is_valid());
  10207. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10208. res.set_content("test", "text/plain");
  10209. });
  10210. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10211. thread t2 =
  10212. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10213. auto se = detail::scope_exit([&] {
  10214. ssl_svr2.stop();
  10215. ssl_svr1.stop();
  10216. t2.join();
  10217. t.join();
  10218. ASSERT_FALSE(ssl_svr1.is_running());
  10219. });
  10220. ssl_svr1.wait_until_ready();
  10221. ssl_svr2.wait_until_ready();
  10222. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10223. std::string cert;
  10224. read_file(SERVER_CERT2_FILE, cert);
  10225. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10226. cli.enable_server_certificate_verification(true);
  10227. cli.set_follow_location(true);
  10228. cli.set_connection_timeout(30);
  10229. auto res = cli.Get("/index");
  10230. ASSERT_TRUE(res);
  10231. ASSERT_EQ(StatusCode::OK_200, res->status);
  10232. }
  10233. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10234. // so a host signed by a system CA verifies even though a custom CA is set
  10235. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10236. std::string cert;
  10237. read_file(SERVER_CERT2_FILE, cert);
  10238. SSLClient cli("google.com");
  10239. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10240. cli.enable_system_ca(true);
  10241. cli.enable_server_certificate_verification(true);
  10242. auto res = cli.Get("/");
  10243. ASSERT_TRUE(res);
  10244. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10245. }
  10246. // The custom CA remains effective when combined with the system CA
  10247. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10248. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10249. ASSERT_TRUE(svr.is_valid());
  10250. svr.Get("/test", [&](const Request &, Response &res) {
  10251. res.set_content("test", "text/plain");
  10252. });
  10253. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10254. auto se = detail::scope_exit([&] {
  10255. svr.stop();
  10256. t.join();
  10257. ASSERT_FALSE(svr.is_running());
  10258. });
  10259. svr.wait_until_ready();
  10260. SSLClient cli("127.0.0.1", PORT);
  10261. std::string cert;
  10262. read_file(SERVER_CERT2_FILE, cert);
  10263. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10264. cli.enable_system_ca(true);
  10265. cli.enable_server_certificate_verification(true);
  10266. cli.set_connection_timeout(30);
  10267. auto res = cli.Get("/test");
  10268. ASSERT_TRUE(res);
  10269. ASSERT_EQ(StatusCode::OK_200, res->status);
  10270. }
  10271. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10272. // skip chain verification entirely (only the certificate identity was
  10273. // checked), so a server presenting an untrusted certificate with a matching
  10274. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10275. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10276. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10277. ASSERT_TRUE(svr.is_valid());
  10278. svr.Get("/test", [&](const Request &, Response &res) {
  10279. res.set_content("test", "text/plain");
  10280. });
  10281. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10282. auto se = detail::scope_exit([&] {
  10283. svr.stop();
  10284. t.join();
  10285. ASSERT_FALSE(svr.is_running());
  10286. });
  10287. svr.wait_until_ready();
  10288. SSLClient cli("127.0.0.1", PORT);
  10289. std::string cert;
  10290. // A trusted CA that did not sign the server certificate. The server cert
  10291. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10292. // this connection.
  10293. read_file(CLIENT_CA_CERT_FILE, cert);
  10294. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10295. cli.enable_server_certificate_verification(true);
  10296. cli.set_connection_timeout(30);
  10297. auto res = cli.Get("/test");
  10298. ASSERT_FALSE(res);
  10299. }
  10300. // enable_system_ca(false) prevents system CA loading entirely
  10301. TEST(SSLClientTest, DisableSystemCa_Online) {
  10302. SSLClient cli("google.com");
  10303. cli.enable_system_ca(false);
  10304. cli.enable_server_certificate_verification(true);
  10305. auto res = cli.Get("/");
  10306. ASSERT_FALSE(res);
  10307. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10308. // itself when the CA chain is empty
  10309. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10310. res.error() == Error::SSLConnection);
  10311. }
  10312. // The universal Client forwards enable_system_ca()
  10313. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10314. std::string cert;
  10315. read_file(SERVER_CERT2_FILE, cert);
  10316. Client cli("https://google.com");
  10317. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10318. cli.enable_system_ca(true);
  10319. cli.enable_server_certificate_verification(true);
  10320. auto res = cli.Get("/");
  10321. ASSERT_TRUE(res);
  10322. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10323. }
  10324. // The system CA policy must carry over to the client created internally for
  10325. // following a cross-host HTTPS redirect
  10326. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10327. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10328. ASSERT_TRUE(svr.is_valid());
  10329. svr.Get("/index", [&](const Request &, Response &res) {
  10330. res.set_redirect("https://www.google.com/");
  10331. });
  10332. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10333. auto se = detail::scope_exit([&] {
  10334. svr.stop();
  10335. t.join();
  10336. ASSERT_FALSE(svr.is_running());
  10337. });
  10338. svr.wait_until_ready();
  10339. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10340. std::string cert;
  10341. read_file(SERVER_CERT2_FILE, cert);
  10342. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10343. cli.enable_system_ca(true);
  10344. cli.enable_server_certificate_verification(true);
  10345. cli.set_follow_location(true);
  10346. cli.set_connection_timeout(30);
  10347. // Receiving any response proves the redirect client completed the TLS
  10348. // handshake with a system-CA-signed host
  10349. auto res = cli.Get("/index");
  10350. ASSERT_TRUE(res);
  10351. }
  10352. TEST(MultipartFormDataTest, LargeData) {
  10353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10354. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10355. const ContentReader &content_reader) {
  10356. if (req.is_multipart_form_data()) {
  10357. std::vector<FormData> items;
  10358. content_reader(
  10359. [&](const FormData &file) {
  10360. items.push_back(file);
  10361. return true;
  10362. },
  10363. [&](const char *data, size_t data_length) {
  10364. items.back().content.append(data, data_length);
  10365. return true;
  10366. });
  10367. EXPECT_TRUE(std::string(items[0].name) == "document");
  10368. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10369. EXPECT_TRUE(items[0].filename == "2MB_data");
  10370. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10371. EXPECT_TRUE(items[1].name == "hello");
  10372. EXPECT_TRUE(items[1].content == "world");
  10373. EXPECT_TRUE(items[1].filename == "");
  10374. EXPECT_TRUE(items[1].content_type == "");
  10375. } else {
  10376. std::string body;
  10377. content_reader([&](const char *data, size_t data_length) {
  10378. body.append(data, data_length);
  10379. return true;
  10380. });
  10381. }
  10382. });
  10383. auto port = svr.bind_to_any_port(HOST);
  10384. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10385. auto se = detail::scope_exit([&] {
  10386. svr.stop();
  10387. t.join();
  10388. ASSERT_FALSE(svr.is_running());
  10389. });
  10390. svr.wait_until_ready();
  10391. {
  10392. std::string data(1024 * 1024 * 2, '.');
  10393. std::stringstream buffer;
  10394. buffer << data;
  10395. SSLClient cli(HOST, port);
  10396. cli.enable_server_certificate_verification(false);
  10397. UploadFormDataItems items{
  10398. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10399. {"hello", "world", "", ""},
  10400. };
  10401. auto res = cli.Post("/post", items);
  10402. ASSERT_TRUE(res);
  10403. ASSERT_EQ(StatusCode::OK_200, res->status);
  10404. }
  10405. }
  10406. TEST(MultipartFormDataTest, DataProviderItems) {
  10407. std::random_device seed_gen;
  10408. std::mt19937 random(seed_gen());
  10409. std::string rand1;
  10410. rand1.resize(1000);
  10411. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10412. std::string rand2;
  10413. rand2.resize(3000);
  10414. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10416. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10417. const ContentReader &content_reader) {
  10418. ASSERT_FALSE(req.is_multipart_form_data());
  10419. std::string body;
  10420. content_reader([&](const char *data, size_t data_length) {
  10421. body.append(data, data_length);
  10422. return true;
  10423. });
  10424. EXPECT_EQ(body, "");
  10425. });
  10426. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10427. const ContentReader &content_reader) {
  10428. ASSERT_TRUE(req.is_multipart_form_data());
  10429. std::vector<FormData> items;
  10430. content_reader(
  10431. [&](const FormData &file) {
  10432. items.push_back(file);
  10433. return true;
  10434. },
  10435. [&](const char *data, size_t data_length) {
  10436. items.back().content.append(data, data_length);
  10437. return true;
  10438. });
  10439. ASSERT_TRUE(items.size() == 2);
  10440. EXPECT_EQ(std::string(items[0].name), "name1");
  10441. EXPECT_EQ(items[0].content, "Testing123");
  10442. EXPECT_EQ(items[0].filename, "filename1");
  10443. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10444. EXPECT_EQ(items[1].name, "name2");
  10445. EXPECT_EQ(items[1].content, "Testing456");
  10446. EXPECT_EQ(items[1].filename, "");
  10447. EXPECT_EQ(items[1].content_type, "");
  10448. });
  10449. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10450. const ContentReader &content_reader) {
  10451. ASSERT_TRUE(req.is_multipart_form_data());
  10452. std::vector<FormData> items;
  10453. content_reader(
  10454. [&](const FormData &file) {
  10455. items.push_back(file);
  10456. return true;
  10457. },
  10458. [&](const char *data, size_t data_length) {
  10459. items.back().content.append(data, data_length);
  10460. return true;
  10461. });
  10462. ASSERT_TRUE(items.size() == 2);
  10463. EXPECT_EQ(items[0].name, "name3");
  10464. EXPECT_EQ(items[0].content, rand1);
  10465. EXPECT_EQ(items[0].filename, "filename3");
  10466. EXPECT_EQ(items[0].content_type, "");
  10467. EXPECT_EQ(items[1].name, "name4");
  10468. EXPECT_EQ(items[1].content, rand2);
  10469. EXPECT_EQ(items[1].filename, "filename4");
  10470. EXPECT_EQ(items[1].content_type, "");
  10471. });
  10472. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10473. const ContentReader &content_reader) {
  10474. ASSERT_TRUE(req.is_multipart_form_data());
  10475. std::vector<FormData> items;
  10476. content_reader(
  10477. [&](const FormData &file) {
  10478. items.push_back(file);
  10479. return true;
  10480. },
  10481. [&](const char *data, size_t data_length) {
  10482. items.back().content.append(data, data_length);
  10483. return true;
  10484. });
  10485. ASSERT_TRUE(items.size() == 4);
  10486. EXPECT_EQ(std::string(items[0].name), "name1");
  10487. EXPECT_EQ(items[0].content, "Testing123");
  10488. EXPECT_EQ(items[0].filename, "filename1");
  10489. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10490. EXPECT_EQ(items[1].name, "name2");
  10491. EXPECT_EQ(items[1].content, "Testing456");
  10492. EXPECT_EQ(items[1].filename, "");
  10493. EXPECT_EQ(items[1].content_type, "");
  10494. EXPECT_EQ(items[2].name, "name3");
  10495. EXPECT_EQ(items[2].content, rand1);
  10496. EXPECT_EQ(items[2].filename, "filename3");
  10497. EXPECT_EQ(items[2].content_type, "");
  10498. EXPECT_EQ(items[3].name, "name4");
  10499. EXPECT_EQ(items[3].content, rand2);
  10500. EXPECT_EQ(items[3].filename, "filename4");
  10501. EXPECT_EQ(items[3].content_type, "");
  10502. });
  10503. auto port = svr.bind_to_any_port("localhost");
  10504. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10505. auto se = detail::scope_exit([&] {
  10506. svr.stop();
  10507. t.join();
  10508. ASSERT_FALSE(svr.is_running());
  10509. });
  10510. svr.wait_until_ready();
  10511. {
  10512. SSLClient cli("localhost", port);
  10513. cli.enable_server_certificate_verification(false);
  10514. UploadFormDataItems items{
  10515. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10516. {"name2", "Testing456", "", ""}, // not a file
  10517. };
  10518. {
  10519. auto res = cli.Post("/post-none", {}, {}, {});
  10520. ASSERT_TRUE(res);
  10521. ASSERT_EQ(StatusCode::OK_200, res->status);
  10522. }
  10523. FormDataProviderItems providers;
  10524. {
  10525. auto res =
  10526. cli.Post("/post-items", {}, items, providers); // empty providers
  10527. ASSERT_TRUE(res);
  10528. ASSERT_EQ(StatusCode::OK_200, res->status);
  10529. }
  10530. providers.push_back({"name3",
  10531. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10532. // test the offset is given correctly at each step
  10533. if (!offset)
  10534. sink.os.write(rand1.data(), 30);
  10535. else if (offset == 30)
  10536. sink.os.write(rand1.data() + 30, 300);
  10537. else if (offset == 330)
  10538. sink.os.write(rand1.data() + 330, 670);
  10539. else if (offset == rand1.size())
  10540. sink.done();
  10541. return true;
  10542. },
  10543. "filename3",
  10544. {}});
  10545. providers.push_back({"name4",
  10546. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10547. // test the offset is given correctly at each step
  10548. if (!offset)
  10549. sink.os.write(rand2.data(), 2000);
  10550. else if (offset == 2000)
  10551. sink.os.write(rand2.data() + 2000, 1);
  10552. else if (offset == 2001)
  10553. sink.os.write(rand2.data() + 2001, 999);
  10554. else if (offset == rand2.size())
  10555. sink.done();
  10556. return true;
  10557. },
  10558. "filename4",
  10559. {}});
  10560. {
  10561. auto res = cli.Post("/post-providers", {}, {}, providers);
  10562. ASSERT_TRUE(res);
  10563. ASSERT_EQ(StatusCode::OK_200, res->status);
  10564. }
  10565. {
  10566. auto res = cli.Post("/post-both", {}, items, providers);
  10567. ASSERT_TRUE(res);
  10568. ASSERT_EQ(StatusCode::OK_200, res->status);
  10569. }
  10570. }
  10571. }
  10572. TEST(MultipartFormDataTest, BadHeader) {
  10573. Server svr;
  10574. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10575. res.set_content("ok", "text/plain");
  10576. });
  10577. thread t = thread([&] { svr.listen(HOST, PORT); });
  10578. auto se = detail::scope_exit([&] {
  10579. svr.stop();
  10580. t.join();
  10581. ASSERT_FALSE(svr.is_running());
  10582. });
  10583. svr.wait_until_ready();
  10584. const std::string body =
  10585. "This is the preamble. It is to be ignored, though it\r\n"
  10586. "is a handy place for composition agents to include an\r\n"
  10587. "explanatory note to non-MIME conformant readers.\r\n"
  10588. "\r\n"
  10589. "\r\n"
  10590. "--simple boundary\r\n"
  10591. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10592. ": BAD...\r\n"
  10593. "\r\n"
  10594. "value1\r\n"
  10595. "--simple boundary\r\n"
  10596. "Content-Disposition: form-data; name=\"field2\"; "
  10597. "filename=\"example.txt\"\r\n"
  10598. "\r\n"
  10599. "value2\r\n"
  10600. "--simple boundary--\r\n"
  10601. "This is the epilogue. It is also to be ignored.\r\n";
  10602. std::string content_type =
  10603. R"(multipart/form-data; boundary="simple boundary")";
  10604. Client cli(HOST, PORT);
  10605. auto res = cli.Post("/post", body, content_type.c_str());
  10606. ASSERT_TRUE(res);
  10607. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10608. }
  10609. TEST(MultipartFormDataTest, WithPreamble) {
  10610. Server svr;
  10611. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10612. res.set_content("ok", "text/plain");
  10613. });
  10614. thread t = thread([&] { svr.listen(HOST, PORT); });
  10615. auto se = detail::scope_exit([&] {
  10616. svr.stop();
  10617. t.join();
  10618. ASSERT_FALSE(svr.is_running());
  10619. });
  10620. svr.wait_until_ready();
  10621. const std::string body =
  10622. "This is the preamble. It is to be ignored, though it\r\n"
  10623. "is a handy place for composition agents to include an\r\n"
  10624. "explanatory note to non-MIME conformant readers.\r\n"
  10625. "\r\n"
  10626. "\r\n"
  10627. "--simple boundary\r\n"
  10628. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10629. "\r\n"
  10630. "value1\r\n"
  10631. "--simple boundary\r\n"
  10632. "Content-Disposition: form-data; name=\"field2\"; "
  10633. "filename=\"example.txt\"\r\n"
  10634. "\r\n"
  10635. "value2\r\n"
  10636. "--simple boundary--\r\n"
  10637. "This is the epilogue. It is also to be ignored.\r\n";
  10638. std::string content_type =
  10639. R"(multipart/form-data; boundary="simple boundary")";
  10640. Client cli(HOST, PORT);
  10641. auto res = cli.Post("/post", body, content_type.c_str());
  10642. ASSERT_TRUE(res);
  10643. EXPECT_EQ(StatusCode::OK_200, res->status);
  10644. }
  10645. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10647. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10648. const ContentReader &content_reader) {
  10649. if (req.is_multipart_form_data()) {
  10650. std::vector<FormData> items;
  10651. content_reader(
  10652. [&](const FormData &file) {
  10653. items.push_back(file);
  10654. return true;
  10655. },
  10656. [&](const char *data, size_t data_length) {
  10657. items.back().content.append(data, data_length);
  10658. return true;
  10659. });
  10660. EXPECT_TRUE(std::string(items[0].name) == "document");
  10661. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10662. EXPECT_TRUE(items[0].filename == "2MB_data");
  10663. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10664. EXPECT_TRUE(items[1].name == "hello");
  10665. EXPECT_TRUE(items[1].content == "world");
  10666. EXPECT_TRUE(items[1].filename == "");
  10667. EXPECT_TRUE(items[1].content_type == "");
  10668. } else {
  10669. std::string body;
  10670. content_reader([&](const char *data, size_t data_length) {
  10671. body.append(data, data_length);
  10672. return true;
  10673. });
  10674. }
  10675. });
  10676. auto port = svr.bind_to_any_port("localhost");
  10677. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. t.join();
  10681. ASSERT_FALSE(svr.is_running());
  10682. });
  10683. svr.wait_until_ready();
  10684. {
  10685. std::string data(1024 * 1024 * 2, '.');
  10686. std::stringstream buffer;
  10687. buffer << data;
  10688. SSLClient cli("localhost", port);
  10689. cli.enable_server_certificate_verification(false);
  10690. UploadFormDataItems items{
  10691. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10692. {"hello", "world", "", ""},
  10693. };
  10694. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10695. ASSERT_TRUE(res);
  10696. ASSERT_EQ(StatusCode::OK_200, res->status);
  10697. }
  10698. }
  10699. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10700. std::string data(1024 * 1024 * 2, '&');
  10701. std::stringstream buffer;
  10702. buffer << data;
  10703. Client cli("https://localhost:8080");
  10704. UploadFormDataItems items{
  10705. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10706. {"hello", "world", "", ""},
  10707. };
  10708. for (const char &c : " \t\r\n") {
  10709. auto res =
  10710. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10711. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10712. ASSERT_FALSE(res);
  10713. }
  10714. }
  10715. TEST(MultipartFormDataTest, PutFormData) {
  10716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10717. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10718. const ContentReader &content_reader) {
  10719. if (req.is_multipart_form_data()) {
  10720. std::vector<FormData> items;
  10721. content_reader(
  10722. [&](const FormData &file) {
  10723. items.push_back(file);
  10724. return true;
  10725. },
  10726. [&](const char *data, size_t data_length) {
  10727. items.back().content.append(data, data_length);
  10728. return true;
  10729. });
  10730. EXPECT_TRUE(std::string(items[0].name) == "document");
  10731. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10732. EXPECT_TRUE(items[0].filename == "2MB_data");
  10733. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10734. EXPECT_TRUE(items[1].name == "hello");
  10735. EXPECT_TRUE(items[1].content == "world");
  10736. EXPECT_TRUE(items[1].filename == "");
  10737. EXPECT_TRUE(items[1].content_type == "");
  10738. } else {
  10739. std::string body;
  10740. content_reader([&](const char *data, size_t data_length) {
  10741. body.append(data, data_length);
  10742. return true;
  10743. });
  10744. }
  10745. });
  10746. auto port = svr.bind_to_any_port("localhost");
  10747. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10748. auto se = detail::scope_exit([&] {
  10749. svr.stop();
  10750. t.join();
  10751. ASSERT_FALSE(svr.is_running());
  10752. });
  10753. svr.wait_until_ready();
  10754. {
  10755. std::string data(1024 * 1024 * 2, '&');
  10756. std::stringstream buffer;
  10757. buffer << data;
  10758. SSLClient cli("localhost", port);
  10759. cli.enable_server_certificate_verification(false);
  10760. UploadFormDataItems items{
  10761. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10762. {"hello", "world", "", ""},
  10763. };
  10764. auto res = cli.Put("/put", items);
  10765. ASSERT_TRUE(res);
  10766. ASSERT_EQ(StatusCode::OK_200, res->status);
  10767. }
  10768. }
  10769. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10771. svr.Put("/put_customboundary",
  10772. [&](const Request &req, const Response & /*res*/,
  10773. const ContentReader &content_reader) {
  10774. if (req.is_multipart_form_data()) {
  10775. std::vector<FormData> items;
  10776. content_reader(
  10777. [&](const FormData &file) {
  10778. items.push_back(file);
  10779. return true;
  10780. },
  10781. [&](const char *data, size_t data_length) {
  10782. items.back().content.append(data, data_length);
  10783. return true;
  10784. });
  10785. EXPECT_TRUE(std::string(items[0].name) == "document");
  10786. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10787. EXPECT_TRUE(items[0].filename == "2MB_data");
  10788. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10789. EXPECT_TRUE(items[1].name == "hello");
  10790. EXPECT_TRUE(items[1].content == "world");
  10791. EXPECT_TRUE(items[1].filename == "");
  10792. EXPECT_TRUE(items[1].content_type == "");
  10793. } else {
  10794. std::string body;
  10795. content_reader([&](const char *data, size_t data_length) {
  10796. body.append(data, data_length);
  10797. return true;
  10798. });
  10799. }
  10800. });
  10801. auto port = svr.bind_to_any_port("localhost");
  10802. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10803. auto se = detail::scope_exit([&] {
  10804. svr.stop();
  10805. t.join();
  10806. ASSERT_FALSE(svr.is_running());
  10807. });
  10808. svr.wait_until_ready();
  10809. {
  10810. std::string data(1024 * 1024 * 2, '&');
  10811. std::stringstream buffer;
  10812. buffer << data;
  10813. SSLClient cli("localhost", port);
  10814. cli.enable_server_certificate_verification(false);
  10815. UploadFormDataItems items{
  10816. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10817. {"hello", "world", "", ""},
  10818. };
  10819. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10820. ASSERT_TRUE(res);
  10821. ASSERT_EQ(StatusCode::OK_200, res->status);
  10822. }
  10823. }
  10824. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10825. std::string data(1024 * 1024 * 2, '&');
  10826. std::stringstream buffer;
  10827. buffer << data;
  10828. Client cli("https://localhost:8080");
  10829. cli.enable_server_certificate_verification(false);
  10830. UploadFormDataItems items{
  10831. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10832. {"hello", "world", "", ""},
  10833. };
  10834. for (const char &c : " \t\r\n") {
  10835. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10836. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10837. ASSERT_FALSE(res);
  10838. }
  10839. }
  10840. TEST(MultipartFormDataTest, AlternateFilename) {
  10841. auto handled = false;
  10842. Server svr;
  10843. svr.Post("/test", [&](const Request &req, Response &res) {
  10844. ASSERT_EQ(2u, req.form.files.size());
  10845. ASSERT_EQ(1u, req.form.fields.size());
  10846. // Test files
  10847. const auto &file1 = req.form.get_file("file1");
  10848. ASSERT_EQ("file1", file1.name);
  10849. ASSERT_EQ("A.txt", file1.filename);
  10850. ASSERT_EQ("text/plain", file1.content_type);
  10851. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10852. const auto &file2 = req.form.get_file("file2");
  10853. ASSERT_EQ("file2", file2.name);
  10854. ASSERT_EQ("a.html", file2.filename);
  10855. ASSERT_EQ("text/html", file2.content_type);
  10856. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10857. file2.content);
  10858. // Test text field
  10859. const auto &text = req.form.get_field("text");
  10860. ASSERT_EQ("text default", text);
  10861. res.set_content("ok", "text/plain");
  10862. handled = true;
  10863. });
  10864. thread t = thread([&] { svr.listen(HOST, PORT); });
  10865. auto se = detail::scope_exit([&] {
  10866. svr.stop();
  10867. t.join();
  10868. ASSERT_FALSE(svr.is_running());
  10869. ASSERT_TRUE(handled);
  10870. });
  10871. svr.wait_until_ready();
  10872. auto req = "POST /test HTTP/1.1\r\n"
  10873. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10874. "Content-Length: 399\r\n"
  10875. "\r\n"
  10876. "----------\r\n"
  10877. "Content-Disposition: form-data; name=\"text\"\r\n"
  10878. "\r\n"
  10879. "text default\r\n"
  10880. "----------\r\n"
  10881. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10882. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10883. "Content-Type: text/plain\r\n"
  10884. "\r\n"
  10885. "Content of a.txt.\r\n"
  10886. "\r\n"
  10887. "----------\r\n"
  10888. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10889. "\"a.html\"\r\n"
  10890. "Content-Type: text/html\r\n"
  10891. "\r\n"
  10892. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10893. "\r\n"
  10894. "------------\r\n";
  10895. ASSERT_TRUE(send_request(1, req));
  10896. }
  10897. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10898. auto handled = false;
  10899. Server svr;
  10900. svr.Post("/test", [&](const Request &req, Response &res) {
  10901. // Case-insensitive "utf-8''" prefix with a long value
  10902. const auto &file = req.form.get_file("file1");
  10903. ASSERT_EQ("file1", file.name);
  10904. // 8000 chars exercises both the Content-Disposition parser and the
  10905. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10906. // Prior to the fix, std::regex_match on this header would cause O(N)
  10907. // stack recursion in libstdc++, leading to SIGSEGV.
  10908. std::string expected_filename(8000, 'A');
  10909. ASSERT_EQ(expected_filename, file.filename);
  10910. res.set_content("ok", "text/plain");
  10911. handled = true;
  10912. });
  10913. thread t = thread([&] { svr.listen(HOST, PORT); });
  10914. auto se = detail::scope_exit([&] {
  10915. svr.stop();
  10916. t.join();
  10917. ASSERT_FALSE(svr.is_running());
  10918. ASSERT_TRUE(handled);
  10919. });
  10920. svr.wait_until_ready();
  10921. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10922. // Regression test for GHSA-qq6v-r583-3h69
  10923. std::string long_filename(8000, 'A');
  10924. std::string body = "----------\r\n"
  10925. "Content-Disposition: form-data; name=\"file1\"; "
  10926. "filename*=\"Utf-8''" +
  10927. long_filename +
  10928. "\"\r\n"
  10929. "\r\n"
  10930. "hello\r\n"
  10931. "------------\r\n";
  10932. auto req = "POST /test HTTP/1.1\r\n"
  10933. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10934. "Content-Length: " +
  10935. std::to_string(body.size()) + "\r\n\r\n" + body;
  10936. ASSERT_TRUE(send_request(1, req));
  10937. }
  10938. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10939. auto handled = false;
  10940. Server svr;
  10941. svr.Post("/test", [&](const Request &req, Response &) {
  10942. ASSERT_EQ(2u, req.form.fields.size());
  10943. const auto &text1 = req.form.get_field("text1");
  10944. ASSERT_EQ("text1", text1);
  10945. const auto &text2 = req.form.get_field("text2");
  10946. ASSERT_EQ("text2", text2);
  10947. handled = true;
  10948. });
  10949. thread t = thread([&] { svr.listen(HOST, PORT); });
  10950. auto se = detail::scope_exit([&] {
  10951. svr.stop();
  10952. t.join();
  10953. ASSERT_FALSE(svr.is_running());
  10954. ASSERT_TRUE(handled);
  10955. });
  10956. svr.wait_until_ready();
  10957. auto req = "POST /test HTTP/1.1\r\n"
  10958. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10959. "Content-Length: 146\r\n"
  10960. "\r\n----------\r\n"
  10961. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10962. "\r\n"
  10963. "text1"
  10964. "\r\n----------\r\n"
  10965. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10966. "\r\n"
  10967. "text2"
  10968. "\r\n------------";
  10969. std::string response;
  10970. ASSERT_TRUE(send_request(1, req, &response));
  10971. ASSERT_EQ("200", response.substr(9, 3));
  10972. }
  10973. TEST(MultipartFormDataTest, ContentLength) {
  10974. auto handled = false;
  10975. Server svr;
  10976. svr.Post("/test", [&](const Request &req, Response &) {
  10977. ASSERT_EQ(2u, req.form.fields.size());
  10978. const auto &text1 = req.form.get_field("text1");
  10979. ASSERT_EQ("text1", text1);
  10980. const auto &text2 = req.form.get_field("text2");
  10981. ASSERT_EQ("text2", text2);
  10982. handled = true;
  10983. });
  10984. thread t = thread([&] { svr.listen(HOST, PORT); });
  10985. auto se = detail::scope_exit([&] {
  10986. svr.stop();
  10987. t.join();
  10988. ASSERT_FALSE(svr.is_running());
  10989. ASSERT_TRUE(handled);
  10990. });
  10991. svr.wait_until_ready();
  10992. auto req = "POST /test HTTP/1.1\r\n"
  10993. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10994. "Content-Length: 167\r\n"
  10995. "\r\n----------\r\n"
  10996. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10997. "Content-Length: 5\r\n"
  10998. "\r\n"
  10999. "text1"
  11000. "\r\n----------\r\n"
  11001. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11002. "\r\n"
  11003. "text2"
  11004. "\r\n------------\r\n";
  11005. std::string response;
  11006. ASSERT_TRUE(send_request(1, req, &response));
  11007. ASSERT_EQ("200", response.substr(9, 3));
  11008. }
  11009. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11010. auto handled = false;
  11011. Server svr;
  11012. svr.Post("/test", [&](const Request &req, Response &) {
  11013. ASSERT_EQ(2u, req.form.fields.size());
  11014. const auto &text1 = req.form.get_field("text1");
  11015. ASSERT_EQ("text1", text1);
  11016. // TODO: Add header access for text fields if needed
  11017. const auto &text2 = req.form.get_field("text2");
  11018. ASSERT_EQ("text2", text2);
  11019. // TODO: Header access for text fields needs to be implemented
  11020. // auto &headers = it->second.headers;
  11021. // ASSERT_EQ(3U, headers.size());
  11022. // auto custom_header = headers.find("x-whatever");
  11023. // ASSERT_TRUE(custom_header != headers.end());
  11024. // ASSERT_NE("customvalue", custom_header->second);
  11025. // ASSERT_EQ("CustomValue", custom_header->second);
  11026. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11027. handled = true;
  11028. });
  11029. thread t = thread([&] { svr.listen(HOST, PORT); });
  11030. auto se = detail::scope_exit([&] {
  11031. svr.stop();
  11032. t.join();
  11033. ASSERT_FALSE(svr.is_running());
  11034. ASSERT_TRUE(handled);
  11035. });
  11036. svr.wait_until_ready();
  11037. auto req = "POST /test HTTP/1.1\r\n"
  11038. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11039. "Content-Length: 232\r\n"
  11040. "\r\n----------\r\n"
  11041. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11042. "Content-Length: 5\r\n"
  11043. "X-Test: 1\r\n"
  11044. "\r\n"
  11045. "text1"
  11046. "\r\n----------\r\n"
  11047. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11048. "Content-Type: text/plain\r\n"
  11049. "X-Whatever: CustomValue\r\n"
  11050. "\r\n"
  11051. "text2"
  11052. "\r\n------------\r\n"
  11053. "That should be disregarded. Not even read";
  11054. std::string response;
  11055. ASSERT_TRUE(send_request(1, req, &response));
  11056. ASSERT_EQ("200", response.substr(9, 3));
  11057. }
  11058. TEST(MultipartFormDataTest, LargeHeader) {
  11059. auto handled = false;
  11060. Server svr;
  11061. svr.Post("/test", [&](const Request &req, Response &) {
  11062. ASSERT_EQ(1u, req.form.fields.size());
  11063. const auto &text = req.form.get_field("name1");
  11064. ASSERT_EQ("text1", text);
  11065. handled = true;
  11066. });
  11067. thread t = thread([&] { svr.listen(HOST, PORT); });
  11068. auto se = detail::scope_exit([&] {
  11069. svr.stop();
  11070. t.join();
  11071. ASSERT_FALSE(svr.is_running());
  11072. ASSERT_TRUE(handled);
  11073. });
  11074. svr.wait_until_ready();
  11075. auto boundary = std::string("cpp-httplib-multipart-data");
  11076. std::string content = "--" + boundary +
  11077. "\r\n"
  11078. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11079. "\r\n"
  11080. "text1\r\n"
  11081. "--" +
  11082. boundary + "--\r\n";
  11083. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11084. "Content-Type: multipart/form-data;boundary=" +
  11085. boundary +
  11086. "\r\n"
  11087. "Content-Length: " +
  11088. std::to_string(content.size()) +
  11089. "\r\n"
  11090. "Dummy-Header: ";
  11091. std::string header_suffix = "\r\n"
  11092. "\r\n";
  11093. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11094. size_t header_dummy_size =
  11095. read_buff_size -
  11096. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11097. auto header_dummy = std::string(header_dummy_size, '@');
  11098. auto req = header_prefix + header_dummy + header_suffix + content;
  11099. std::string response;
  11100. ASSERT_TRUE(send_request(1, req, &response));
  11101. ASSERT_EQ("200", response.substr(9, 3));
  11102. }
  11103. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11104. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11105. // (not chunked Transfer-Encoding) after the streaming refactor.
  11106. auto handled = false;
  11107. Server svr;
  11108. svr.Post("/upload", [&](const Request &req, Response &res) {
  11109. auto cl_it = req.headers.find("Content-Length");
  11110. EXPECT_TRUE(cl_it != req.headers.end());
  11111. auto te_it = req.headers.find("Transfer-Encoding");
  11112. EXPECT_TRUE(te_it == req.headers.end());
  11113. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11114. res.set_content("ok", "text/plain");
  11115. handled = true;
  11116. });
  11117. auto port = svr.bind_to_any_port(HOST);
  11118. auto t = thread([&] { svr.listen_after_bind(); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. ASSERT_TRUE(handled);
  11124. });
  11125. svr.wait_until_ready();
  11126. UploadFormDataItems items = {
  11127. {"field1", "hello", "", "text/plain"},
  11128. {"file1", "world", "test.txt", "application/octet-stream"},
  11129. };
  11130. Client cli(HOST, port);
  11131. auto res = cli.Post("/upload", {}, items);
  11132. ASSERT_TRUE(res);
  11133. EXPECT_EQ(StatusCode::OK_200, res->status);
  11134. }
  11135. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11136. // Verify that make_multipart_content_provider coalesces many small segments
  11137. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11138. constexpr size_t kItemCount = 1000;
  11139. UploadFormDataItems items;
  11140. items.reserve(kItemCount);
  11141. for (size_t i = 0; i < kItemCount; i++) {
  11142. items.push_back(
  11143. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11144. }
  11145. const std::string boundary = "----test-boundary";
  11146. auto content_length = detail::get_multipart_content_length(items, boundary);
  11147. auto provider = detail::make_multipart_content_provider(items, boundary);
  11148. // Drive the provider the same way write_content_with_progress does
  11149. size_t write_count = 0;
  11150. size_t total_bytes = 0;
  11151. DataSink sink;
  11152. size_t offset = 0;
  11153. sink.write = [&](const char *d, size_t l) -> bool {
  11154. (void)d;
  11155. write_count++;
  11156. total_bytes += l;
  11157. offset += l;
  11158. return true;
  11159. };
  11160. sink.is_writable = []() -> bool { return true; };
  11161. while (offset < content_length) {
  11162. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11163. }
  11164. EXPECT_EQ(content_length, total_bytes);
  11165. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11166. // With buffering into 64KB blocks, write_count should be much smaller.
  11167. auto segment_count = 3 * kItemCount + 1;
  11168. EXPECT_LT(write_count, segment_count / 10);
  11169. }
  11170. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11171. // Integration test: send many UploadFormDataItems and verify the server
  11172. // receives all of them correctly (#2410).
  11173. constexpr size_t kItemCount = 500;
  11174. auto handled = false;
  11175. Server svr;
  11176. svr.Post("/upload", [&](const Request &req, Response &res) {
  11177. EXPECT_EQ(kItemCount, req.form.fields.size());
  11178. for (size_t i = 0; i < kItemCount; i++) {
  11179. auto key = "field" + std::to_string(i);
  11180. auto val = "value" + std::to_string(i);
  11181. auto it = req.form.fields.find(key);
  11182. if (it != req.form.fields.end()) {
  11183. EXPECT_EQ(val, it->second.content);
  11184. } else {
  11185. ADD_FAILURE() << "Missing field: " << key;
  11186. }
  11187. }
  11188. res.set_content("ok", "text/plain");
  11189. handled = true;
  11190. });
  11191. auto port = svr.bind_to_any_port(HOST);
  11192. auto t = thread([&] { svr.listen_after_bind(); });
  11193. auto se = detail::scope_exit([&] {
  11194. svr.stop();
  11195. t.join();
  11196. ASSERT_FALSE(svr.is_running());
  11197. ASSERT_TRUE(handled);
  11198. });
  11199. svr.wait_until_ready();
  11200. UploadFormDataItems items;
  11201. items.reserve(kItemCount);
  11202. for (size_t i = 0; i < kItemCount; i++) {
  11203. items.push_back(
  11204. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11205. }
  11206. Client cli(HOST, port);
  11207. auto res = cli.Post("/upload", items);
  11208. ASSERT_TRUE(res);
  11209. EXPECT_EQ(StatusCode::OK_200, res->status);
  11210. }
  11211. TEST(MultipartFormDataTest, MakeFileProvider) {
  11212. // Verify make_file_provider sends a file's contents correctly.
  11213. const std::string file_content(4096, 'Z');
  11214. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11215. {
  11216. std::ofstream ofs(tmp_path, std::ios::binary);
  11217. ofs.write(file_content.data(),
  11218. static_cast<std::streamsize>(file_content.size()));
  11219. }
  11220. auto handled = false;
  11221. Server svr;
  11222. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11223. const ContentReader &content_reader) {
  11224. ASSERT_TRUE(req.is_multipart_form_data());
  11225. std::vector<FormData> items;
  11226. content_reader(
  11227. [&](const FormData &file) {
  11228. items.push_back(file);
  11229. return true;
  11230. },
  11231. [&](const char *data, size_t data_length) {
  11232. items.back().content.append(data, data_length);
  11233. return true;
  11234. });
  11235. ASSERT_EQ(1u, items.size());
  11236. EXPECT_EQ("myfile", items[0].name);
  11237. EXPECT_EQ("data.bin", items[0].filename);
  11238. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11239. EXPECT_EQ(file_content, items[0].content);
  11240. handled = true;
  11241. });
  11242. auto port = svr.bind_to_any_port(HOST);
  11243. auto t = thread([&] { svr.listen_after_bind(); });
  11244. auto se = detail::scope_exit([&] {
  11245. svr.stop();
  11246. t.join();
  11247. ASSERT_FALSE(svr.is_running());
  11248. ASSERT_TRUE(handled);
  11249. std::remove(tmp_path.c_str());
  11250. });
  11251. svr.wait_until_ready();
  11252. FormDataProviderItems providers;
  11253. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11254. "application/octet-stream"));
  11255. Client cli(HOST, port);
  11256. auto res = cli.Post("/upload", {}, {}, providers);
  11257. ASSERT_TRUE(res);
  11258. EXPECT_EQ(StatusCode::OK_200, res->status);
  11259. }
  11260. TEST(MakeFileBodyTest, Basic) {
  11261. const std::string file_content(4096, 'Z');
  11262. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11263. {
  11264. std::ofstream ofs(tmp_path, std::ios::binary);
  11265. ofs.write(file_content.data(),
  11266. static_cast<std::streamsize>(file_content.size()));
  11267. }
  11268. auto handled = false;
  11269. Server svr;
  11270. svr.Post("/upload", [&](const Request &req, Response &res) {
  11271. EXPECT_EQ(file_content, req.body);
  11272. handled = true;
  11273. res.status = StatusCode::OK_200;
  11274. });
  11275. auto port = svr.bind_to_any_port(HOST);
  11276. auto t = thread([&] { svr.listen_after_bind(); });
  11277. auto se = detail::scope_exit([&] {
  11278. svr.stop();
  11279. t.join();
  11280. ASSERT_FALSE(svr.is_running());
  11281. ASSERT_TRUE(handled);
  11282. std::remove(tmp_path.c_str());
  11283. });
  11284. svr.wait_until_ready();
  11285. auto fb = make_file_body(tmp_path);
  11286. ASSERT_GT(fb.first, 0u);
  11287. Client cli(HOST, port);
  11288. auto res =
  11289. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11290. ASSERT_TRUE(res);
  11291. EXPECT_EQ(StatusCode::OK_200, res->status);
  11292. }
  11293. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11294. static constexpr unsigned int number_of_tasks{1000000};
  11295. std::atomic_uint count{0};
  11296. std::unique_ptr<TaskQueue> task_queue{
  11297. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11298. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11299. auto queued = task_queue->enqueue(
  11300. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11301. EXPECT_TRUE(queued);
  11302. }
  11303. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11304. task_queue->shutdown();
  11305. #else
  11306. EXPECT_NO_THROW(task_queue->shutdown());
  11307. #endif
  11308. EXPECT_EQ(number_of_tasks, count.load());
  11309. }
  11310. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11311. static constexpr unsigned int number_of_tasks{1000000};
  11312. static constexpr unsigned int qlimit{2};
  11313. unsigned int queued_count{0};
  11314. std::atomic_uint count{0};
  11315. std::unique_ptr<TaskQueue> task_queue{
  11316. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11317. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11318. if (task_queue->enqueue(
  11319. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11320. queued_count++;
  11321. }
  11322. }
  11323. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11324. task_queue->shutdown();
  11325. #else
  11326. EXPECT_NO_THROW(task_queue->shutdown());
  11327. #endif
  11328. EXPECT_EQ(queued_count, count.load());
  11329. EXPECT_TRUE(queued_count <= number_of_tasks);
  11330. EXPECT_TRUE(queued_count >= qlimit);
  11331. }
  11332. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11333. // Use a short idle timeout so a dynamic thread spawns, times out and
  11334. // exits during the test, and the pool keeps working afterwards.
  11335. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11336. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11337. /*idle_timeout_sec=*/1}};
  11338. std::atomic_uint count{0};
  11339. std::condition_variable cv;
  11340. std::mutex mtx;
  11341. bool release = false;
  11342. // Block the base thread so the second task spawns a dynamic thread.
  11343. EXPECT_TRUE(task_queue->enqueue([&] {
  11344. std::unique_lock<std::mutex> lock(mtx);
  11345. while (!release) {
  11346. cv.wait(lock);
  11347. }
  11348. count++;
  11349. }));
  11350. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11351. // Let the dynamic thread finish its task and exceed the idle timeout.
  11352. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11353. {
  11354. std::unique_lock<std::mutex> lock(mtx);
  11355. release = true;
  11356. }
  11357. cv.notify_all();
  11358. // The pool must still accept and run tasks after the dynamic thread exited.
  11359. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11360. task_queue->shutdown();
  11361. EXPECT_EQ(3u, count.load());
  11362. }
  11363. TEST(TaskQueueTest, MaxQueuedRequests) {
  11364. static constexpr unsigned int qlimit{3};
  11365. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11366. std::condition_variable sem_cv;
  11367. std::mutex sem_mtx;
  11368. int credits = 0;
  11369. bool queued;
  11370. /* Fill up the queue with tasks that will block until we give them credits to
  11371. * complete. */
  11372. for (unsigned int n = 0; n <= qlimit;) {
  11373. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11374. std::unique_lock<std::mutex> lock(sem_mtx);
  11375. while (credits <= 0) {
  11376. sem_cv.wait(lock);
  11377. }
  11378. /* Consume the credit and signal the test code if they are all gone. */
  11379. if (--credits == 0) { sem_cv.notify_one(); }
  11380. });
  11381. if (n < qlimit) {
  11382. /* The first qlimit enqueues must succeed. */
  11383. EXPECT_TRUE(queued);
  11384. } else {
  11385. /* The last one will succeed only when the worker thread
  11386. * starts and dequeues the first blocking task. Although
  11387. * not necessary for the correctness of this test, we sleep for
  11388. * a short while to avoid busy waiting. */
  11389. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11390. }
  11391. if (queued) { n++; }
  11392. }
  11393. /* Further enqueues must fail since the queue is full. */
  11394. for (auto i = 0; i < 4; i++) {
  11395. queued = task_queue->enqueue([] {});
  11396. EXPECT_FALSE(queued);
  11397. }
  11398. /* Give the credits to allow the previous tasks to complete. */
  11399. {
  11400. std::unique_lock<std::mutex> lock(sem_mtx);
  11401. credits += qlimit + 1;
  11402. }
  11403. sem_cv.notify_all();
  11404. /* Wait for all the credits to be consumed. */
  11405. {
  11406. std::unique_lock<std::mutex> lock(sem_mtx);
  11407. while (credits > 0) {
  11408. sem_cv.wait(lock);
  11409. }
  11410. }
  11411. /* Check that we are able again to enqueue at least qlimit tasks. */
  11412. for (unsigned int i = 0; i < qlimit; i++) {
  11413. queued = task_queue->enqueue([] {});
  11414. EXPECT_TRUE(queued);
  11415. }
  11416. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11417. task_queue->shutdown();
  11418. #else
  11419. EXPECT_NO_THROW(task_queue->shutdown());
  11420. #endif
  11421. }
  11422. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11423. Server svr;
  11424. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11425. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11426. });
  11427. svr.Get("/hello", [](const Request &req, Response &res) {
  11428. res.set_content(req.get_param_value("key"), "text/plain");
  11429. });
  11430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11431. auto se = detail::scope_exit([&] {
  11432. svr.stop();
  11433. thread.join();
  11434. ASSERT_FALSE(svr.is_running());
  11435. });
  11436. svr.wait_until_ready();
  11437. {
  11438. Client cli(HOST, PORT);
  11439. cli.set_follow_location(true);
  11440. auto res = cli.Get("/");
  11441. ASSERT_TRUE(res);
  11442. EXPECT_EQ(StatusCode::OK_200, res->status);
  11443. EXPECT_EQ("val&key2=val2", res->body);
  11444. }
  11445. }
  11446. #endif
  11447. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11448. Server svr;
  11449. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11450. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11451. });
  11452. svr.Get("/hello", [](const Request &req, Response &res) {
  11453. res.set_content(req.get_param_value("key"), "text/plain");
  11454. });
  11455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11456. auto se = detail::scope_exit([&] {
  11457. svr.stop();
  11458. thread.join();
  11459. ASSERT_FALSE(svr.is_running());
  11460. });
  11461. svr.wait_until_ready();
  11462. {
  11463. Client cli(HOST, PORT);
  11464. cli.set_follow_location(true);
  11465. auto res = cli.Get("/");
  11466. ASSERT_TRUE(res);
  11467. EXPECT_EQ(StatusCode::OK_200, res->status);
  11468. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11469. }
  11470. }
  11471. TEST(RedirectTest, RedirectWithPlusInPath) {
  11472. Server svr;
  11473. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11474. res.set_redirect("/a+b");
  11475. });
  11476. // Route pattern uses regex; escape + as \\+
  11477. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11478. res.set_content(req.path, "text/plain");
  11479. });
  11480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11481. auto se = detail::scope_exit([&] {
  11482. svr.stop();
  11483. thread.join();
  11484. ASSERT_FALSE(svr.is_running());
  11485. });
  11486. svr.wait_until_ready();
  11487. {
  11488. Client cli(HOST, PORT);
  11489. cli.set_follow_location(true);
  11490. auto res = cli.Get("/");
  11491. ASSERT_TRUE(res);
  11492. EXPECT_EQ(StatusCode::OK_200, res->status);
  11493. EXPECT_EQ("/a+b", res->body);
  11494. }
  11495. }
  11496. #ifdef CPPHTTPLIB_SSL_ENABLED
  11497. TEST(RedirectTest, Issue2185_Online) {
  11498. SSLClient client("github.com");
  11499. client.set_follow_location(true);
  11500. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11501. "Coollab-Windows.zip");
  11502. ASSERT_TRUE(res);
  11503. EXPECT_EQ(StatusCode::OK_200, res->status);
  11504. EXPECT_EQ(9920427U, res->body.size());
  11505. }
  11506. #endif
  11507. TEST(VulnerabilityTest, CRLFInjection) {
  11508. Server svr;
  11509. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11510. res.set_content("Hello 1", "text/plain");
  11511. });
  11512. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11513. res.set_content("Hello 2", "text/plain");
  11514. });
  11515. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11516. res.set_content("Hello 3", "text/plain");
  11517. });
  11518. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11519. res.set_content("Hello 4", "text/plain");
  11520. });
  11521. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11522. for (const auto &x : req.headers) {
  11523. auto key = x.first;
  11524. EXPECT_STRNE("evil", key.c_str());
  11525. }
  11526. });
  11527. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11528. auto se = detail::scope_exit([&] {
  11529. svr.stop();
  11530. thread.join();
  11531. ASSERT_FALSE(svr.is_running());
  11532. });
  11533. svr.wait_until_ready();
  11534. {
  11535. Client cli(HOST, PORT);
  11536. cli.Post("/test1", "A=B",
  11537. "application/x-www-form-urlencoded\r\nevil: hello1");
  11538. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11539. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11540. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11541. }
  11542. }
  11543. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11544. auto server_thread = std::thread([] {
  11545. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11546. default_socket_options(srv);
  11547. sockaddr_in addr{};
  11548. addr.sin_family = AF_INET;
  11549. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11550. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11551. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11552. ::listen(srv, 1);
  11553. sockaddr_in cli_addr{};
  11554. socklen_t cli_len = sizeof(cli_addr);
  11555. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11556. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11557. std::string buf_all;
  11558. char buf[2048];
  11559. ssize_t n;
  11560. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11561. buf_all.append(buf, static_cast<size_t>(n));
  11562. size_t pos;
  11563. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11564. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11565. auto e = request_block.find("\r\n");
  11566. if (e != std::string::npos) {
  11567. auto request_line = request_block.substr(0, e);
  11568. std::string msg =
  11569. "CRLF injection detected in request line: '" + request_line + "'";
  11570. EXPECT_FALSE(true) << msg;
  11571. }
  11572. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11573. ::send(cli,
  11574. #ifdef _WIN32
  11575. static_cast<const char *>(resp.c_str()),
  11576. static_cast<int>(resp.size()),
  11577. #else
  11578. resp.c_str(), resp.size(),
  11579. #endif
  11580. 0);
  11581. buf_all.erase(0, pos + 4);
  11582. }
  11583. }
  11584. detail::close_socket(cli);
  11585. detail::close_socket(srv);
  11586. });
  11587. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11588. auto cli = Client("127.0.0.1", PORT + 1);
  11589. auto headers = Headers{
  11590. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11591. {"Connection", "keep-alive"}};
  11592. auto res = cli.Get("/hi", headers);
  11593. EXPECT_FALSE(res);
  11594. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11595. server_thread.join();
  11596. }
  11597. TEST(PathParamsTest, StaticMatch) {
  11598. const auto pattern = "/users/all";
  11599. detail::PathParamsMatcher matcher(pattern);
  11600. Request request;
  11601. request.path = "/users/all";
  11602. ASSERT_TRUE(matcher.match(request));
  11603. std::unordered_map<std::string, std::string> expected_params = {};
  11604. EXPECT_EQ(request.path_params, expected_params);
  11605. }
  11606. TEST(PathParamsTest, StaticMismatch) {
  11607. const auto pattern = "/users/all";
  11608. detail::PathParamsMatcher matcher(pattern);
  11609. Request request;
  11610. request.path = "/users/1";
  11611. ASSERT_FALSE(matcher.match(request));
  11612. }
  11613. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11614. const auto pattern = "/users/:id/subscriptions";
  11615. detail::PathParamsMatcher matcher(pattern);
  11616. Request request;
  11617. request.path = "/users/42/subscriptions";
  11618. ASSERT_TRUE(matcher.match(request));
  11619. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11620. EXPECT_EQ(request.path_params, expected_params);
  11621. }
  11622. TEST(PathParamsTest, SingleParamInTheEnd) {
  11623. const auto pattern = "/users/:id";
  11624. detail::PathParamsMatcher matcher(pattern);
  11625. Request request;
  11626. request.path = "/users/24";
  11627. ASSERT_TRUE(matcher.match(request));
  11628. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11629. EXPECT_EQ(request.path_params, expected_params);
  11630. }
  11631. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11632. const auto pattern = "/users/:id/";
  11633. detail::PathParamsMatcher matcher(pattern);
  11634. Request request;
  11635. request.path = "/users/42/";
  11636. ASSERT_TRUE(matcher.match(request));
  11637. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11638. EXPECT_EQ(request.path_params, expected_params);
  11639. }
  11640. TEST(PathParamsTest, EmptyParam) {
  11641. const auto pattern = "/users/:id/";
  11642. detail::PathParamsMatcher matcher(pattern);
  11643. Request request;
  11644. request.path = "/users//";
  11645. ASSERT_TRUE(matcher.match(request));
  11646. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11647. EXPECT_EQ(request.path_params, expected_params);
  11648. }
  11649. TEST(PathParamsTest, FragmentMismatch) {
  11650. const auto pattern = "/users/:id/";
  11651. detail::PathParamsMatcher matcher(pattern);
  11652. Request request;
  11653. request.path = "/admins/24/";
  11654. ASSERT_FALSE(matcher.match(request));
  11655. }
  11656. TEST(PathParamsTest, ExtraFragments) {
  11657. const auto pattern = "/users/:id";
  11658. detail::PathParamsMatcher matcher(pattern);
  11659. Request request;
  11660. request.path = "/users/42/subscriptions";
  11661. ASSERT_FALSE(matcher.match(request));
  11662. }
  11663. TEST(PathParamsTest, MissingTrailingParam) {
  11664. const auto pattern = "/users/:id";
  11665. detail::PathParamsMatcher matcher(pattern);
  11666. Request request;
  11667. request.path = "/users";
  11668. ASSERT_FALSE(matcher.match(request));
  11669. }
  11670. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11671. const auto pattern = "/users/:id/subscriptions";
  11672. detail::PathParamsMatcher matcher(pattern);
  11673. Request request;
  11674. request.path = "/users/subscriptions";
  11675. ASSERT_FALSE(matcher.match(request));
  11676. }
  11677. TEST(PathParamsTest, MultipleParams) {
  11678. const auto pattern = "/users/:userid/subscriptions/:subid";
  11679. detail::PathParamsMatcher matcher(pattern);
  11680. Request request;
  11681. request.path = "/users/42/subscriptions/2";
  11682. ASSERT_TRUE(matcher.match(request));
  11683. std::unordered_map<std::string, std::string> expected_params = {
  11684. {"userid", "42"}, {"subid", "2"}};
  11685. EXPECT_EQ(request.path_params, expected_params);
  11686. }
  11687. TEST(PathParamsTest, SequenceOfParams) {
  11688. const auto pattern = "/values/:x/:y/:z";
  11689. detail::PathParamsMatcher matcher(pattern);
  11690. Request request;
  11691. request.path = "/values/1/2/3";
  11692. ASSERT_TRUE(matcher.match(request));
  11693. std::unordered_map<std::string, std::string> expected_params = {
  11694. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11695. EXPECT_EQ(request.path_params, expected_params);
  11696. }
  11697. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11698. const auto pattern = "/prefix:suffix";
  11699. detail::PathParamsMatcher matcher(pattern);
  11700. Request request;
  11701. request.path = "/prefix:suffix";
  11702. ASSERT_TRUE(matcher.match(request));
  11703. const std::unordered_map<std::string, std::string> expected_params = {};
  11704. EXPECT_EQ(request.path_params, expected_params);
  11705. }
  11706. TEST(ParseUrlTest, VariousPatterns) {
  11707. {
  11708. detail::UrlComponents uc;
  11709. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11710. EXPECT_EQ("http", uc.scheme);
  11711. EXPECT_EQ("example.com", uc.host);
  11712. EXPECT_EQ("8080", uc.port);
  11713. EXPECT_EQ("/path", uc.path);
  11714. EXPECT_EQ("?q=1", uc.query);
  11715. }
  11716. {
  11717. detail::UrlComponents uc;
  11718. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11719. EXPECT_EQ("https", uc.scheme);
  11720. EXPECT_EQ("example.com", uc.host);
  11721. EXPECT_TRUE(uc.port.empty());
  11722. EXPECT_EQ("/path", uc.path);
  11723. }
  11724. {
  11725. detail::UrlComponents uc;
  11726. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11727. EXPECT_EQ("::1", uc.host);
  11728. EXPECT_EQ("8080", uc.port);
  11729. EXPECT_EQ("/path", uc.path);
  11730. }
  11731. {
  11732. detail::UrlComponents uc;
  11733. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11734. }
  11735. {
  11736. detail::UrlComponents uc;
  11737. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11738. EXPECT_TRUE(uc.scheme.empty());
  11739. EXPECT_EQ("example.com", uc.host);
  11740. EXPECT_EQ("/path", uc.path);
  11741. EXPECT_EQ("?q=1", uc.query);
  11742. }
  11743. {
  11744. detail::UrlComponents uc;
  11745. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11746. EXPECT_TRUE(uc.host.empty());
  11747. EXPECT_EQ("/path", uc.path);
  11748. EXPECT_EQ("?q=1", uc.query);
  11749. }
  11750. {
  11751. detail::UrlComponents uc;
  11752. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11753. EXPECT_EQ("example.com", uc.host);
  11754. EXPECT_EQ("8080", uc.port);
  11755. }
  11756. {
  11757. // Unix socket path — must not be parsed as host
  11758. detail::UrlComponents uc;
  11759. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11760. EXPECT_TRUE(uc.host.empty());
  11761. }
  11762. {
  11763. detail::UrlComponents uc;
  11764. ASSERT_TRUE(detail::parse_url("", uc));
  11765. EXPECT_TRUE(uc.host.empty());
  11766. EXPECT_TRUE(uc.path.empty());
  11767. }
  11768. {
  11769. detail::UrlComponents uc;
  11770. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11771. }
  11772. {
  11773. detail::UrlComponents uc;
  11774. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11775. }
  11776. {
  11777. // Accepted by parse_url; callers restrict to http/https
  11778. detail::UrlComponents uc;
  11779. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11780. EXPECT_EQ("ftp", uc.scheme);
  11781. }
  11782. {
  11783. detail::UrlComponents uc;
  11784. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11785. }
  11786. {
  11787. detail::UrlComponents uc;
  11788. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11789. }
  11790. }
  11791. TEST(ParseUrlTest, FragmentHandling) {
  11792. {
  11793. detail::UrlComponents uc;
  11794. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11795. EXPECT_EQ("/path", uc.path);
  11796. EXPECT_TRUE(uc.query.empty());
  11797. }
  11798. {
  11799. detail::UrlComponents uc;
  11800. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11801. EXPECT_TRUE(uc.path.empty());
  11802. EXPECT_TRUE(uc.query.empty());
  11803. }
  11804. }
  11805. TEST(ParseUrlTest, UserinfoHandling) {
  11806. // Userinfo with @ but no colon — host includes @
  11807. detail::UrlComponents uc;
  11808. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11809. EXPECT_EQ("user@host.com", uc.host);
  11810. EXPECT_EQ("/path", uc.path);
  11811. }
  11812. TEST(ParseUrlTest, IPv6EdgeCases) {
  11813. {
  11814. detail::UrlComponents uc;
  11815. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11816. EXPECT_TRUE(uc.scheme.empty());
  11817. EXPECT_EQ("::1", uc.host);
  11818. EXPECT_EQ("8080", uc.port);
  11819. }
  11820. {
  11821. // Zone ID '%25' is not in [a-fA-F0-9:]
  11822. detail::UrlComponents uc;
  11823. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11824. }
  11825. }
  11826. TEST(ParseUrlTest, SchemeEdgeCases) {
  11827. {
  11828. detail::UrlComponents uc;
  11829. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11830. }
  11831. {
  11832. detail::UrlComponents uc;
  11833. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11834. }
  11835. {
  11836. detail::UrlComponents uc;
  11837. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11838. }
  11839. }
  11840. TEST(ParseUrlTest, PortEdgeCases) {
  11841. {
  11842. detail::UrlComponents uc;
  11843. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11844. EXPECT_TRUE(uc.port.empty());
  11845. EXPECT_EQ("/path", uc.path);
  11846. }
  11847. {
  11848. // parse_url accepts any port string; validation is done by parse_port
  11849. detail::UrlComponents uc;
  11850. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11851. EXPECT_EQ("abc", uc.port);
  11852. }
  11853. }
  11854. TEST(ParseUrlTest, WebSocketPatterns) {
  11855. {
  11856. detail::UrlComponents uc;
  11857. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11858. EXPECT_EQ("ws", uc.scheme);
  11859. EXPECT_EQ("echo.example.com", uc.host);
  11860. EXPECT_EQ("8080", uc.port);
  11861. EXPECT_EQ("/ws", uc.path);
  11862. }
  11863. {
  11864. detail::UrlComponents uc;
  11865. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11866. EXPECT_EQ("wss", uc.scheme);
  11867. EXPECT_EQ("echo.example.com", uc.host);
  11868. EXPECT_TRUE(uc.port.empty());
  11869. EXPECT_EQ("/ws", uc.path);
  11870. }
  11871. }
  11872. TEST(ParseUrlTest, QueryOnly) {
  11873. detail::UrlComponents uc;
  11874. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11875. EXPECT_TRUE(uc.host.empty());
  11876. EXPECT_TRUE(uc.path.empty());
  11877. EXPECT_EQ("?q=1&r=2", uc.query);
  11878. }
  11879. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11880. detail::UrlComponents uc;
  11881. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11882. EXPECT_TRUE(uc.scheme.empty());
  11883. EXPECT_EQ("example.com", uc.host);
  11884. EXPECT_EQ("443", uc.port);
  11885. EXPECT_EQ("/path", uc.path);
  11886. }
  11887. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11888. // If ipv6 regex working, regex match codepath is taken.
  11889. // else port will default to 80 in Client impl
  11890. int clientImplMagicPort = 80;
  11891. int port = 4321;
  11892. // above ports must be different to avoid false negative
  11893. EXPECT_NE(clientImplMagicPort, port);
  11894. std::string ipV6TestURL = "http://[ff06::c3]";
  11895. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11896. CLIENT_PRIVATE_KEY_FILE);
  11897. EXPECT_EQ(cli.port(), port);
  11898. }
  11899. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11900. auto file_path = "./www/dir/index.html";
  11901. auto dir_path = "./www/dir";
  11902. detail::FileStat stat_file(file_path);
  11903. EXPECT_TRUE(stat_file.is_file());
  11904. EXPECT_FALSE(stat_file.is_dir());
  11905. detail::FileStat stat_dir(dir_path);
  11906. EXPECT_FALSE(stat_dir.is_file());
  11907. EXPECT_TRUE(stat_dir.is_dir());
  11908. }
  11909. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11910. // IPv4 with default HTTP port (80)
  11911. EXPECT_EQ("example.com",
  11912. detail::make_host_and_port_string("example.com", 80, false));
  11913. // IPv4 with default HTTPS port (443)
  11914. EXPECT_EQ("example.com",
  11915. detail::make_host_and_port_string("example.com", 443, true));
  11916. // IPv4 with non-default HTTP port
  11917. EXPECT_EQ("example.com:8080",
  11918. detail::make_host_and_port_string("example.com", 8080, false));
  11919. // IPv4 with non-default HTTPS port
  11920. EXPECT_EQ("example.com:8443",
  11921. detail::make_host_and_port_string("example.com", 8443, true));
  11922. // IPv6 with default HTTP port (80)
  11923. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11924. // IPv6 with default HTTPS port (443)
  11925. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11926. // IPv6 with non-default HTTP port
  11927. EXPECT_EQ("[::1]:8080",
  11928. detail::make_host_and_port_string("::1", 8080, false));
  11929. // IPv6 with non-default HTTPS port
  11930. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11931. // IPv6 full address with default port
  11932. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11933. detail::make_host_and_port_string(
  11934. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11935. // IPv6 full address with non-default port
  11936. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11937. detail::make_host_and_port_string(
  11938. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11939. // IPv6 localhost with non-default port
  11940. EXPECT_EQ("[::1]:3000",
  11941. detail::make_host_and_port_string("::1", 3000, false));
  11942. // IPv6 with zone ID (link-local address) with default port
  11943. EXPECT_EQ("[fe80::1%eth0]",
  11944. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11945. // IPv6 with zone ID (link-local address) with non-default port
  11946. EXPECT_EQ("[fe80::1%eth0]:8080",
  11947. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11948. // Edge case: Port 443 with is_ssl=false (should add port)
  11949. EXPECT_EQ("example.com:443",
  11950. detail::make_host_and_port_string("example.com", 443, false));
  11951. // Edge case: Port 80 with is_ssl=true (should add port)
  11952. EXPECT_EQ("example.com:80",
  11953. detail::make_host_and_port_string("example.com", 80, true));
  11954. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11955. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11956. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11957. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11958. // Security fix: Already bracketed IPv6 should not get double brackets
  11959. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11960. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11961. EXPECT_EQ("[::1]:8080",
  11962. detail::make_host_and_port_string("[::1]", 8080, false));
  11963. EXPECT_EQ("[2001:db8::1]:8080",
  11964. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11965. EXPECT_EQ("[fe80::1%eth0]",
  11966. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11967. EXPECT_EQ("[fe80::1%eth0]:8080",
  11968. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11969. // Edge case: Empty host (should return as-is)
  11970. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11971. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11972. // This is a known limitation but shouldn't crash
  11973. EXPECT_EQ("[host:name]",
  11974. detail::make_host_and_port_string("host:name", 80, false));
  11975. // Port number edge cases (no validation, but should not crash)
  11976. EXPECT_EQ("example.com:0",
  11977. detail::make_host_and_port_string("example.com", 0, false));
  11978. EXPECT_EQ("example.com:-1",
  11979. detail::make_host_and_port_string("example.com", -1, false));
  11980. EXPECT_EQ("example.com:65535",
  11981. detail::make_host_and_port_string("example.com", 65535, false));
  11982. EXPECT_EQ("example.com:65536",
  11983. detail::make_host_and_port_string("example.com", 65536, false));
  11984. }
  11985. #ifdef CPPHTTPLIB_SSL_ENABLED
  11986. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11987. httplib::SSLClient cli("roblox.com", 443);
  11988. cli.set_follow_location(true);
  11989. auto res = cli.Get("/");
  11990. ASSERT_TRUE(res);
  11991. EXPECT_EQ(StatusCode::OK_200, res->status);
  11992. }
  11993. #endif
  11994. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11995. Server svr;
  11996. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11997. EXPECT_EQ(res.status, 400);
  11998. });
  11999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12000. auto se = detail::scope_exit([&] {
  12001. svr.stop();
  12002. thread.join();
  12003. ASSERT_FALSE(svr.is_running());
  12004. });
  12005. svr.wait_until_ready();
  12006. Client cli(HOST, PORT);
  12007. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12008. }
  12009. TEST(InvalidHeaderCharsTest, is_field_name) {
  12010. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12011. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12012. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12013. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12014. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12015. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12016. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12017. EXPECT_FALSE(detail::fields::is_field_name(""));
  12018. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12019. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12020. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12021. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12022. }
  12023. TEST(InvalidHeaderCharsTest, is_field_value) {
  12024. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12025. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12026. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12027. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12028. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12029. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12030. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12031. EXPECT_TRUE(detail::fields::is_field_value(""));
  12032. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12033. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12034. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12035. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12036. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12037. }
  12038. TEST(InvalidHeaderCharsTest, OnServer) {
  12039. Server svr;
  12040. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12041. std::string header = "Not Set";
  12042. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12043. res.set_header(header, "value");
  12044. res.set_content("Page Content Page Content", "text/plain");
  12045. });
  12046. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12047. std::string header = "Not Set";
  12048. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12049. res.set_header("X-Test", header);
  12050. res.set_content("Page Content Page Content", "text/plain");
  12051. });
  12052. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12053. auto se = detail::scope_exit([&] {
  12054. svr.stop();
  12055. thread.join();
  12056. ASSERT_FALSE(svr.is_running());
  12057. });
  12058. svr.wait_until_ready();
  12059. Client cli(HOST, PORT);
  12060. {
  12061. auto res = cli.Get(
  12062. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12063. ASSERT_TRUE(res);
  12064. EXPECT_EQ("Page Content Page Content", res->body);
  12065. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12066. }
  12067. {
  12068. auto res = cli.Get(
  12069. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12070. ASSERT_TRUE(res);
  12071. EXPECT_EQ("Page Content Page Content", res->body);
  12072. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12073. }
  12074. }
  12075. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12076. auto handled = false;
  12077. Server svr;
  12078. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12079. thread t = thread([&] { svr.listen(HOST, PORT); });
  12080. auto se = detail::scope_exit([&] {
  12081. svr.stop();
  12082. t.join();
  12083. ASSERT_FALSE(svr.is_running());
  12084. ASSERT_FALSE(handled);
  12085. });
  12086. svr.wait_until_ready();
  12087. auto req = "POST /test HTTP/1.1\r\n"
  12088. "Content-Length: x\r\n"
  12089. "\r\n";
  12090. std::string response;
  12091. ASSERT_TRUE(send_request(1, req, &response));
  12092. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12093. response.substr(0, response.find("\r\n")));
  12094. }
  12095. #ifndef _WIN32
  12096. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12097. static constexpr char reject[] = "Unauthorized";
  12098. static constexpr char accept[] = "Upload accepted";
  12099. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12100. Server svr;
  12101. svr.set_expect_100_continue_handler(
  12102. [](const Request & /*req*/, Response &res) {
  12103. res.status = StatusCode::Unauthorized_401;
  12104. res.set_content(reject, "text/plain");
  12105. return res.status;
  12106. });
  12107. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12108. res.set_content(accept, "text/plain");
  12109. });
  12110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12111. auto se = detail::scope_exit([&] {
  12112. svr.stop();
  12113. thread.join();
  12114. ASSERT_FALSE(svr.is_running());
  12115. });
  12116. svr.wait_until_ready();
  12117. {
  12118. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12119. curl_easy_init(), &curl_easy_cleanup};
  12120. ASSERT_NE(curl, nullptr);
  12121. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12122. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12123. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12124. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12125. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12126. &curl_slist_free_all};
  12127. ASSERT_NE(list, nullptr);
  12128. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12129. struct read_data {
  12130. size_t read_size;
  12131. size_t total_size;
  12132. } data = {0, total_size};
  12133. using read_callback_t =
  12134. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12135. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12136. void *userdata) -> size_t {
  12137. read_data *d = (read_data *)userdata;
  12138. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12139. std::fill_n(ptr, size * nmemb, 'A');
  12140. d->read_size += size * nmemb;
  12141. return size * nmemb;
  12142. };
  12143. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12144. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12145. std::vector<char> buffer;
  12146. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12147. using write_callback_t =
  12148. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12149. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12150. void *userdata) -> size_t {
  12151. std::vector<char> *buf = (std::vector<char> *)userdata;
  12152. buf->reserve(buf->size() + size * nmemb + 1);
  12153. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12154. return size * nmemb;
  12155. };
  12156. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12157. {
  12158. const auto res = curl_easy_perform(curl.get());
  12159. ASSERT_EQ(res, CURLE_OK);
  12160. }
  12161. {
  12162. auto response_code = long{};
  12163. const auto res =
  12164. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12165. ASSERT_EQ(res, CURLE_OK);
  12166. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12167. }
  12168. {
  12169. auto dl = curl_off_t{};
  12170. const auto res =
  12171. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12172. ASSERT_EQ(res, CURLE_OK);
  12173. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12174. }
  12175. {
  12176. buffer.push_back('\0');
  12177. ASSERT_STRCASEEQ(buffer.data(), reject);
  12178. }
  12179. }
  12180. }
  12181. #endif
  12182. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12183. // Regression test for #2458.
  12184. //
  12185. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12186. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12187. // ticket can make the client socket spuriously readable during the
  12188. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12189. // the client withholds the body and then blocks reading a response that never
  12190. // comes, failing with `Failed to read connection`.
  12191. //
  12192. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12193. // within the timeout. This raw OpenSSL server deliberately never sends
  12194. // `100 Continue`; the client must still deliver the body and receive 200.
  12195. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12196. signal(SIGPIPE, SIG_IGN);
  12197. const auto port = PORT + 4;
  12198. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12199. ASSERT_NE(srv, INVALID_SOCKET);
  12200. int opt = 1;
  12201. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12202. sockaddr_in addr{};
  12203. addr.sin_family = AF_INET;
  12204. addr.sin_port = htons(static_cast<uint16_t>(port));
  12205. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12206. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12207. ASSERT_EQ(0, ::listen(srv, 1));
  12208. std::atomic<size_t> server_body_bytes{0};
  12209. auto server_thread = std::thread([&] {
  12210. sockaddr_in cli_addr{};
  12211. socklen_t cli_len = sizeof(cli_addr);
  12212. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12213. if (cli == INVALID_SOCKET) { return; }
  12214. // Bound the lifetime of the server side so a buggy client (which never
  12215. // sends the body) cannot make this thread block forever on join.
  12216. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12217. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12218. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12219. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12220. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12221. SSL *ssl = SSL_new(ctx);
  12222. SSL_set_fd(ssl, static_cast<int>(cli));
  12223. if (SSL_accept(ssl) > 0) {
  12224. // Read the request headers. Reading here also flushes the TLS 1.3
  12225. // session tickets to the client. Deliberately do NOT send
  12226. // `100 Continue`.
  12227. std::string buf;
  12228. char tmp[1024];
  12229. while (buf.find("\r\n\r\n") == std::string::npos) {
  12230. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12231. if (n <= 0) { break; }
  12232. buf.append(tmp, static_cast<size_t>(n));
  12233. }
  12234. // A correct client sends the body now; count what arrives.
  12235. auto pos = buf.find("\r\n\r\n");
  12236. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12237. while (body < 4096) {
  12238. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12239. if (n <= 0) { break; }
  12240. body += static_cast<size_t>(n);
  12241. }
  12242. server_body_bytes = body;
  12243. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12244. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12245. SSL_shutdown(ssl);
  12246. }
  12247. SSL_free(ssl);
  12248. detail::close_socket(cli);
  12249. SSL_CTX_free(ctx);
  12250. });
  12251. auto se = detail::scope_exit([&] {
  12252. server_thread.join();
  12253. detail::close_socket(srv);
  12254. });
  12255. SSLClient cli("127.0.0.1", port);
  12256. cli.enable_server_certificate_verification(false);
  12257. cli.set_connection_timeout(5, 0);
  12258. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12259. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12260. std::string body(4096, 'A');
  12261. auto res = cli.Put("/api/test", body, "application/json");
  12262. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12263. EXPECT_EQ(StatusCode::OK_200, res->status);
  12264. EXPECT_EQ(body.size(), server_body_bytes.load());
  12265. }
  12266. #endif
  12267. template <typename S, typename C>
  12268. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12269. svr.Get("/stream", [&](const Request &, Response &res) {
  12270. auto data = new std::string("01234567890123456789");
  12271. res.set_content_provider(
  12272. data->size(), "text/plain",
  12273. [&, data](size_t offset, size_t length, DataSink &sink) {
  12274. const size_t DATA_CHUNK_SIZE = 4;
  12275. const auto &d = *data;
  12276. std::this_thread::sleep_for(std::chrono::seconds(1));
  12277. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12278. return true;
  12279. },
  12280. [data](bool success) {
  12281. EXPECT_FALSE(success);
  12282. delete data;
  12283. });
  12284. });
  12285. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12286. auto i = new size_t(0);
  12287. res.set_content_provider(
  12288. "text/plain",
  12289. [i](size_t, DataSink &sink) {
  12290. if (*i < 5) {
  12291. std::this_thread::sleep_for(std::chrono::seconds(1));
  12292. sink.write("abcd", 4);
  12293. (*i)++;
  12294. } else {
  12295. sink.done();
  12296. }
  12297. return true;
  12298. },
  12299. [i](bool success) {
  12300. EXPECT_FALSE(success);
  12301. delete i;
  12302. });
  12303. });
  12304. svr.Get("/chunked", [&](const Request &, Response &res) {
  12305. auto i = new size_t(0);
  12306. res.set_chunked_content_provider(
  12307. "text/plain",
  12308. [i](size_t, DataSink &sink) {
  12309. if (*i < 5) {
  12310. std::this_thread::sleep_for(std::chrono::seconds(1));
  12311. sink.os << "abcd";
  12312. (*i)++;
  12313. } else {
  12314. sink.done();
  12315. }
  12316. return true;
  12317. },
  12318. [i](bool success) {
  12319. EXPECT_FALSE(success);
  12320. delete i;
  12321. });
  12322. });
  12323. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12324. auto se = detail::scope_exit([&] {
  12325. svr.stop();
  12326. listen_thread.join();
  12327. ASSERT_FALSE(svr.is_running());
  12328. });
  12329. svr.wait_until_ready();
  12330. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12331. {
  12332. auto start = std::chrono::steady_clock::now();
  12333. auto res = cli.Get("/stream");
  12334. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12335. std::chrono::steady_clock::now() - start)
  12336. .count();
  12337. ASSERT_FALSE(res);
  12338. EXPECT_EQ(Error::Read, res.error());
  12339. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12340. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12341. }
  12342. {
  12343. auto start = std::chrono::steady_clock::now();
  12344. auto res = cli.Get("/stream_without_length");
  12345. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12346. std::chrono::steady_clock::now() - start)
  12347. .count();
  12348. ASSERT_FALSE(res);
  12349. EXPECT_EQ(Error::Read, res.error());
  12350. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12351. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12352. }
  12353. {
  12354. auto start = std::chrono::steady_clock::now();
  12355. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12356. EXPECT_EQ("abcd", string(data, data_length));
  12357. return true;
  12358. });
  12359. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12360. std::chrono::steady_clock::now() - start)
  12361. .count();
  12362. ASSERT_FALSE(res);
  12363. EXPECT_EQ(Error::Read, res.error());
  12364. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12365. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12366. }
  12367. }
  12368. TEST(MaxTimeoutTest, ContentStream) {
  12369. time_t timeout = 2000;
  12370. time_t threshold = 200;
  12371. Server svr;
  12372. Client cli("localhost", PORT);
  12373. max_timeout_test(svr, cli, timeout, threshold);
  12374. }
  12375. #ifdef CPPHTTPLIB_SSL_ENABLED
  12376. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12377. time_t timeout = 2000;
  12378. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12380. SSLClient cli("localhost", PORT);
  12381. cli.enable_server_certificate_verification(false);
  12382. max_timeout_test(svr, cli, timeout, threshold);
  12383. }
  12384. #endif
  12385. class EventDispatcher {
  12386. public:
  12387. EventDispatcher() {}
  12388. bool wait_event(DataSink *sink) {
  12389. unique_lock<mutex> lk(m_);
  12390. int id = id_;
  12391. // Wait with timeout to prevent hanging if client disconnects
  12392. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12393. [&] { return cid_ == id; })) {
  12394. return false; // Timeout occurred
  12395. }
  12396. sink->write(message_.data(), message_.size());
  12397. return true;
  12398. }
  12399. void send_event(const string &message) {
  12400. lock_guard<mutex> lk(m_);
  12401. cid_ = id_++;
  12402. message_ = message;
  12403. cv_.notify_all();
  12404. }
  12405. private:
  12406. mutex m_;
  12407. condition_variable cv_;
  12408. atomic_int id_{0};
  12409. atomic_int cid_{-1};
  12410. string message_;
  12411. };
  12412. TEST(ClientInThreadTest, Issue2068) {
  12413. EventDispatcher ed;
  12414. Server svr;
  12415. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12416. res.set_chunked_content_provider("text/event-stream",
  12417. [&](size_t /*offset*/, DataSink &sink) {
  12418. return ed.wait_event(&sink);
  12419. });
  12420. });
  12421. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12422. svr.wait_until_ready();
  12423. thread event_thread([&] {
  12424. int id = 0;
  12425. while (svr.is_running()) {
  12426. this_thread::sleep_for(chrono::milliseconds(500));
  12427. std::stringstream ss;
  12428. ss << "data: " << id << "\n\n";
  12429. ed.send_event(ss.str());
  12430. id++;
  12431. }
  12432. });
  12433. auto se = detail::scope_exit([&] {
  12434. svr.stop();
  12435. listen_thread.join();
  12436. event_thread.join();
  12437. ASSERT_FALSE(svr.is_running());
  12438. });
  12439. {
  12440. auto client = detail::make_unique<Client>(HOST, PORT);
  12441. client->set_read_timeout(std::chrono::minutes(10));
  12442. std::atomic<bool> stop{false};
  12443. std::thread t([&] {
  12444. client->Get("/event1",
  12445. [&](const char *, size_t) -> bool { return !stop; });
  12446. });
  12447. std::this_thread::sleep_for(std::chrono::seconds(2));
  12448. stop = true;
  12449. client->stop();
  12450. t.join();
  12451. // Reset client after thread has finished
  12452. client.reset();
  12453. }
  12454. }
  12455. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12456. auto handled = false;
  12457. Server svr;
  12458. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12459. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12460. auto se = detail::scope_exit([&] {
  12461. svr.stop();
  12462. t.join();
  12463. ASSERT_FALSE(svr.is_running());
  12464. ASSERT_FALSE(handled);
  12465. });
  12466. svr.wait_until_ready();
  12467. // Two Content-Length headers with different values — must be rejected
  12468. auto req = "POST /test HTTP/1.1\r\n"
  12469. "Content-Length: 5\r\n"
  12470. "Content-Length: 10\r\n"
  12471. "\r\n"
  12472. "hello";
  12473. std::string response;
  12474. ASSERT_TRUE(send_request(1, req, &response));
  12475. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12476. response.substr(0, response.find("\r\n")));
  12477. }
  12478. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12479. auto handled = false;
  12480. Server svr;
  12481. svr.Post("/test", [&](const Request &, Response &res) {
  12482. handled = true;
  12483. res.set_content("ok", "text/plain");
  12484. });
  12485. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12486. auto se = detail::scope_exit([&] {
  12487. svr.stop();
  12488. t.join();
  12489. ASSERT_FALSE(svr.is_running());
  12490. ASSERT_TRUE(handled);
  12491. });
  12492. svr.wait_until_ready();
  12493. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12494. auto req = "POST /test HTTP/1.1\r\n"
  12495. "Content-Length: 5\r\n"
  12496. "Content-Length: 5\r\n"
  12497. "\r\n"
  12498. "hello";
  12499. std::string response;
  12500. ASSERT_TRUE(send_request(1, req, &response));
  12501. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12502. }
  12503. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12504. Server svr;
  12505. svr.Get("/", [](const Request &req, Response &res) {
  12506. EXPECT_EQ(2U, req.trailers.size());
  12507. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12508. // Denied
  12509. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12510. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12511. // Accepted
  12512. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12513. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12514. EXPECT_TRUE(req.has_trailer("X-World"));
  12515. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12516. res.set_content("ok", "text/plain");
  12517. });
  12518. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12519. auto se = detail::scope_exit([&] {
  12520. svr.stop();
  12521. t.join();
  12522. ASSERT_FALSE(svr.is_running());
  12523. });
  12524. svr.wait_until_ready();
  12525. const std::string req = "GET / HTTP/1.1\r\n"
  12526. "Transfer-Encoding: chunked\r\n"
  12527. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12528. "\r\n"
  12529. "0\r\n"
  12530. "Content-Length: 10\r\n"
  12531. "Host: internal.local\r\n"
  12532. "Content-Type: malicious/content\r\n"
  12533. "Cookie: any\r\n"
  12534. "Set-Cookie: any\r\n"
  12535. "X-Forwarded-For: attacker.com\r\n"
  12536. "X-Real-Ip: 1.1.1.1\r\n"
  12537. "X-Hello: hello\r\n"
  12538. "X-World: world\r\n"
  12539. "\r\n";
  12540. std::string res;
  12541. ASSERT_TRUE(send_request(1, req, &res));
  12542. }
  12543. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12544. Server svr;
  12545. std::string observed_remote_addr;
  12546. std::string observed_xff;
  12547. svr.Get("/ip", [&](const Request &req, Response &res) {
  12548. observed_remote_addr = req.remote_addr;
  12549. observed_xff = req.get_header_value("X-Forwarded-For");
  12550. res.set_content("ok", "text/plain");
  12551. });
  12552. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12553. auto se = detail::scope_exit([&] {
  12554. svr.stop();
  12555. t.join();
  12556. ASSERT_FALSE(svr.is_running());
  12557. });
  12558. svr.wait_until_ready();
  12559. Client cli(HOST, PORT);
  12560. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12561. ASSERT_TRUE(res);
  12562. EXPECT_EQ(StatusCode::OK_200, res->status);
  12563. EXPECT_EQ(observed_xff, "203.0.113.66");
  12564. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12565. observed_remote_addr == "127.0.0.1");
  12566. }
  12567. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12568. Server svr;
  12569. svr.set_trusted_proxies({"203.0.113.66"});
  12570. std::string observed_remote_addr;
  12571. std::string observed_xff;
  12572. svr.Get("/ip", [&](const Request &req, Response &res) {
  12573. observed_remote_addr = req.remote_addr;
  12574. observed_xff = req.get_header_value("X-Forwarded-For");
  12575. res.set_content("ok", "text/plain");
  12576. });
  12577. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12578. auto se = detail::scope_exit([&] {
  12579. svr.stop();
  12580. t.join();
  12581. ASSERT_FALSE(svr.is_running());
  12582. });
  12583. svr.wait_until_ready();
  12584. Client cli(HOST, PORT);
  12585. auto res = cli.Get("/ip");
  12586. ASSERT_TRUE(res);
  12587. EXPECT_EQ(StatusCode::OK_200, res->status);
  12588. EXPECT_EQ(observed_xff, "");
  12589. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12590. observed_remote_addr == "127.0.0.1");
  12591. }
  12592. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12593. Server svr;
  12594. svr.set_trusted_proxies({"203.0.113.66"});
  12595. std::string observed_remote_addr;
  12596. std::string observed_xff;
  12597. svr.Get("/ip", [&](const Request &req, Response &res) {
  12598. observed_remote_addr = req.remote_addr;
  12599. observed_xff = req.get_header_value("X-Forwarded-For");
  12600. res.set_content("ok", "text/plain");
  12601. });
  12602. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12603. auto se = detail::scope_exit([&] {
  12604. svr.stop();
  12605. t.join();
  12606. ASSERT_FALSE(svr.is_running());
  12607. });
  12608. svr.wait_until_ready();
  12609. Client cli(HOST, PORT);
  12610. auto res = cli.Get(
  12611. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12612. ASSERT_TRUE(res);
  12613. EXPECT_EQ(StatusCode::OK_200, res->status);
  12614. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12615. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12616. }
  12617. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12618. Server svr;
  12619. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12620. std::string observed_remote_addr;
  12621. std::string observed_xff;
  12622. svr.Get("/ip", [&](const Request &req, Response &res) {
  12623. observed_remote_addr = req.remote_addr;
  12624. observed_xff = req.get_header_value("X-Forwarded-For");
  12625. res.set_content("ok", "text/plain");
  12626. });
  12627. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12628. auto se = detail::scope_exit([&] {
  12629. svr.stop();
  12630. t.join();
  12631. ASSERT_FALSE(svr.is_running());
  12632. });
  12633. svr.wait_until_ready();
  12634. Client cli(HOST, PORT);
  12635. auto res = cli.Get(
  12636. "/ip",
  12637. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12638. ASSERT_TRUE(res);
  12639. EXPECT_EQ(StatusCode::OK_200, res->status);
  12640. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12641. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12642. }
  12643. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12644. Server svr;
  12645. svr.set_trusted_proxies({"192.0.2.45"});
  12646. std::string observed_remote_addr;
  12647. std::string observed_xff;
  12648. svr.Get("/ip", [&](const Request &req, Response &res) {
  12649. observed_remote_addr = req.remote_addr;
  12650. observed_xff = req.get_header_value("X-Forwarded-For");
  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. Client cli(HOST, PORT);
  12661. auto res = cli.Get(
  12662. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12663. ASSERT_TRUE(res);
  12664. EXPECT_EQ(StatusCode::OK_200, res->status);
  12665. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12666. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12667. }
  12668. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12669. Server svr;
  12670. svr.set_trusted_proxies({"192.0.2.45"});
  12671. std::string observed_remote_addr;
  12672. std::string observed_xff;
  12673. svr.Get("/ip", [&](const Request &req, Response &res) {
  12674. observed_remote_addr = req.remote_addr;
  12675. observed_xff = req.get_header_value("X-Forwarded-For");
  12676. res.set_content("ok", "text/plain");
  12677. });
  12678. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12679. auto se = detail::scope_exit([&] {
  12680. svr.stop();
  12681. t.join();
  12682. ASSERT_FALSE(svr.is_running());
  12683. });
  12684. svr.wait_until_ready();
  12685. Client cli(HOST, PORT);
  12686. auto res = cli.Get(
  12687. "/ip",
  12688. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12689. ASSERT_TRUE(res);
  12690. EXPECT_EQ(StatusCode::OK_200, res->status);
  12691. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12692. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12693. }
  12694. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12695. Server svr;
  12696. svr.set_trusted_proxies({"192.0.2.45"});
  12697. std::string observed_remote_addr;
  12698. std::string observed_xff;
  12699. svr.Get("/ip", [&](const Request &req, Response &res) {
  12700. observed_remote_addr = req.remote_addr;
  12701. observed_xff = req.get_header_value("X-Forwarded-For");
  12702. res.set_content("ok", "text/plain");
  12703. });
  12704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12705. auto se = detail::scope_exit([&] {
  12706. svr.stop();
  12707. t.join();
  12708. ASSERT_FALSE(svr.is_running());
  12709. });
  12710. svr.wait_until_ready();
  12711. std::string raw_req =
  12712. "GET /ip HTTP/1.1\r\n"
  12713. "Host: localhost\r\n"
  12714. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12715. "Connection: close\r\n"
  12716. "\r\n";
  12717. std::string out;
  12718. ASSERT_TRUE(send_request(5, raw_req, &out));
  12719. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12720. // Header parser trims surrounding whitespace of the header value
  12721. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12722. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12723. }
  12724. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12725. // crash the server (it used to call front() on an empty vector inside
  12726. // get_client_ip). The connection-level remote address must be retained instead.
  12727. static void run_malformed_xff_test(const std::string &xff_value) {
  12728. Server svr;
  12729. svr.set_trusted_proxies({"192.0.2.45"});
  12730. std::string observed_remote_addr;
  12731. svr.Get("/ip", [&](const Request &req, Response &res) {
  12732. observed_remote_addr = req.remote_addr;
  12733. res.set_content("ok", "text/plain");
  12734. });
  12735. int port = 0;
  12736. thread t = thread([&]() {
  12737. port = svr.bind_to_any_port(HOST);
  12738. svr.listen_after_bind();
  12739. });
  12740. auto se = detail::scope_exit([&] {
  12741. svr.stop();
  12742. t.join();
  12743. ASSERT_FALSE(svr.is_running());
  12744. });
  12745. svr.wait_until_ready();
  12746. Client cli(HOST, port);
  12747. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  12748. ASSERT_TRUE(res);
  12749. EXPECT_EQ(StatusCode::OK_200, res->status);
  12750. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12751. observed_remote_addr == "127.0.0.1");
  12752. }
  12753. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12754. run_malformed_xff_test("");
  12755. }
  12756. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12757. run_malformed_xff_test(",");
  12758. }
  12759. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12760. run_malformed_xff_test(", , ,");
  12761. }
  12762. #ifndef _WIN32
  12763. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12764. Server svr;
  12765. svr.Post("/post", [&](const Request &req, Response &res) {
  12766. res.set_content(req.body, "text/plain");
  12767. });
  12768. svr.Put("/put", [&](const Request &req, Response &res) {
  12769. res.set_content(req.body, "text/plain");
  12770. });
  12771. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12772. res.set_content(req.body, "text/plain");
  12773. });
  12774. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12775. res.set_content(req.body, "text/plain");
  12776. });
  12777. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12778. auto se = detail::scope_exit([&] {
  12779. svr.stop();
  12780. t.join();
  12781. ASSERT_FALSE(svr.is_running());
  12782. });
  12783. svr.wait_until_ready();
  12784. std::string resp;
  12785. // POST without Content-Length
  12786. ASSERT_TRUE(send_request(5,
  12787. "POST /post HTTP/1.1\r\n"
  12788. "Host: localhost\r\n"
  12789. "Connection: close\r\n"
  12790. "\r\n",
  12791. &resp));
  12792. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12793. // PUT without Content-Length
  12794. resp.clear();
  12795. ASSERT_TRUE(send_request(5,
  12796. "PUT /put HTTP/1.1\r\n"
  12797. "Host: localhost\r\n"
  12798. "Connection: close\r\n"
  12799. "\r\n",
  12800. &resp));
  12801. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12802. // PATCH without Content-Length
  12803. resp.clear();
  12804. ASSERT_TRUE(send_request(5,
  12805. "PATCH /patch HTTP/1.1\r\n"
  12806. "Host: localhost\r\n"
  12807. "Connection: close\r\n"
  12808. "\r\n",
  12809. &resp));
  12810. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12811. // DELETE without Content-Length
  12812. resp.clear();
  12813. ASSERT_TRUE(send_request(5,
  12814. "DELETE /delete HTTP/1.1\r\n"
  12815. "Host: localhost\r\n"
  12816. "Connection: close\r\n"
  12817. "\r\n",
  12818. &resp));
  12819. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12820. }
  12821. #endif
  12822. //==============================================================================
  12823. // open_stream() Tests
  12824. //==============================================================================
  12825. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12826. std::string result;
  12827. char buf[8192];
  12828. ssize_t n;
  12829. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12830. result.append(buf, static_cast<size_t>(n));
  12831. }
  12832. return result;
  12833. }
  12834. // Mock stream for unit tests
  12835. class MockStream : public Stream {
  12836. public:
  12837. std::string data;
  12838. size_t pos = 0;
  12839. ssize_t error_after = -1; // -1 = no error
  12840. explicit MockStream(const std::string &d, ssize_t err = -1)
  12841. : data(d), error_after(err) {}
  12842. bool is_readable() const override { return true; }
  12843. bool wait_readable() const override { return true; }
  12844. bool wait_writable() const override { return true; }
  12845. ssize_t read(char *ptr, size_t size) override {
  12846. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12847. if (pos >= data.size()) return 0;
  12848. size_t limit =
  12849. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12850. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12851. std::memcpy(ptr, data.data() + pos, to_read);
  12852. pos += to_read;
  12853. return static_cast<ssize_t>(to_read);
  12854. }
  12855. ssize_t write(const char *, size_t) override { return -1; }
  12856. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12857. ip = "127.0.0.1";
  12858. port = 0;
  12859. }
  12860. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12861. ip = "127.0.0.1";
  12862. port = 0;
  12863. }
  12864. socket_t socket() const override { return INVALID_SOCKET; }
  12865. time_t duration() const override { return 0; }
  12866. };
  12867. TEST(StreamHandleTest, Basic) {
  12868. ClientImpl::StreamHandle handle;
  12869. EXPECT_FALSE(handle.is_valid());
  12870. handle.response = detail::make_unique<Response>();
  12871. handle.error = Error::Connection;
  12872. EXPECT_FALSE(handle.is_valid());
  12873. handle.error = Error::Success;
  12874. EXPECT_TRUE(handle.is_valid());
  12875. }
  12876. TEST(BodyReaderTest, Basic) {
  12877. MockStream stream("Hello, World!");
  12878. detail::BodyReader reader;
  12879. reader.stream = &stream;
  12880. reader.content_length = 13;
  12881. char buf[32];
  12882. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12883. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12884. EXPECT_TRUE(reader.eof);
  12885. }
  12886. TEST(BodyReaderTest, NoStream) {
  12887. detail::BodyReader reader;
  12888. char buf[32];
  12889. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12890. EXPECT_EQ(Error::Connection, reader.last_error);
  12891. }
  12892. TEST(BodyReaderTest, Error) {
  12893. MockStream stream("Hello, World!", 5);
  12894. detail::BodyReader reader;
  12895. reader.stream = &stream;
  12896. reader.content_length = 13;
  12897. char buf[32];
  12898. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12899. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12900. EXPECT_EQ(Error::Read, reader.last_error);
  12901. }
  12902. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12903. // Mock-based StreamHandle tests relying on private internals are removed.
  12904. class OpenStreamTest : public ::testing::Test {
  12905. protected:
  12906. void SetUp() override {
  12907. svr_.Get("/hello", [](const Request &, Response &res) {
  12908. res.set_content("Hello World!", "text/plain");
  12909. });
  12910. svr_.Get("/large", [](const Request &, Response &res) {
  12911. res.set_content(std::string(10000, 'X'), "text/plain");
  12912. });
  12913. svr_.Get("/chunked", [](const Request &, Response &res) {
  12914. res.set_chunked_content_provider("text/plain",
  12915. [](size_t offset, DataSink &sink) {
  12916. if (offset < 15) {
  12917. sink.write("chunk", 5);
  12918. return true;
  12919. }
  12920. sink.done();
  12921. return true;
  12922. });
  12923. });
  12924. svr_.Get("/compressible", [](const Request &, Response &res) {
  12925. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12926. DataSink &sink) {
  12927. if (offset < 100 * 1024) {
  12928. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12929. sink.write(chunk.data(), chunk.size());
  12930. return true;
  12931. }
  12932. sink.done();
  12933. return true;
  12934. });
  12935. });
  12936. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12937. [](const Request & /*req*/, Response &res) {
  12938. auto i = new int(0);
  12939. res.set_header("Trailer", "Content-Length, X-Allowed");
  12940. res.set_chunked_content_provider(
  12941. "text/plain",
  12942. [i](size_t /*offset*/, DataSink &sink) {
  12943. switch (*i) {
  12944. case 0: sink.os << "123"; break;
  12945. case 1: sink.os << "456"; break;
  12946. case 2: sink.os << "789"; break;
  12947. case 3: {
  12948. sink.done_with_trailer(
  12949. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12950. } break;
  12951. }
  12952. (*i)++;
  12953. return true;
  12954. },
  12955. [i](bool success) {
  12956. EXPECT_TRUE(success);
  12957. delete i;
  12958. });
  12959. });
  12960. // Echo headers endpoint for header-related tests
  12961. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12962. std::string body;
  12963. for (const auto &h : req.headers) {
  12964. body.append(h.first);
  12965. body.push_back(':');
  12966. body.append(h.second);
  12967. body.push_back('\n');
  12968. }
  12969. res.set_content(body, "text/plain");
  12970. });
  12971. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12972. std::string body;
  12973. for (const auto &h : req.headers) {
  12974. body.append(h.first);
  12975. body.push_back(':');
  12976. body.append(h.second);
  12977. body.push_back('\n');
  12978. }
  12979. res.set_content(body, "text/plain");
  12980. });
  12981. port_ = svr_.bind_to_any_port("127.0.0.1");
  12982. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12983. svr_.wait_until_ready();
  12984. }
  12985. void TearDown() override {
  12986. svr_.stop();
  12987. if (thread_.joinable()) thread_.join();
  12988. }
  12989. Server svr_;
  12990. std::thread thread_;
  12991. int port_ = 0;
  12992. };
  12993. TEST_F(OpenStreamTest, Basic) {
  12994. Client cli("127.0.0.1", port_);
  12995. auto handle = cli.open_stream("GET", "/hello");
  12996. EXPECT_TRUE(handle.is_valid());
  12997. EXPECT_EQ("Hello World!", read_all(handle));
  12998. }
  12999. TEST_F(OpenStreamTest, SmallBuffer) {
  13000. Client cli("127.0.0.1", port_);
  13001. auto handle = cli.open_stream("GET", "/hello");
  13002. std::string result;
  13003. char buf[4];
  13004. ssize_t n;
  13005. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13006. result.append(buf, static_cast<size_t>(n));
  13007. EXPECT_EQ("Hello World!", result);
  13008. }
  13009. TEST_F(OpenStreamTest, DefaultHeaders) {
  13010. Client cli("127.0.0.1", port_);
  13011. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13012. {
  13013. auto handle = cli.open_stream("GET", "/echo-headers");
  13014. ASSERT_TRUE(handle.is_valid());
  13015. auto body = read_all(handle);
  13016. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13017. std::string::npos);
  13018. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13019. std::string::npos);
  13020. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13021. }
  13022. // open_stream POST with body and no explicit content_type should NOT add
  13023. // text/plain Content-Type (behavior differs from non-streaming path), but
  13024. // should include Content-Length
  13025. {
  13026. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13027. ASSERT_TRUE(handle.is_valid());
  13028. auto body = read_all(handle);
  13029. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13030. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13031. }
  13032. // open_stream POST with explicit Content-Type should preserve it
  13033. {
  13034. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13035. {{"Content-Type", "application/custom"}},
  13036. "{}", "application/custom");
  13037. ASSERT_TRUE(handle.is_valid());
  13038. auto body = read_all(handle);
  13039. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13040. }
  13041. // User-specified User-Agent must not be overwritten for stream API
  13042. {
  13043. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13044. {{"User-Agent", "MyAgent/1.2"}});
  13045. ASSERT_TRUE(handle.is_valid());
  13046. auto body = read_all(handle);
  13047. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13048. }
  13049. }
  13050. TEST_F(OpenStreamTest, Large) {
  13051. Client cli("127.0.0.1", port_);
  13052. auto handle = cli.open_stream("GET", "/large");
  13053. EXPECT_EQ(10000u, read_all(handle).size());
  13054. }
  13055. TEST_F(OpenStreamTest, ConnectionError) {
  13056. Client cli("127.0.0.1", 9999);
  13057. auto handle = cli.open_stream("GET", "/hello");
  13058. EXPECT_FALSE(handle.is_valid());
  13059. }
  13060. TEST_F(OpenStreamTest, Chunked) {
  13061. Client cli("127.0.0.1", port_);
  13062. auto handle = cli.open_stream("GET", "/chunked");
  13063. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13064. "Transfer-Encoding") == "chunked");
  13065. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13066. }
  13067. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13068. Client cli("127.0.0.1", port_);
  13069. auto handle =
  13070. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13071. ASSERT_TRUE(handle.is_valid());
  13072. // Consume body to allow trailers to be received/parsed
  13073. auto body = read_all(handle);
  13074. // Explicitly parse trailers (ensure trailers are available for assertion)
  13075. handle.parse_trailers_if_needed();
  13076. EXPECT_EQ(std::string("123456789"), body);
  13077. // The response should include a Trailer header declaring both names
  13078. ASSERT_TRUE(handle.response);
  13079. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13080. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13081. handle.response->get_header_value("Trailer"));
  13082. // Prohibited trailer must not be present
  13083. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13084. // Allowed trailer should be present
  13085. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13086. EXPECT_EQ(std::string("yes"),
  13087. handle.response->get_trailer_value("X-Allowed"));
  13088. // Verify trailers are NOT present as regular headers
  13089. EXPECT_EQ(std::string(""),
  13090. handle.response->get_header_value("Content-Length"));
  13091. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13092. }
  13093. static std::thread serve_single_response(std::promise<int> &port_promise,
  13094. const std::string &response) {
  13095. return std::thread([&port_promise, response] {
  13096. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13097. default_socket_options(srv);
  13098. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13099. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13100. sockaddr_in addr{};
  13101. addr.sin_family = AF_INET;
  13102. addr.sin_port = htons(0); // Let OS assign a free port
  13103. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13104. int opt = 1;
  13105. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13106. #ifdef _WIN32
  13107. reinterpret_cast<const char *>(&opt),
  13108. #else
  13109. &opt,
  13110. #endif
  13111. sizeof(opt));
  13112. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13113. ::listen(srv, 1) != 0) {
  13114. port_promise.set_value(-1);
  13115. detail::close_socket(srv);
  13116. return;
  13117. }
  13118. socklen_t addr_len = sizeof(addr);
  13119. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13120. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13121. sockaddr_in cli_addr{};
  13122. socklen_t cli_len = sizeof(cli_addr);
  13123. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13124. if (cli != INVALID_SOCKET) {
  13125. // Read the complete HTTP request (until the blank line that terminates
  13126. // headers) before sending the response. If the server closes the socket
  13127. // while the client's request data is still unread in the kernel receive
  13128. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13129. // connection on both sides: it discards the client's receive buffer
  13130. // (which already holds our response) and causes any in-progress write on
  13131. // the client to fail with ECONNRESET. Reading all request data first
  13132. // ensures close() emits a graceful FIN.
  13133. {
  13134. char rbuf[256];
  13135. std::string req;
  13136. while (req.find("\r\n\r\n") == std::string::npos) {
  13137. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13138. if (n <= 0) { break; }
  13139. req.append(rbuf, static_cast<size_t>(n));
  13140. }
  13141. }
  13142. ::send(cli,
  13143. #ifdef _WIN32
  13144. static_cast<const char *>(response.c_str()),
  13145. static_cast<int>(response.size()),
  13146. #else
  13147. response.c_str(), response.size(),
  13148. #endif
  13149. 0);
  13150. detail::close_socket(cli);
  13151. }
  13152. detail::close_socket(srv);
  13153. });
  13154. }
  13155. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13156. #ifndef _WIN32
  13157. signal(SIGPIPE, SIG_IGN);
  13158. #endif
  13159. std::promise<int> port_promise;
  13160. auto port_future = port_promise.get_future();
  13161. auto server_thread =
  13162. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13163. "Content-Type: text/plain\r\n"
  13164. "Content-Length: not-a-number\r\n"
  13165. "Connection: close\r\n"
  13166. "\r\n"
  13167. "hello");
  13168. auto port = port_future.get();
  13169. ASSERT_GT(port, 0);
  13170. Client cli("127.0.0.1", port);
  13171. auto handle = cli.open_stream("GET", "/");
  13172. EXPECT_FALSE(handle.is_valid());
  13173. server_thread.join();
  13174. }
  13175. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13176. #ifndef _WIN32
  13177. signal(SIGPIPE, SIG_IGN);
  13178. #endif
  13179. std::promise<int> port_promise;
  13180. auto port_future = port_promise.get_future();
  13181. auto server_thread = serve_single_response(
  13182. port_promise, "HTTP/1.1 200 OK\r\n"
  13183. "Content-Type: text/plain\r\n"
  13184. "Content-Length: 99999999999999999999999999\r\n"
  13185. "Connection: close\r\n"
  13186. "\r\n"
  13187. "hello");
  13188. auto port = port_future.get();
  13189. ASSERT_GT(port, 0);
  13190. // Before the fix, std::stoull would throw std::out_of_range here and
  13191. // crash the process. After the fix, strtoull silently clamps to
  13192. // ULLONG_MAX so the stream opens without crashing. The important thing
  13193. // is that the process does NOT terminate.
  13194. Client cli("127.0.0.1", port);
  13195. auto handle = cli.open_stream("GET", "/");
  13196. EXPECT_TRUE(handle.is_valid());
  13197. server_thread.join();
  13198. }
  13199. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13200. TEST_F(OpenStreamTest, Gzip) {
  13201. Client cli("127.0.0.1", port_);
  13202. auto handle = cli.open_stream("GET", "/compressible", {},
  13203. {{"Accept-Encoding", "gzip"}});
  13204. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13205. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13206. }
  13207. #endif
  13208. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13209. TEST_F(OpenStreamTest, Brotli) {
  13210. Client cli("127.0.0.1", port_);
  13211. auto handle =
  13212. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13213. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13214. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13215. }
  13216. #endif
  13217. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13218. TEST_F(OpenStreamTest, Zstd) {
  13219. Client cli("127.0.0.1", port_);
  13220. auto handle = cli.open_stream("GET", "/compressible", {},
  13221. {{"Accept-Encoding", "zstd"}});
  13222. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13223. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13224. }
  13225. #endif
  13226. #ifdef CPPHTTPLIB_SSL_ENABLED
  13227. class SSLOpenStreamTest : public ::testing::Test {
  13228. protected:
  13229. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13230. void SetUp() override {
  13231. svr_.Get("/hello", [](const Request &, Response &res) {
  13232. res.set_content("Hello SSL World!", "text/plain");
  13233. });
  13234. svr_.Get("/chunked", [](const Request &, Response &res) {
  13235. res.set_chunked_content_provider("text/plain",
  13236. [](size_t offset, DataSink &sink) {
  13237. if (offset < 15) {
  13238. sink.write("chunk", 5);
  13239. return true;
  13240. }
  13241. sink.done();
  13242. return true;
  13243. });
  13244. });
  13245. svr_.Post("/echo", [](const Request &req, Response &res) {
  13246. res.set_content(req.body, req.get_header_value("Content-Type"));
  13247. });
  13248. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13249. std::string body = req.body;
  13250. res.set_chunked_content_provider(
  13251. "text/plain", [body](size_t offset, DataSink &sink) {
  13252. if (offset < body.size()) {
  13253. sink.write(body.data() + offset, body.size() - offset);
  13254. }
  13255. sink.done();
  13256. return true;
  13257. });
  13258. });
  13259. port_ = svr_.bind_to_any_port("127.0.0.1");
  13260. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13261. svr_.wait_until_ready();
  13262. }
  13263. void TearDown() override {
  13264. svr_.stop();
  13265. if (thread_.joinable()) thread_.join();
  13266. }
  13267. SSLServer svr_;
  13268. std::thread thread_;
  13269. int port_ = 0;
  13270. };
  13271. TEST_F(SSLOpenStreamTest, Basic) {
  13272. SSLClient cli("127.0.0.1", port_);
  13273. cli.enable_server_certificate_verification(false);
  13274. auto handle = cli.open_stream("GET", "/hello");
  13275. ASSERT_TRUE(handle.is_valid());
  13276. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13277. }
  13278. TEST_F(SSLOpenStreamTest, Chunked) {
  13279. SSLClient cli("127.0.0.1", port_);
  13280. cli.enable_server_certificate_verification(false);
  13281. auto handle = cli.open_stream("GET", "/chunked");
  13282. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13283. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13284. "Transfer-Encoding") == "chunked");
  13285. auto body = read_all(handle);
  13286. EXPECT_EQ("chunkchunkchunk", body);
  13287. }
  13288. TEST_F(SSLOpenStreamTest, Post) {
  13289. SSLClient cli("127.0.0.1", port_);
  13290. cli.enable_server_certificate_verification(false);
  13291. auto handle =
  13292. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13293. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13294. EXPECT_EQ(200, handle.response->status);
  13295. auto body = read_all(handle);
  13296. EXPECT_EQ("Hello SSL POST", body);
  13297. }
  13298. TEST_F(SSLOpenStreamTest, PostChunked) {
  13299. SSLClient cli("127.0.0.1", port_);
  13300. cli.enable_server_certificate_verification(false);
  13301. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13302. "Chunked SSL Data", "text/plain");
  13303. ASSERT_TRUE(handle.is_valid());
  13304. EXPECT_EQ(200, handle.response->status);
  13305. auto body = read_all(handle);
  13306. EXPECT_EQ("Chunked SSL Data", body);
  13307. }
  13308. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13309. // Content-Length is terminated by the server closing the connection. When the
  13310. // SSL peer sends a close_notify after the body, the client must treat it as a
  13311. // clean EOF and return a successful response rather than an error.
  13312. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13314. ASSERT_TRUE(svr.is_valid());
  13315. svr.set_keep_alive_max_count(1);
  13316. const std::string expected_body = "Hello from connection-close response!";
  13317. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13318. res.set_content_provider("text/plain",
  13319. [&](size_t offset, DataSink &sink) -> bool {
  13320. if (offset < expected_body.size()) {
  13321. sink.write(expected_body.data() + offset,
  13322. expected_body.size() - offset);
  13323. }
  13324. sink.done();
  13325. return true;
  13326. });
  13327. });
  13328. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13329. auto se = detail::scope_exit([&] {
  13330. svr.stop();
  13331. listen_thread.join();
  13332. ASSERT_FALSE(svr.is_running());
  13333. });
  13334. svr.wait_until_ready();
  13335. SSLClient cli(HOST, PORT);
  13336. cli.enable_server_certificate_verification(false);
  13337. auto res = cli.Get("/no-content-length");
  13338. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13339. EXPECT_EQ(StatusCode::OK_200, res->status);
  13340. EXPECT_EQ(expected_body, res->body);
  13341. }
  13342. #endif // CPPHTTPLIB_SSL_ENABLED
  13343. //==============================================================================
  13344. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13345. // results for various scenarios.
  13346. //==============================================================================
  13347. TEST(ParityTest, GetVsOpenStream) {
  13348. Server svr;
  13349. const std::string path = "/parity";
  13350. const std::string content = "Parity test content: hello world";
  13351. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13352. res.set_content(content, "text/plain");
  13353. });
  13354. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13355. auto se = detail::scope_exit([&] {
  13356. svr.stop();
  13357. t.join();
  13358. ASSERT_FALSE(svr.is_running());
  13359. });
  13360. svr.wait_until_ready();
  13361. Client cli(HOST, PORT);
  13362. // Non-stream path
  13363. auto r1 = cli.Get(path);
  13364. ASSERT_TRUE(r1);
  13365. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13366. // Stream path
  13367. auto h = cli.open_stream("GET", path);
  13368. ASSERT_TRUE(h.is_valid());
  13369. EXPECT_EQ(r1->body, read_all(h));
  13370. }
  13371. // Helper to compress data with provided compressor type T
  13372. template <typename Compressor>
  13373. static std::string compress_payload_for_parity(const std::string &in) {
  13374. std::string out;
  13375. Compressor compressor;
  13376. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13377. [&](const char *data, size_t n) {
  13378. out.append(data, n);
  13379. return true;
  13380. });
  13381. EXPECT_TRUE(ok);
  13382. return out;
  13383. }
  13384. // Helper function for compression parity tests
  13385. template <typename Compressor>
  13386. static void test_compression_parity(const std::string &original,
  13387. const std::string &path,
  13388. const std::string &encoding) {
  13389. const std::string compressed =
  13390. compress_payload_for_parity<Compressor>(original);
  13391. Server svr;
  13392. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13393. res.set_content(compressed, "application/octet-stream");
  13394. res.set_header("Content-Encoding", encoding);
  13395. });
  13396. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13397. auto se = detail::scope_exit([&] {
  13398. svr.stop();
  13399. t.join();
  13400. ASSERT_FALSE(svr.is_running());
  13401. });
  13402. svr.wait_until_ready();
  13403. Client cli(HOST, PORT);
  13404. // Non-streaming
  13405. {
  13406. auto res = cli.Get(path);
  13407. ASSERT_TRUE(res);
  13408. EXPECT_EQ(StatusCode::OK_200, res->status);
  13409. EXPECT_EQ(original, res->body);
  13410. }
  13411. // Streaming
  13412. {
  13413. auto h = cli.open_stream("GET", path);
  13414. ASSERT_TRUE(h.is_valid());
  13415. EXPECT_EQ(original, read_all(h));
  13416. }
  13417. }
  13418. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13419. TEST(ParityTest, Gzip) {
  13420. test_compression_parity<detail::gzip_compressor>(
  13421. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13422. }
  13423. #endif
  13424. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13425. TEST(ParityTest, Brotli) {
  13426. test_compression_parity<detail::brotli_compressor>(
  13427. "Hello, brotli parity test payload", "/parity-br", "br");
  13428. }
  13429. #endif
  13430. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13431. TEST(ParityTest, Zstd) {
  13432. test_compression_parity<detail::zstd_compressor>(
  13433. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13434. }
  13435. #endif
  13436. //==============================================================================
  13437. // New Stream API Tests
  13438. //==============================================================================
  13439. inline std::string read_body(httplib::stream::Result &result) {
  13440. std::string body;
  13441. while (result.next()) {
  13442. body.append(result.data(), result.size());
  13443. }
  13444. return body;
  13445. }
  13446. TEST(ClientConnectionTest, Basic) {
  13447. httplib::ClientConnection conn;
  13448. EXPECT_FALSE(conn.is_open());
  13449. conn.sock = 1;
  13450. EXPECT_TRUE(conn.is_open());
  13451. httplib::ClientConnection conn2(std::move(conn));
  13452. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13453. conn2.sock = INVALID_SOCKET;
  13454. }
  13455. // Unified test server for all stream::* tests
  13456. class StreamApiTest : public ::testing::Test {
  13457. protected:
  13458. void SetUp() override {
  13459. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13460. res.set_content("Hello World!", "text/plain");
  13461. });
  13462. svr_.Get("/echo-params",
  13463. [](const httplib::Request &req, httplib::Response &res) {
  13464. std::string r;
  13465. for (const auto &p : req.params) {
  13466. if (!r.empty()) r += "&";
  13467. r += p.first + "=" + p.second;
  13468. }
  13469. res.set_content(r, "text/plain");
  13470. });
  13471. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13472. res.set_content(req.body, req.get_header_value("Content-Type"));
  13473. });
  13474. svr_.Post("/echo-headers",
  13475. [](const httplib::Request &req, httplib::Response &res) {
  13476. std::string r;
  13477. for (const auto &h : req.headers)
  13478. r += h.first + ": " + h.second + "\n";
  13479. res.set_content(r, "text/plain");
  13480. });
  13481. svr_.Post("/echo-params",
  13482. [](const httplib::Request &req, httplib::Response &res) {
  13483. std::string r = "params:";
  13484. for (const auto &p : req.params)
  13485. r += p.first + "=" + p.second + ";";
  13486. res.set_content(r + " body:" + req.body, "text/plain");
  13487. });
  13488. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13489. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13490. });
  13491. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13492. res.set_content("PUT:" + req.body, "text/plain");
  13493. });
  13494. svr_.Patch("/echo",
  13495. [](const httplib::Request &req, httplib::Response &res) {
  13496. res.set_content("PATCH:" + req.body, "text/plain");
  13497. });
  13498. svr_.Delete(
  13499. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13500. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13501. "text/plain");
  13502. });
  13503. svr_.Get("/head-test",
  13504. [](const httplib::Request &, httplib::Response &res) {
  13505. res.set_content("body for HEAD", "text/plain");
  13506. });
  13507. svr_.Options("/options",
  13508. [](const httplib::Request &, httplib::Response &res) {
  13509. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13510. });
  13511. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13512. svr_.wait_until_ready();
  13513. }
  13514. void TearDown() override {
  13515. svr_.stop();
  13516. if (thread_.joinable()) thread_.join();
  13517. }
  13518. httplib::Server svr_;
  13519. std::thread thread_;
  13520. };
  13521. // stream::Get tests
  13522. TEST_F(StreamApiTest, GetBasic) {
  13523. httplib::Client cli(HOST, PORT);
  13524. auto result = httplib::stream::Get(cli, "/hello");
  13525. ASSERT_TRUE(result.is_valid());
  13526. EXPECT_EQ(200, result.status());
  13527. EXPECT_EQ("Hello World!", read_body(result));
  13528. }
  13529. TEST_F(StreamApiTest, GetWithParams) {
  13530. httplib::Client cli(HOST, PORT);
  13531. httplib::Params params{{"foo", "bar"}};
  13532. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13533. ASSERT_TRUE(result.is_valid());
  13534. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13535. }
  13536. TEST_F(StreamApiTest, GetConnectionError) {
  13537. httplib::Client cli(HOST, 9999);
  13538. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13539. }
  13540. TEST_F(StreamApiTest, Get404) {
  13541. httplib::Client cli(HOST, PORT);
  13542. auto result = httplib::stream::Get(cli, "/nonexistent");
  13543. EXPECT_TRUE(result.is_valid());
  13544. EXPECT_EQ(404, result.status());
  13545. }
  13546. // stream::Post tests
  13547. TEST_F(StreamApiTest, PostBasic) {
  13548. httplib::Client cli(HOST, PORT);
  13549. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13550. "application/json");
  13551. ASSERT_TRUE(result.is_valid());
  13552. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13553. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13554. }
  13555. TEST_F(StreamApiTest, PostWithHeaders) {
  13556. httplib::Client cli(HOST, PORT);
  13557. httplib::Headers headers{{"X-Custom", "value"}};
  13558. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13559. "text/plain");
  13560. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13561. }
  13562. TEST_F(StreamApiTest, PostWithParams) {
  13563. httplib::Client cli(HOST, PORT);
  13564. httplib::Params params{{"k", "v"}};
  13565. auto result =
  13566. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13567. auto body = read_body(result);
  13568. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13569. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13570. }
  13571. TEST_F(StreamApiTest, PostLarge) {
  13572. httplib::Client cli(HOST, PORT);
  13573. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13574. size_t total = 0;
  13575. while (result.next()) {
  13576. total += result.size();
  13577. }
  13578. EXPECT_EQ(100u * 1024u, total);
  13579. }
  13580. // stream::Put/Patch tests
  13581. TEST_F(StreamApiTest, PutAndPatch) {
  13582. httplib::Client cli(HOST, PORT);
  13583. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13584. EXPECT_EQ("PUT:test", read_body(put));
  13585. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13586. EXPECT_EQ("PATCH:test", read_body(patch));
  13587. }
  13588. // stream::Delete tests
  13589. TEST_F(StreamApiTest, Delete) {
  13590. httplib::Client cli(HOST, PORT);
  13591. auto del1 = httplib::stream::Delete(cli, "/resource");
  13592. EXPECT_EQ("Deleted", read_body(del1));
  13593. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13594. EXPECT_EQ("Deleted:data", read_body(del2));
  13595. }
  13596. // stream::Head/Options tests
  13597. TEST_F(StreamApiTest, HeadAndOptions) {
  13598. httplib::Client cli(HOST, PORT);
  13599. auto head = httplib::stream::Head(cli, "/head-test");
  13600. EXPECT_TRUE(head.is_valid());
  13601. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13602. auto opts = httplib::stream::Options(cli, "/options");
  13603. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13604. }
  13605. // SSL stream::* tests
  13606. #ifdef CPPHTTPLIB_SSL_ENABLED
  13607. class SSLStreamApiTest : public ::testing::Test {
  13608. protected:
  13609. void SetUp() override {
  13610. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13611. res.set_content("Hello SSL!", "text/plain");
  13612. });
  13613. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13614. res.set_content(req.body, "text/plain");
  13615. });
  13616. port_ = svr_.bind_to_any_port("127.0.0.1");
  13617. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13618. svr_.wait_until_ready();
  13619. }
  13620. void TearDown() override {
  13621. svr_.stop();
  13622. if (thread_.joinable()) thread_.join();
  13623. }
  13624. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13625. std::thread thread_;
  13626. int port_ = 0;
  13627. };
  13628. TEST_F(SSLStreamApiTest, GetAndPost) {
  13629. httplib::SSLClient cli("127.0.0.1", port_);
  13630. cli.enable_server_certificate_verification(false);
  13631. auto get = httplib::stream::Get(cli, "/hello");
  13632. EXPECT_EQ("Hello SSL!", read_body(get));
  13633. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13634. EXPECT_EQ("test", read_body(post));
  13635. }
  13636. #endif
  13637. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13638. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13639. // BodyReader
  13640. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13641. // Test that read timeout during streaming is detected
  13642. // Use a large content-length response where server delays mid-stream
  13643. Server svr;
  13644. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13645. // Send a large response with delay in the middle
  13646. res.set_content_provider(
  13647. 1000, // content_length
  13648. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13649. if (offset < 100) {
  13650. // Send first 100 bytes immediately
  13651. std::string data(100, 'A');
  13652. sink.write(data.c_str(), data.size());
  13653. return true;
  13654. }
  13655. // Then delay longer than client timeout
  13656. std::this_thread::sleep_for(std::chrono::seconds(3));
  13657. std::string data(900, 'B');
  13658. sink.write(data.c_str(), data.size());
  13659. return true;
  13660. });
  13661. });
  13662. auto port = 8091;
  13663. std::thread t([&]() { svr.listen("localhost", port); });
  13664. svr.wait_until_ready();
  13665. Client cli("localhost", port);
  13666. cli.set_read_timeout(1, 0); // 1 second timeout
  13667. auto handle = cli.open_stream("GET", "/slow-stream");
  13668. ASSERT_TRUE(handle.is_valid());
  13669. char buf[256];
  13670. ssize_t total = 0;
  13671. ssize_t n;
  13672. bool got_error = false;
  13673. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13674. total += n;
  13675. }
  13676. if (n < 0) {
  13677. got_error = true;
  13678. // Should be timeout or read error
  13679. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13680. handle.get_read_error() == Error::Read)
  13681. << "Actual error: " << to_string(handle.get_read_error());
  13682. }
  13683. // Either we got an error, or we got less data than expected
  13684. EXPECT_TRUE(got_error || total < 1000)
  13685. << "Expected timeout but got all " << total << " bytes";
  13686. svr.stop();
  13687. t.join();
  13688. }
  13689. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13690. // Test connection closed detection via BodyReader
  13691. Server svr;
  13692. std::atomic<bool> close_now{false};
  13693. svr.Get("/will-close", [&](const Request &, Response &res) {
  13694. res.set_content_provider(
  13695. 10000, // Large content_length that we won't fully send
  13696. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13697. if (offset < 100) {
  13698. std::string data(100, 'X');
  13699. sink.write(data.c_str(), data.size());
  13700. return true;
  13701. }
  13702. // Wait for signal then abort
  13703. while (!close_now) {
  13704. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13705. }
  13706. return false; // Abort - server will close connection
  13707. });
  13708. });
  13709. auto port = 8092;
  13710. std::thread t([&]() { svr.listen("localhost", port); });
  13711. svr.wait_until_ready();
  13712. Client cli("localhost", port);
  13713. auto handle = cli.open_stream("GET", "/will-close");
  13714. ASSERT_TRUE(handle.is_valid());
  13715. char buf[256];
  13716. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13717. EXPECT_GT(n, 0) << "First read should succeed";
  13718. // Signal server to close
  13719. close_now = true;
  13720. // Keep reading until error or EOF
  13721. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13722. // Keep reading
  13723. }
  13724. // Should get an error since content_length wasn't satisfied
  13725. if (n < 0) {
  13726. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13727. handle.get_read_error() == Error::Read)
  13728. << "Actual error: " << to_string(handle.get_read_error());
  13729. }
  13730. svr.stop();
  13731. t.join();
  13732. }
  13733. #ifdef CPPHTTPLIB_SSL_ENABLED
  13734. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13735. // Test that read timeout during SSL streaming is detected
  13736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13737. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13738. res.set_content_provider(
  13739. 1000, "text/plain",
  13740. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13741. if (offset < 100) {
  13742. std::string data(100, 'A');
  13743. sink.write(data.c_str(), data.size());
  13744. return true;
  13745. }
  13746. std::this_thread::sleep_for(std::chrono::seconds(3));
  13747. std::string data(900, 'B');
  13748. sink.write(data.c_str(), data.size());
  13749. return true;
  13750. });
  13751. });
  13752. auto port = 8093;
  13753. std::thread t([&]() { svr.listen("localhost", port); });
  13754. svr.wait_until_ready();
  13755. SSLClient cli("localhost", port);
  13756. cli.enable_server_certificate_verification(false);
  13757. cli.set_read_timeout(1, 0); // 1 second timeout
  13758. auto handle = cli.open_stream("GET", "/slow-stream");
  13759. ASSERT_TRUE(handle.is_valid());
  13760. char buf[256];
  13761. ssize_t total = 0;
  13762. ssize_t n;
  13763. bool got_error = false;
  13764. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13765. total += n;
  13766. }
  13767. if (n < 0) {
  13768. got_error = true;
  13769. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13770. handle.get_read_error() == Error::Read)
  13771. << "Actual error: " << to_string(handle.get_read_error());
  13772. }
  13773. EXPECT_TRUE(got_error || total < 1000)
  13774. << "Expected timeout but got all " << total << " bytes";
  13775. svr.stop();
  13776. t.join();
  13777. }
  13778. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13779. // Test SSL connection closed detection
  13780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13781. std::atomic<bool> close_now{false};
  13782. svr.Get("/will-close", [&](const Request &, Response &res) {
  13783. res.set_content_provider(
  13784. 10000, "text/plain",
  13785. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13786. if (offset < 100) {
  13787. std::string data(100, 'X');
  13788. sink.write(data.c_str(), data.size());
  13789. return true;
  13790. }
  13791. while (!close_now) {
  13792. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13793. }
  13794. return false;
  13795. });
  13796. });
  13797. auto port = 8094;
  13798. std::thread t([&]() { svr.listen("localhost", port); });
  13799. svr.wait_until_ready();
  13800. SSLClient cli("localhost", port);
  13801. cli.enable_server_certificate_verification(false);
  13802. auto handle = cli.open_stream("GET", "/will-close");
  13803. ASSERT_TRUE(handle.is_valid());
  13804. char buf[256];
  13805. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13806. EXPECT_GT(n, 0);
  13807. // Signal server to close
  13808. close_now = true;
  13809. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13810. // Keep reading
  13811. }
  13812. if (n < 0) {
  13813. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13814. handle.get_read_error() == Error::Read)
  13815. << "Actual error: " << to_string(handle.get_read_error());
  13816. }
  13817. svr.stop();
  13818. t.join();
  13819. }
  13820. #endif
  13821. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13822. using namespace httplib;
  13823. // Create a test file
  13824. const char *fname = "etag_testfile.txt";
  13825. const char *content = "etag-content";
  13826. {
  13827. std::ofstream ofs(fname);
  13828. ofs << content;
  13829. ASSERT_TRUE(ofs.good());
  13830. }
  13831. Server svr;
  13832. svr.set_mount_point("/static", ".");
  13833. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13834. svr.wait_until_ready();
  13835. Client cli(HOST, PORT);
  13836. // First request: should get 200 with ETag header
  13837. auto res1 = cli.Get("/static/etag_testfile.txt");
  13838. ASSERT_TRUE(res1);
  13839. ASSERT_EQ(200, res1->status);
  13840. ASSERT_TRUE(res1->has_header("ETag"));
  13841. std::string etag = res1->get_header_value("ETag");
  13842. EXPECT_FALSE(etag.empty());
  13843. // Verify ETag format: W/"hex-hex"
  13844. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13845. EXPECT_EQ('W', etag[0]);
  13846. EXPECT_EQ('/', etag[1]);
  13847. EXPECT_EQ('"', etag[2]);
  13848. EXPECT_EQ('"', etag.back());
  13849. // Exact match: expect 304 Not Modified
  13850. Headers h2 = {{"If-None-Match", etag}};
  13851. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13852. ASSERT_TRUE(res2);
  13853. EXPECT_EQ(304, res2->status);
  13854. // Wildcard match: expect 304 Not Modified
  13855. Headers h3 = {{"If-None-Match", "*"}};
  13856. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13857. ASSERT_TRUE(res3);
  13858. EXPECT_EQ(304, res3->status);
  13859. // Non-matching ETag: expect 200
  13860. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13861. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13862. ASSERT_TRUE(res4);
  13863. EXPECT_EQ(200, res4->status);
  13864. // Multiple ETags with one matching: expect 304
  13865. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13866. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13867. ASSERT_TRUE(res5);
  13868. EXPECT_EQ(304, res5->status);
  13869. svr.stop();
  13870. t.join();
  13871. std::remove(fname);
  13872. }
  13873. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13874. using namespace httplib;
  13875. Server svr;
  13876. svr.set_mount_point("/static", ".");
  13877. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13878. svr.wait_until_ready();
  13879. Client cli(HOST, PORT);
  13880. // Send If-None-Match: * to a non-existent file
  13881. Headers h = {{"If-None-Match", "*"}};
  13882. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13883. ASSERT_TRUE(res);
  13884. EXPECT_EQ(404, res->status);
  13885. svr.stop();
  13886. t.join();
  13887. }
  13888. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13889. using namespace httplib;
  13890. // Create a test file
  13891. const char *fname = "etag_boundary_testfile.txt";
  13892. const char *content = "boundary-test";
  13893. {
  13894. std::ofstream ofs(fname);
  13895. ofs << content;
  13896. ASSERT_TRUE(ofs.good());
  13897. }
  13898. Server svr;
  13899. svr.set_mount_point("/static", ".");
  13900. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13901. svr.wait_until_ready();
  13902. Client cli(HOST, PORT);
  13903. // Get the actual ETag
  13904. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13905. ASSERT_TRUE(res1);
  13906. ASSERT_EQ(200, res1->status);
  13907. ASSERT_TRUE(res1->has_header("ETag"));
  13908. std::string etag = res1->get_header_value("ETag");
  13909. // Test 1: Very long ETag value (longer than actual ETag)
  13910. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13911. Headers h1 = {{"If-None-Match", "W/"
  13912. "\"very-long-etag-value-that-is-much-longer-"
  13913. "than-the-actual-etag-value\""}};
  13914. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13915. ASSERT_TRUE(res2);
  13916. EXPECT_EQ(200, res2->status); // Should not match
  13917. // Test 2: Long string followed by wildcard
  13918. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13919. // string)
  13920. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13921. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13922. ASSERT_TRUE(res3);
  13923. EXPECT_EQ(304, res3->status); // Should match on "*"
  13924. // Test 3: Wildcard followed by long string
  13925. // Should match on "*" immediately and return 304
  13926. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13927. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13928. ASSERT_TRUE(res4);
  13929. EXPECT_EQ(304, res4->status); // Should match on "*"
  13930. // Test 4: Multiple long non-matching values
  13931. // Should NOT match and return 200 (test that all comparisons are safe)
  13932. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13933. "W/\"second-long-non-matching-value\", "
  13934. "W/\"third-long-non-matching-value\""}};
  13935. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13936. ASSERT_TRUE(res5);
  13937. EXPECT_EQ(200, res5->status); // Should not match
  13938. // Test 5: Single character that is not "*" (edge case)
  13939. Headers h5 = {{"If-None-Match", "X"}};
  13940. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13941. ASSERT_TRUE(res6);
  13942. EXPECT_EQ(200, res6->status); // Should not match
  13943. svr.stop();
  13944. t.join();
  13945. std::remove(fname);
  13946. }
  13947. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13948. using namespace httplib;
  13949. // Create a test file
  13950. const char *fname = "ims_testfile.txt";
  13951. const char *content = "if-modified-since-test";
  13952. {
  13953. std::ofstream ofs(fname);
  13954. ofs << content;
  13955. ASSERT_TRUE(ofs.good());
  13956. }
  13957. Server svr;
  13958. svr.set_mount_point("/static", ".");
  13959. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13960. svr.wait_until_ready();
  13961. Client cli(HOST, PORT);
  13962. // First request: should get 200 with Last-Modified header
  13963. auto res1 = cli.Get("/static/ims_testfile.txt");
  13964. ASSERT_TRUE(res1);
  13965. ASSERT_EQ(200, res1->status);
  13966. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13967. std::string last_modified = res1->get_header_value("Last-Modified");
  13968. EXPECT_FALSE(last_modified.empty());
  13969. // If-Modified-Since with same time: expect 304
  13970. Headers h2 = {{"If-Modified-Since", last_modified}};
  13971. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13972. ASSERT_TRUE(res2);
  13973. EXPECT_EQ(304, res2->status);
  13974. // If-Modified-Since with future time: expect 304
  13975. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13976. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13977. ASSERT_TRUE(res3);
  13978. EXPECT_EQ(304, res3->status);
  13979. // If-Modified-Since with past time: expect 200
  13980. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13981. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13982. ASSERT_TRUE(res4);
  13983. EXPECT_EQ(200, res4->status);
  13984. // If-None-Match takes precedence over If-Modified-Since
  13985. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13986. ASSERT_TRUE(res1->has_header("ETag"));
  13987. std::string etag = res1->get_header_value("ETag");
  13988. Headers h5 = {{"If-None-Match", etag},
  13989. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13990. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13991. ASSERT_TRUE(res5);
  13992. EXPECT_EQ(304, res5->status);
  13993. svr.stop();
  13994. t.join();
  13995. std::remove(fname);
  13996. }
  13997. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13998. using namespace httplib;
  13999. Server svr;
  14000. // Endpoint that returns compressible content
  14001. svr.Get("/compressible", [](const Request &, Response &res) {
  14002. // Return a large enough body to trigger compression
  14003. std::string body(1000, 'a');
  14004. res.set_content(body, "text/plain");
  14005. });
  14006. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14007. svr.wait_until_ready();
  14008. Client cli(HOST, PORT);
  14009. // Request with gzip support: should get Vary header when compressed
  14010. cli.set_compress(true);
  14011. auto res1 = cli.Get("/compressible");
  14012. ASSERT_TRUE(res1);
  14013. EXPECT_EQ(200, res1->status);
  14014. // If Content-Encoding is set, Vary should also be set
  14015. if (res1->has_header("Content-Encoding")) {
  14016. EXPECT_TRUE(res1->has_header("Vary"));
  14017. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14018. }
  14019. // Request without Accept-Encoding header: should not have compression
  14020. Headers h_no_compress;
  14021. auto res2 = cli.Get("/compressible", h_no_compress);
  14022. ASSERT_TRUE(res2);
  14023. EXPECT_EQ(200, res2->status);
  14024. // Verify Vary header is present when compression is applied
  14025. // (the exact behavior depends on server configuration)
  14026. svr.stop();
  14027. t.join();
  14028. }
  14029. TEST(ETagTest, IfRangeWithETag) {
  14030. using namespace httplib;
  14031. // Create a test file with known content
  14032. const char *fname = "if_range_testfile.txt";
  14033. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14034. {
  14035. std::ofstream ofs(fname);
  14036. ofs << content;
  14037. ASSERT_TRUE(ofs.good());
  14038. }
  14039. Server svr;
  14040. svr.set_mount_point("/static", ".");
  14041. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14042. svr.wait_until_ready();
  14043. Client cli(HOST, PORT);
  14044. // First request: get ETag
  14045. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14046. ASSERT_TRUE(res1);
  14047. ASSERT_EQ(200, res1->status);
  14048. ASSERT_TRUE(res1->has_header("ETag"));
  14049. std::string etag = res1->get_header_value("ETag");
  14050. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14051. // Since our server generates weak ETags (W/"..."), If-Range with our
  14052. // ETag should NOT result in partial content - it should return full content.
  14053. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14054. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14055. ASSERT_TRUE(res2);
  14056. // Weak ETag in If-Range -> full content (200), not partial (206)
  14057. EXPECT_EQ(200, res2->status);
  14058. EXPECT_EQ(content, res2->body);
  14059. EXPECT_FALSE(res2->has_header("Content-Range"));
  14060. // Range request with non-matching If-Range (ETag): should get 200 (full
  14061. // content)
  14062. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14063. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14064. ASSERT_TRUE(res3);
  14065. EXPECT_EQ(200, res3->status);
  14066. EXPECT_EQ(content, res3->body);
  14067. EXPECT_FALSE(res3->has_header("Content-Range"));
  14068. // Range request with strong ETag (hypothetical - our server doesn't generate
  14069. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14070. // should return full content)
  14071. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14072. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14073. ASSERT_TRUE(res4);
  14074. EXPECT_EQ(200, res4->status);
  14075. EXPECT_EQ(content, res4->body);
  14076. EXPECT_FALSE(res4->has_header("Content-Range"));
  14077. svr.stop();
  14078. t.join();
  14079. std::remove(fname);
  14080. }
  14081. TEST(ETagTest, IfRangeWithDate) {
  14082. using namespace httplib;
  14083. // Create a test file
  14084. const char *fname = "if_range_date_testfile.txt";
  14085. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14086. {
  14087. std::ofstream ofs(fname);
  14088. ofs << content;
  14089. ASSERT_TRUE(ofs.good());
  14090. }
  14091. Server svr;
  14092. svr.set_mount_point("/static", ".");
  14093. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14094. svr.wait_until_ready();
  14095. Client cli(HOST, PORT);
  14096. // First request: get Last-Modified
  14097. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14098. ASSERT_TRUE(res1);
  14099. ASSERT_EQ(200, res1->status);
  14100. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14101. std::string last_modified = res1->get_header_value("Last-Modified");
  14102. // Range request with matching If-Range (date): should get 206
  14103. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14104. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14105. ASSERT_TRUE(res2);
  14106. EXPECT_EQ(206, res2->status);
  14107. EXPECT_EQ("FGHIJ", res2->body);
  14108. // Range request with old If-Range date: should get 200 (full content)
  14109. Headers h3 = {{"Range", "bytes=5-9"},
  14110. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14111. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14112. ASSERT_TRUE(res3);
  14113. EXPECT_EQ(200, res3->status);
  14114. EXPECT_EQ(content, res3->body);
  14115. // Range request with future If-Range date: should get 206
  14116. Headers h4 = {{"Range", "bytes=0-4"},
  14117. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14118. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14119. ASSERT_TRUE(res4);
  14120. EXPECT_EQ(206, res4->status);
  14121. EXPECT_EQ("ABCDE", res4->body);
  14122. svr.stop();
  14123. t.join();
  14124. std::remove(fname);
  14125. }
  14126. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14127. using namespace httplib;
  14128. const char *fname = "etag_malformed.txt";
  14129. const char *content = "malformed-etag";
  14130. {
  14131. std::ofstream ofs(fname);
  14132. ofs << content;
  14133. ASSERT_TRUE(ofs.good());
  14134. }
  14135. Server svr;
  14136. svr.set_mount_point("/static", ".");
  14137. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14138. svr.wait_until_ready();
  14139. Client cli(HOST, PORT);
  14140. // baseline: should get 200 and an ETag
  14141. auto res1 = cli.Get("/static/etag_malformed.txt");
  14142. ASSERT_TRUE(res1);
  14143. ASSERT_EQ(200, res1->status);
  14144. ASSERT_TRUE(res1->has_header("ETag"));
  14145. // Malformed ETag value (missing quotes) should be treated as non-matching
  14146. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14147. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14148. ASSERT_TRUE(res_bad);
  14149. EXPECT_EQ(200, res_bad->status);
  14150. // Whitespace-only header value should be considered invalid / non-matching
  14151. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14152. "Host: localhost\r\n"
  14153. "If-None-Match: \r\n"
  14154. "Connection: close\r\n"
  14155. "\r\n";
  14156. std::string out;
  14157. ASSERT_TRUE(send_request(5, raw_req, &out));
  14158. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14159. svr.stop();
  14160. t.join();
  14161. std::remove(fname);
  14162. }
  14163. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14164. using namespace httplib;
  14165. const char *fname = "ims_invalid_format.txt";
  14166. const char *content = "ims-bad-format";
  14167. {
  14168. std::ofstream ofs(fname);
  14169. ofs << content;
  14170. ASSERT_TRUE(ofs.good());
  14171. }
  14172. Server svr;
  14173. svr.set_mount_point("/static", ".");
  14174. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14175. svr.wait_until_ready();
  14176. Client cli(HOST, PORT);
  14177. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14178. ASSERT_TRUE(res1);
  14179. ASSERT_EQ(200, res1->status);
  14180. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14181. // If-Modified-Since with invalid format should not result in 304
  14182. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14183. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14184. ASSERT_TRUE(res_bad);
  14185. EXPECT_EQ(200, res_bad->status);
  14186. // If-Range with invalid date format should be treated as mismatch -> full
  14187. // content (200)
  14188. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14189. {"If-Range", "invalid-date"}};
  14190. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14191. ASSERT_TRUE(res_ifrange);
  14192. EXPECT_EQ(200, res_ifrange->status);
  14193. svr.stop();
  14194. t.join();
  14195. std::remove(fname);
  14196. }
  14197. TEST(ETagTest, IfRangeWithMalformedETag) {
  14198. using namespace httplib;
  14199. const char *fname = "ifrange_malformed.txt";
  14200. const std::string content = "0123456789";
  14201. {
  14202. std::ofstream ofs(fname);
  14203. ofs << content;
  14204. ASSERT_TRUE(ofs.good());
  14205. }
  14206. Server svr;
  14207. svr.set_mount_point("/static", ".");
  14208. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14209. svr.wait_until_ready();
  14210. Client cli(HOST, PORT);
  14211. // First request: get ETag
  14212. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14213. ASSERT_TRUE(res1);
  14214. ASSERT_EQ(200, res1->status);
  14215. ASSERT_TRUE(res1->has_header("ETag"));
  14216. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14217. // full content (200)
  14218. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14219. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14220. ASSERT_TRUE(res2);
  14221. EXPECT_EQ(200, res2->status);
  14222. EXPECT_EQ(content, res2->body);
  14223. svr.stop();
  14224. t.join();
  14225. std::remove(fname);
  14226. }
  14227. TEST(ETagTest, ExtremeLargeDateValues) {
  14228. using namespace httplib;
  14229. const char *fname = "ims_extreme_date.txt";
  14230. const char *content = "ims-extreme-date";
  14231. {
  14232. std::ofstream ofs(fname);
  14233. ofs << content;
  14234. ASSERT_TRUE(ofs.good());
  14235. }
  14236. Server svr;
  14237. svr.set_mount_point("/static", ".");
  14238. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14239. svr.wait_until_ready();
  14240. Client cli(HOST, PORT);
  14241. auto res1 = cli.Get(std::string("/static/") + fname);
  14242. ASSERT_TRUE(res1);
  14243. ASSERT_EQ(200, res1->status);
  14244. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14245. // Extremely large year that may overflow date parsing routines.
  14246. Headers h_large_date = {
  14247. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14248. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14249. ASSERT_TRUE(res_bad);
  14250. // Expect server to treat this as invalid/mismatch and return full content
  14251. EXPECT_EQ(200, res_bad->status);
  14252. // If-Range with extremely large date should be treated as mismatch -> full
  14253. // content (200)
  14254. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14255. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14256. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14257. ASSERT_TRUE(res_ifrange);
  14258. EXPECT_EQ(200, res_ifrange->status);
  14259. svr.stop();
  14260. t.join();
  14261. std::remove(fname);
  14262. }
  14263. TEST(ETagTest, NegativeFileModificationTime) {
  14264. using namespace httplib;
  14265. const char *fname = "ims_negative_mtime.txt";
  14266. const std::string content = "negative-mtime";
  14267. {
  14268. std::ofstream ofs(fname);
  14269. ofs << content;
  14270. ASSERT_TRUE(ofs.good());
  14271. }
  14272. // Try to set file mtime to a negative value. This may fail on some
  14273. // platforms/filesystems; if it fails, the test will still verify server
  14274. // behaves safely by performing a regular conditional request.
  14275. #if defined(__APPLE__) || defined(__linux__)
  14276. bool set_negative = false;
  14277. do {
  14278. struct timeval times[2];
  14279. // access time: now
  14280. times[0].tv_sec = time(nullptr);
  14281. times[0].tv_usec = 0;
  14282. // modification time: negative (e.g., -1)
  14283. times[1].tv_sec = -1;
  14284. times[1].tv_usec = 0;
  14285. if (utimes(fname, times) == 0) { set_negative = true; }
  14286. } while (0);
  14287. #else
  14288. bool set_negative = false;
  14289. #endif
  14290. Server svr;
  14291. svr.set_mount_point("/static", ".");
  14292. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14293. svr.wait_until_ready();
  14294. Client cli(HOST, PORT);
  14295. auto res1 = cli.Get(std::string("/static/") + fname);
  14296. ASSERT_TRUE(res1);
  14297. ASSERT_EQ(200, res1->status);
  14298. bool has_last_modified = res1->has_header("Last-Modified");
  14299. std::string last_modified;
  14300. if (has_last_modified) {
  14301. last_modified = res1->get_header_value("Last-Modified");
  14302. }
  14303. if (set_negative) {
  14304. // If we successfully set a negative mtime, ensure server returns a
  14305. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14306. // with an old date and ensure server handles it without crash.
  14307. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14308. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14309. ASSERT_TRUE(res2);
  14310. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14311. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14312. } else {
  14313. // Could not set negative mtime on this platform; fall back to verifying
  14314. // that normal invalid/malformed dates are treated safely (non-304).
  14315. Headers h_bad_date = {
  14316. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14317. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14318. ASSERT_TRUE(res_bad);
  14319. EXPECT_EQ(200, res_bad->status);
  14320. }
  14321. svr.stop();
  14322. t.join();
  14323. std::remove(fname);
  14324. }
  14325. //==============================================================================
  14326. // SSE Parsing Tests
  14327. //==============================================================================
  14328. class SSEParsingTest : public ::testing::Test {
  14329. protected:
  14330. // Test helper that mimics SSE parsing behavior
  14331. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14332. int &retry_ms) {
  14333. // Blank line signals end of event
  14334. if (line.empty() || line == "\r") { return true; }
  14335. // Lines starting with ':' are comments (ignored)
  14336. if (!line.empty() && line[0] == ':') { return false; }
  14337. // Find the colon separator
  14338. auto colon_pos = line.find(':');
  14339. if (colon_pos == std::string::npos) {
  14340. // Line with no colon is treated as field name with empty value
  14341. return false;
  14342. }
  14343. std::string field = line.substr(0, colon_pos);
  14344. std::string value;
  14345. // Value starts after colon, skip optional single space
  14346. if (colon_pos + 1 < line.size()) {
  14347. size_t value_start = colon_pos + 1;
  14348. if (line[value_start] == ' ') { value_start++; }
  14349. value = line.substr(value_start);
  14350. // Remove trailing \r if present
  14351. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14352. }
  14353. // Handle known fields
  14354. if (field == "event") {
  14355. msg.event = value;
  14356. } else if (field == "data") {
  14357. // Multiple data lines are concatenated with newlines
  14358. if (!msg.data.empty()) { msg.data += "\n"; }
  14359. msg.data += value;
  14360. } else if (field == "id") {
  14361. // Empty id is valid (clears the last event ID)
  14362. msg.id = value;
  14363. } else if (field == "retry") {
  14364. // Parse retry interval in milliseconds
  14365. {
  14366. int v = 0;
  14367. auto res =
  14368. detail::from_chars(value.data(), value.data() + value.size(), v);
  14369. if (res.ec == std::errc{}) { retry_ms = v; }
  14370. }
  14371. }
  14372. // Unknown fields are ignored per SSE spec
  14373. return false;
  14374. }
  14375. };
  14376. // Test: Single-line data
  14377. TEST_F(SSEParsingTest, SingleLineData) {
  14378. sse::SSEMessage msg;
  14379. int retry_ms = 3000;
  14380. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14381. EXPECT_EQ(msg.data, "hello");
  14382. EXPECT_EQ(msg.event, "message");
  14383. // Blank line ends event
  14384. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14385. }
  14386. // Test: Multi-line data
  14387. TEST_F(SSEParsingTest, MultiLineData) {
  14388. sse::SSEMessage msg;
  14389. int retry_ms = 3000;
  14390. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14391. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14392. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14393. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14394. }
  14395. // Test: Custom event types
  14396. TEST_F(SSEParsingTest, CustomEventType) {
  14397. sse::SSEMessage msg;
  14398. int retry_ms = 3000;
  14399. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14400. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14401. EXPECT_EQ(msg.event, "update");
  14402. EXPECT_EQ(msg.data, "payload");
  14403. }
  14404. // Test: Event ID handling
  14405. TEST_F(SSEParsingTest, EventIdHandling) {
  14406. sse::SSEMessage msg;
  14407. int retry_ms = 3000;
  14408. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14409. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14410. EXPECT_EQ(msg.id, "12345");
  14411. }
  14412. // Test: Empty event ID (clears last event ID)
  14413. TEST_F(SSEParsingTest, EmptyEventId) {
  14414. sse::SSEMessage msg;
  14415. msg.id = "previous";
  14416. int retry_ms = 3000;
  14417. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14418. EXPECT_EQ(msg.id, "");
  14419. }
  14420. // Test: Retry field parsing
  14421. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14422. sse::SSEMessage msg;
  14423. int retry_ms = 3000;
  14424. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14425. EXPECT_EQ(retry_ms, 5000);
  14426. }
  14427. // Test: Invalid retry value
  14428. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14429. sse::SSEMessage msg;
  14430. int retry_ms = 3000;
  14431. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14432. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14433. }
  14434. // Test: Comments (lines starting with :)
  14435. TEST_F(SSEParsingTest, CommentsIgnored) {
  14436. sse::SSEMessage msg;
  14437. int retry_ms = 3000;
  14438. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14439. EXPECT_EQ(msg.data, "");
  14440. EXPECT_EQ(msg.event, "message");
  14441. }
  14442. // Test: Colon in value
  14443. TEST_F(SSEParsingTest, ColonInValue) {
  14444. sse::SSEMessage msg;
  14445. int retry_ms = 3000;
  14446. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14447. EXPECT_EQ(msg.data, "hello:world:test");
  14448. }
  14449. // Test: Line with no colon (field name only)
  14450. TEST_F(SSEParsingTest, FieldNameOnly) {
  14451. sse::SSEMessage msg;
  14452. int retry_ms = 3000;
  14453. // According to SSE spec, this is treated as field name with empty value
  14454. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14455. // Since we don't recognize "data" without colon, data should be empty
  14456. EXPECT_EQ(msg.data, "");
  14457. }
  14458. // Test: Trailing \r handling
  14459. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14460. sse::SSEMessage msg;
  14461. int retry_ms = 3000;
  14462. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14463. EXPECT_EQ(msg.data, "hello");
  14464. }
  14465. // Test: Unknown fields ignored
  14466. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14467. sse::SSEMessage msg;
  14468. int retry_ms = 3000;
  14469. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14470. EXPECT_EQ(msg.data, "");
  14471. EXPECT_EQ(msg.event, "message");
  14472. }
  14473. // Test: Space after colon is optional
  14474. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14475. sse::SSEMessage msg1, msg2;
  14476. int retry_ms = 3000;
  14477. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14478. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14479. EXPECT_EQ(msg1.data, "hello");
  14480. EXPECT_EQ(msg2.data, "hello");
  14481. }
  14482. // Test: SSEMessage clear
  14483. TEST_F(SSEParsingTest, MessageClear) {
  14484. sse::SSEMessage msg;
  14485. msg.event = "custom";
  14486. msg.data = "some data";
  14487. msg.id = "123";
  14488. msg.clear();
  14489. EXPECT_EQ(msg.event, "message");
  14490. EXPECT_EQ(msg.data, "");
  14491. EXPECT_EQ(msg.id, "");
  14492. }
  14493. // Test: Complete event parsing
  14494. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14495. sse::SSEMessage msg;
  14496. int retry_ms = 3000;
  14497. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14498. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14499. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14500. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14501. // Blank line ends event
  14502. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14503. EXPECT_EQ(msg.event, "notification");
  14504. EXPECT_EQ(msg.id, "evt-42");
  14505. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14506. EXPECT_EQ(retry_ms, 1000);
  14507. }
  14508. //==============================================================================
  14509. // Integration Tests with Server
  14510. //==============================================================================
  14511. class SSEIntegrationTest : public ::testing::Test {
  14512. protected:
  14513. void SetUp() override {
  14514. stop_server_.store(false);
  14515. events_.clear();
  14516. server_ = httplib::detail::make_unique<Server>();
  14517. setup_server();
  14518. start_server();
  14519. }
  14520. void TearDown() override {
  14521. stop_server_.store(true);
  14522. event_cv_.notify_all();
  14523. server_->stop();
  14524. if (server_thread_.joinable()) { server_thread_.join(); }
  14525. }
  14526. void setup_server() {
  14527. // Simple SSE endpoint
  14528. server_->Get("/events", [this](const Request &req, Response &res) {
  14529. auto last_id = req.get_header_value("Last-Event-ID");
  14530. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14531. res.set_chunked_content_provider(
  14532. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14533. std::unique_lock<std::mutex> lock(event_mutex_);
  14534. if (event_cv_.wait_for(
  14535. lock, std::chrono::milliseconds(200), [this] {
  14536. return !events_.empty() || stop_server_.load();
  14537. })) {
  14538. if (stop_server_.load()) { return false; }
  14539. if (!events_.empty()) {
  14540. std::string event = events_.front();
  14541. events_.erase(events_.begin());
  14542. sink.write(event.data(), event.size());
  14543. return true;
  14544. }
  14545. }
  14546. return !stop_server_.load();
  14547. });
  14548. });
  14549. // Endpoint that returns error
  14550. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14551. res.status = 500;
  14552. res.set_content("Internal Server Error", "text/plain");
  14553. });
  14554. // Endpoint for custom event types
  14555. server_->Get("/custom-events", [](const Request &, Response &res) {
  14556. res.set_chunked_content_provider(
  14557. "text/event-stream", [](size_t offset, DataSink &sink) {
  14558. if (offset == 0) {
  14559. std::string event = "event: update\ndata: updated\n\n"
  14560. "event: delete\ndata: deleted\n\n";
  14561. sink.write(event.data(), event.size());
  14562. }
  14563. return false; // End stream after sending
  14564. });
  14565. });
  14566. }
  14567. void start_server() {
  14568. port_ = server_->bind_to_any_port(HOST);
  14569. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14570. // Wait for server to start
  14571. while (!server_->is_running()) {
  14572. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14573. }
  14574. }
  14575. int get_port() const { return port_; }
  14576. void send_event(const std::string &event) {
  14577. std::lock_guard<std::mutex> lock(event_mutex_);
  14578. events_.push_back(event);
  14579. event_cv_.notify_all();
  14580. }
  14581. std::unique_ptr<Server> server_;
  14582. std::thread server_thread_;
  14583. std::mutex event_mutex_;
  14584. std::condition_variable event_cv_;
  14585. std::vector<std::string> events_;
  14586. std::atomic<bool> stop_server_{false};
  14587. std::string last_received_event_id_;
  14588. int port_ = 0;
  14589. };
  14590. // Test: Successful connection and on_open callback
  14591. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14592. // Add a simple endpoint that sends one event and closes
  14593. server_->Get("/simple-event", [](const Request &, Response &res) {
  14594. res.set_chunked_content_provider(
  14595. "text/event-stream", [](size_t offset, DataSink &sink) {
  14596. if (offset == 0) {
  14597. std::string event = "data: hello\n\n";
  14598. sink.write(event.data(), event.size());
  14599. }
  14600. return false; // Close stream after sending
  14601. });
  14602. });
  14603. Client client("localhost", get_port());
  14604. sse::SSEClient sse(client, "/simple-event");
  14605. std::atomic<bool> open_called{false};
  14606. std::atomic<bool> message_received{false};
  14607. sse.on_open([&open_called]() { open_called.store(true); });
  14608. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14609. if (msg.data == "hello") { message_received.store(true); }
  14610. });
  14611. sse.set_reconnect_interval(100);
  14612. sse.set_max_reconnect_attempts(1);
  14613. // Start async
  14614. sse.start_async();
  14615. // Wait for message to be processed
  14616. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14617. sse.stop();
  14618. EXPECT_TRUE(open_called.load());
  14619. EXPECT_TRUE(message_received.load());
  14620. }
  14621. // Test: on_message callback
  14622. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14623. // Endpoint that sends multiple events then closes
  14624. server_->Get("/multi-event", [](const Request &, Response &res) {
  14625. res.set_chunked_content_provider(
  14626. "text/event-stream", [](size_t offset, DataSink &sink) {
  14627. if (offset == 0) {
  14628. std::string events = "data: message1\n\ndata: message2\n\n";
  14629. sink.write(events.data(), events.size());
  14630. }
  14631. return false;
  14632. });
  14633. });
  14634. Client client("localhost", get_port());
  14635. sse::SSEClient sse(client, "/multi-event");
  14636. std::vector<std::string> received_messages;
  14637. std::mutex messages_mutex;
  14638. sse.on_message([&](const sse::SSEMessage &msg) {
  14639. std::lock_guard<std::mutex> lock(messages_mutex);
  14640. received_messages.push_back(msg.data);
  14641. });
  14642. sse.set_reconnect_interval(100);
  14643. sse.set_max_reconnect_attempts(1);
  14644. sse.start_async();
  14645. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14646. sse.stop();
  14647. std::lock_guard<std::mutex> lock(messages_mutex);
  14648. EXPECT_GE(received_messages.size(), 2u);
  14649. if (received_messages.size() >= 2) {
  14650. EXPECT_EQ(received_messages[0], "message1");
  14651. EXPECT_EQ(received_messages[1], "message2");
  14652. }
  14653. }
  14654. // Test: on_event for specific types
  14655. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14656. Client client("localhost", get_port());
  14657. sse::SSEClient sse(client, "/custom-events");
  14658. std::atomic<bool> update_received{false};
  14659. std::atomic<bool> delete_received{false};
  14660. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14661. if (msg.data == "updated") { update_received.store(true); }
  14662. });
  14663. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14664. if (msg.data == "deleted") { delete_received.store(true); }
  14665. });
  14666. sse.set_max_reconnect_attempts(1);
  14667. sse.start_async();
  14668. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14669. sse.stop();
  14670. EXPECT_TRUE(update_received.load());
  14671. EXPECT_TRUE(delete_received.load());
  14672. }
  14673. // Test: on_error callback on connection failure
  14674. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14675. // Connect to a non-existent port
  14676. Client client("localhost", 59999);
  14677. sse::SSEClient sse(client, "/events");
  14678. std::atomic<bool> error_called{false};
  14679. Error received_error = Error::Success;
  14680. sse.on_error([&](Error err) {
  14681. error_called.store(true);
  14682. received_error = err;
  14683. });
  14684. sse.set_reconnect_interval(50);
  14685. sse.set_max_reconnect_attempts(1);
  14686. sse.start_async();
  14687. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14688. sse.stop();
  14689. EXPECT_TRUE(error_called.load());
  14690. EXPECT_NE(received_error, Error::Success);
  14691. }
  14692. // Test: Last-Event-ID header sent on reconnect
  14693. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14694. // Endpoint that sends event with ID
  14695. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14696. res.set_chunked_content_provider(
  14697. "text/event-stream", [](size_t offset, DataSink &sink) {
  14698. if (offset == 0) {
  14699. std::string event = "id: evt-123\ndata: test\n\n";
  14700. sink.write(event.data(), event.size());
  14701. }
  14702. return false;
  14703. });
  14704. });
  14705. Client client("localhost", get_port());
  14706. sse::SSEClient sse(client, "/event-with-id");
  14707. std::atomic<bool> id_received{false};
  14708. sse.on_message([&](const sse::SSEMessage &msg) {
  14709. if (!msg.id.empty()) { id_received.store(true); }
  14710. });
  14711. sse.set_reconnect_interval(100);
  14712. sse.set_max_reconnect_attempts(1);
  14713. sse.start_async();
  14714. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14715. sse.stop();
  14716. EXPECT_TRUE(id_received.load());
  14717. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14718. }
  14719. // Test: Manual stop
  14720. TEST_F(SSEIntegrationTest, ManualStop) {
  14721. // Endpoint that sends one event and stays open briefly
  14722. std::atomic<bool> handler_running{true};
  14723. server_->Get("/stay-open", [&handler_running](const Request &,
  14724. Response &res) {
  14725. res.set_chunked_content_provider(
  14726. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14727. if (offset == 0) {
  14728. std::string event = "data: connected\n\n";
  14729. sink.write(event.data(), event.size());
  14730. }
  14731. // Keep connection open while handler_running is true
  14732. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14733. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14734. }
  14735. return false;
  14736. });
  14737. });
  14738. Client client("localhost", get_port());
  14739. sse::SSEClient sse(client, "/stay-open");
  14740. std::atomic<bool> connected{false};
  14741. sse.on_open([&connected]() { connected.store(true); });
  14742. sse.set_reconnect_interval(100);
  14743. sse.set_max_reconnect_attempts(1);
  14744. sse.start_async();
  14745. // Wait for connection to establish
  14746. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14747. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14748. }
  14749. EXPECT_TRUE(connected.load());
  14750. EXPECT_TRUE(sse.is_connected());
  14751. // Signal handler to stop
  14752. handler_running.store(false);
  14753. // Stop SSE client
  14754. sse.stop();
  14755. EXPECT_FALSE(sse.is_connected());
  14756. }
  14757. // Test: SSEClient with custom headers
  14758. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14759. // Setup a server endpoint that checks for custom header
  14760. std::atomic<bool> header_received{false};
  14761. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14762. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14763. header_received.store(true);
  14764. }
  14765. res.set_chunked_content_provider("text/event-stream",
  14766. [](size_t, DataSink &) { return false; });
  14767. });
  14768. Client client("localhost", get_port());
  14769. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14770. sse::SSEClient sse(client, "/header-check", headers);
  14771. sse.set_max_reconnect_attempts(1);
  14772. sse.start_async();
  14773. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14774. sse.stop();
  14775. EXPECT_TRUE(header_received.load());
  14776. }
  14777. // Test: Reconnect interval configuration
  14778. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14779. Client client("localhost", get_port());
  14780. sse::SSEClient sse(client, "/events");
  14781. auto &result = sse.set_reconnect_interval(500);
  14782. // Builder pattern should return reference to self
  14783. EXPECT_EQ(&result, &sse);
  14784. }
  14785. // Test: Max reconnect attempts
  14786. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14787. // Connect to non-existent port to force reconnects
  14788. Client client("localhost", 59998);
  14789. sse::SSEClient sse(client, "/events");
  14790. std::atomic<int> error_count{0};
  14791. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14792. sse.set_reconnect_interval(50);
  14793. sse.set_max_reconnect_attempts(2);
  14794. auto start = std::chrono::steady_clock::now();
  14795. sse.start(); // Blocking call
  14796. auto end = std::chrono::steady_clock::now();
  14797. // Should have stopped after 2 failed attempts
  14798. EXPECT_GE(error_count.load(), 2);
  14799. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14800. auto duration =
  14801. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14802. #ifdef _WIN32
  14803. // Windows is much slower for socket connection failures
  14804. EXPECT_LT(duration.count(), 7000);
  14805. #else
  14806. EXPECT_LT(duration.count(), 1000);
  14807. #endif
  14808. }
  14809. // Test: Multi-line data in integration
  14810. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14811. // Endpoint with multi-line data
  14812. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14813. res.set_chunked_content_provider(
  14814. "text/event-stream", [](size_t offset, DataSink &sink) {
  14815. if (offset == 0) {
  14816. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14817. sink.write(event.data(), event.size());
  14818. }
  14819. return false;
  14820. });
  14821. });
  14822. Client client("localhost", get_port());
  14823. sse::SSEClient sse(client, "/multiline-data");
  14824. std::string received_data;
  14825. std::mutex data_mutex;
  14826. sse.on_message([&](const sse::SSEMessage &msg) {
  14827. std::lock_guard<std::mutex> lock(data_mutex);
  14828. received_data = msg.data;
  14829. });
  14830. sse.set_reconnect_interval(100);
  14831. sse.set_max_reconnect_attempts(1);
  14832. sse.start_async();
  14833. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14834. sse.stop();
  14835. std::lock_guard<std::mutex> lock(data_mutex);
  14836. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14837. }
  14838. // Test: Auto-reconnect after server disconnection
  14839. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14840. std::atomic<int> connection_count{0};
  14841. std::atomic<int> message_count{0};
  14842. // Endpoint that sends one event and closes, forcing reconnect
  14843. server_->Get("/reconnect-test",
  14844. [&connection_count](const Request &, Response &res) {
  14845. connection_count.fetch_add(1);
  14846. res.set_chunked_content_provider(
  14847. "text/event-stream", [](size_t offset, DataSink &sink) {
  14848. if (offset == 0) {
  14849. std::string event = "data: hello\n\n";
  14850. sink.write(event.data(), event.size());
  14851. }
  14852. return false; // Close connection after sending
  14853. });
  14854. });
  14855. Client client("localhost", get_port());
  14856. sse::SSEClient sse(client, "/reconnect-test");
  14857. sse.on_message([&message_count](const sse::SSEMessage &) {
  14858. message_count.fetch_add(1);
  14859. });
  14860. sse.set_reconnect_interval(100);
  14861. sse.set_max_reconnect_attempts(3);
  14862. sse.start_async();
  14863. // Wait long enough for multiple reconnects
  14864. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14865. sse.stop();
  14866. // Should have connected multiple times (initial + reconnects)
  14867. EXPECT_GE(connection_count.load(), 2);
  14868. // Should have received messages from multiple connections
  14869. EXPECT_GE(message_count.load(), 2);
  14870. }
  14871. // Test: Last-Event-ID sent on reconnect
  14872. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14873. std::atomic<int> connection_count{0};
  14874. std::vector<std::string> received_last_event_ids;
  14875. std::mutex id_mutex;
  14876. // Endpoint that checks Last-Event-ID header and sends event with ID
  14877. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14878. int conn = connection_count.fetch_add(1);
  14879. // Capture the Last-Event-ID header from each connection
  14880. {
  14881. std::lock_guard<std::mutex> lock(id_mutex);
  14882. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14883. }
  14884. res.set_chunked_content_provider(
  14885. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14886. if (offset == 0) {
  14887. std::string event =
  14888. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14889. sink.write(event.data(), event.size());
  14890. }
  14891. return false;
  14892. });
  14893. });
  14894. Client client("localhost", get_port());
  14895. sse::SSEClient sse(client, "/reconnect-with-id");
  14896. sse.set_reconnect_interval(100);
  14897. sse.set_max_reconnect_attempts(3);
  14898. sse.start_async();
  14899. // Wait for at least 2 connections
  14900. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14901. sse.stop();
  14902. // Verify behavior
  14903. std::lock_guard<std::mutex> lock(id_mutex);
  14904. EXPECT_GE(received_last_event_ids.size(), 2u);
  14905. // First connection should have no Last-Event-ID
  14906. if (!received_last_event_ids.empty()) {
  14907. EXPECT_EQ(received_last_event_ids[0], "");
  14908. }
  14909. // Second connection should have Last-Event-ID from first connection
  14910. if (received_last_event_ids.size() >= 2) {
  14911. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14912. }
  14913. }
  14914. // Test: set_headers updates headers used on reconnect
  14915. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14916. std::vector<std::string> received_tokens;
  14917. std::mutex token_mutex;
  14918. // Endpoint that captures Authorization header
  14919. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14920. {
  14921. std::lock_guard<std::mutex> lock(token_mutex);
  14922. received_tokens.push_back(req.get_header_value("Authorization"));
  14923. }
  14924. res.set_chunked_content_provider(
  14925. "text/event-stream", [](size_t offset, DataSink &sink) {
  14926. if (offset == 0) {
  14927. std::string event = "data: hello\n\n";
  14928. sink.write(event.data(), event.size());
  14929. }
  14930. return false; // Close connection to trigger reconnect
  14931. });
  14932. });
  14933. Client client("localhost", get_port());
  14934. Headers headers = {{"Authorization", "Bearer old-token"}};
  14935. sse::SSEClient sse(client, "/auth-check", headers);
  14936. // Update headers on each successful connection
  14937. sse.on_open(
  14938. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14939. sse.set_reconnect_interval(100);
  14940. sse.set_max_reconnect_attempts(3);
  14941. sse.start_async();
  14942. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14943. sse.stop();
  14944. std::lock_guard<std::mutex> lock(token_mutex);
  14945. ASSERT_GE(received_tokens.size(), 2u);
  14946. // First connection uses original header
  14947. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14948. // Second connection uses updated header from set_headers
  14949. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14950. }
  14951. // Test: 401 allows reconnection (so on_error can refresh headers)
  14952. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14953. std::atomic<int> connection_count{0};
  14954. // Endpoint: returns 401 on first attempt, 200 on second
  14955. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14956. int conn = connection_count.fetch_add(1);
  14957. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14958. res.status = StatusCode::Unauthorized_401;
  14959. res.set_content("Unauthorized", "text/plain");
  14960. return;
  14961. }
  14962. res.set_chunked_content_provider(
  14963. "text/event-stream", [](size_t offset, DataSink &sink) {
  14964. if (offset == 0) {
  14965. std::string event = "data: authenticated\n\n";
  14966. sink.write(event.data(), event.size());
  14967. }
  14968. return false;
  14969. });
  14970. });
  14971. Client client("localhost", get_port());
  14972. Headers headers = {{"Authorization", "Bearer expired"}};
  14973. sse::SSEClient sse(client, "/auth-retry", headers);
  14974. std::atomic<bool> message_received{false};
  14975. // Refresh token on error
  14976. sse.on_error(
  14977. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14978. sse.on_message([&](const sse::SSEMessage &msg) {
  14979. if (msg.data == "authenticated") { message_received.store(true); }
  14980. });
  14981. sse.set_reconnect_interval(100);
  14982. sse.set_max_reconnect_attempts(3);
  14983. sse.start_async();
  14984. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14985. sse.stop();
  14986. // Should have reconnected after 401 and succeeded with new token
  14987. EXPECT_GE(connection_count.load(), 2);
  14988. EXPECT_TRUE(message_received.load());
  14989. }
  14990. TEST(Issue2318Test, EmptyHostString) {
  14991. {
  14992. httplib::Client cli_empty("", PORT);
  14993. auto res = cli_empty.Get("/");
  14994. ASSERT_FALSE(res);
  14995. EXPECT_EQ(httplib::Error::Connection, res.error());
  14996. }
  14997. {
  14998. httplib::Client cli(" ", PORT);
  14999. auto res = cli.Get("/");
  15000. ASSERT_FALSE(res);
  15001. EXPECT_EQ(httplib::Error::Connection, res.error());
  15002. }
  15003. }
  15004. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15005. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15006. Server svr;
  15007. // Set a small payload limit (1KB)
  15008. svr.set_payload_max_length(1024);
  15009. svr.Post("/test", [&](const Request &req, Response &res) {
  15010. res.set_content("Body size: " + std::to_string(req.body.size()),
  15011. "text/plain");
  15012. });
  15013. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15014. auto se = detail::scope_exit([&] {
  15015. svr.stop();
  15016. listen_thread.join();
  15017. });
  15018. svr.wait_until_ready();
  15019. // Create data that compresses well but exceeds limit when decompressed
  15020. // 8KB of repeated null bytes compresses to a very small size
  15021. std::string original_data(8 * 1024, '\0');
  15022. // Compress the data using gzip
  15023. std::string compressed_data;
  15024. detail::gzip_compressor compressor;
  15025. compressor.compress(original_data.data(), original_data.size(), true,
  15026. [&](const char *data, size_t size) {
  15027. compressed_data.append(data, size);
  15028. return true;
  15029. });
  15030. // Verify compression worked (compressed should be much smaller)
  15031. ASSERT_LT(compressed_data.size(), original_data.size());
  15032. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15033. // Send compressed data with Content-Encoding: gzip
  15034. Client cli(HOST, PORT);
  15035. Headers headers = {{"Content-Encoding", "gzip"}};
  15036. auto res =
  15037. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15038. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15039. ASSERT_TRUE(res);
  15040. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15041. }
  15042. #endif
  15043. // ============================================================================
  15044. // OpenSSL-Specific Tests
  15045. // ============================================================================
  15046. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15047. X509 *readCertificate(const std::string &strFileName) {
  15048. std::ifstream inStream(strFileName);
  15049. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15050. std::istreambuf_iterator<char>());
  15051. if (strCertPEM.empty()) return (nullptr);
  15052. BIO *pbCert = BIO_new(BIO_s_mem());
  15053. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15054. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15055. BIO_free(pbCert);
  15056. return (pCert);
  15057. }
  15058. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15059. std::ifstream inStream(strFileName);
  15060. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15061. std::istreambuf_iterator<char>());
  15062. if (strPrivateKeyPEM.empty()) return (nullptr);
  15063. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15064. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15065. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15066. BIO_free(pbPrivKey);
  15067. return (pPrivateKey);
  15068. }
  15069. TEST(BindServerTest, UpdateCerts) {
  15070. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15071. int port = svr.bind_to_any_port("0.0.0.0");
  15072. ASSERT_TRUE(svr.is_valid());
  15073. ASSERT_TRUE(port > 0);
  15074. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15075. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15076. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15077. ASSERT_TRUE(cert != nullptr);
  15078. ASSERT_TRUE(ca_cert != nullptr);
  15079. ASSERT_TRUE(key != nullptr);
  15080. X509_STORE *cert_store = X509_STORE_new();
  15081. X509_STORE_add_cert(cert_store, ca_cert);
  15082. // svr.update_certs(cert, key, cert_store); // deprecated
  15083. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15084. CLIENT_CA_CERT_FILE);
  15085. ASSERT_TRUE(svr.is_valid());
  15086. svr.stop();
  15087. X509_STORE_free(cert_store);
  15088. X509_free(cert);
  15089. X509_free(ca_cert);
  15090. EVP_PKEY_free(key);
  15091. }
  15092. // Test that update_certs() updates client CA list correctly
  15093. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15094. // Start with file-based constructor
  15095. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15096. ASSERT_TRUE(svr.is_valid());
  15097. // Initially no client CA list should be set
  15098. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15099. ASSERT_TRUE(ssl_ctx != nullptr);
  15100. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15101. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15102. EXPECT_EQ(0, count_before);
  15103. // Now update with client CA (PEM string)
  15104. std::string cert_pem, key_pem, ca_pem;
  15105. read_file(SERVER_CERT_FILE, cert_pem);
  15106. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15107. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15108. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15109. ASSERT_TRUE(svr.is_valid());
  15110. // Now client CA list should be set
  15111. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15112. ASSERT_TRUE(ca_list_after != nullptr);
  15113. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15114. }
  15115. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15116. // Test that the file-path SSLServer constructor properly sets the client CA
  15117. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15119. ASSERT_TRUE(svr.is_valid());
  15120. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15121. ASSERT_TRUE(ssl_ctx != nullptr);
  15122. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15123. ASSERT_TRUE(ca_list != nullptr);
  15124. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15125. }
  15126. #endif
  15127. // ============================================================================
  15128. // MbedTLS-Specific Tests
  15129. // ============================================================================
  15130. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15131. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15132. using namespace httplib::tls;
  15133. // Track if callback was invoked
  15134. bool callback_invoked = false;
  15135. // The callback receives void* ctx which is actually MbedTlsContext*
  15136. // We can access the mbedtls_ssl_config via the context
  15137. auto setup_callback = [&callback_invoked](void *ctx) {
  15138. callback_invoked = true;
  15139. // Cast to MbedTlsContext* to access the ssl config
  15140. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15141. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15142. // Use static variables to hold certificate data (simplified for test)
  15143. static mbedtls_x509_crt own_cert;
  15144. static mbedtls_pk_context own_key;
  15145. static mbedtls_x509_crt ca_chain;
  15146. static bool initialized = false;
  15147. if (!initialized) {
  15148. mbedtls_x509_crt_init(&own_cert);
  15149. mbedtls_pk_init(&own_key);
  15150. mbedtls_x509_crt_init(&ca_chain);
  15151. // Load server certificate
  15152. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15153. return false;
  15154. }
  15155. // Load server private key
  15156. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15157. #if MBEDTLS_VERSION_MAJOR >= 3
  15158. ,
  15159. mbedtls_ctr_drbg_random, nullptr
  15160. #endif
  15161. ) != 0) {
  15162. return false;
  15163. }
  15164. // Load CA chain for client verification
  15165. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15166. return false;
  15167. }
  15168. initialized = true;
  15169. }
  15170. // Configure the SSL config
  15171. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15172. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15173. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15174. // Set minimum TLS version using mbedTLS native API
  15175. #if MBEDTLS_VERSION_MAJOR >= 3
  15176. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15177. #else
  15178. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15179. MBEDTLS_SSL_MINOR_VERSION_3);
  15180. #endif
  15181. return true;
  15182. };
  15183. SSLServer svr(setup_callback);
  15184. ASSERT_TRUE(svr.is_valid());
  15185. ASSERT_TRUE(callback_invoked);
  15186. svr.Get("/test", [&](const Request &req, Response &res) {
  15187. res.set_content("test", "text/plain");
  15188. auto cert = req.peer_cert();
  15189. ASSERT_TRUE(static_cast<bool>(cert));
  15190. auto common_name = cert.subject_cn();
  15191. EXPECT_EQ("Common Name", common_name);
  15192. });
  15193. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15194. auto se = detail::scope_exit([&] {
  15195. svr.stop();
  15196. t.join();
  15197. ASSERT_FALSE(svr.is_running());
  15198. });
  15199. svr.wait_until_ready();
  15200. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15201. cli.enable_server_certificate_verification(false);
  15202. cli.set_connection_timeout(30);
  15203. auto res = cli.Get("/test");
  15204. ASSERT_TRUE(res);
  15205. ASSERT_EQ(StatusCode::OK_200, res->status);
  15206. }
  15207. #endif
  15208. // WebSocket Tests
  15209. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15210. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15211. // defining the meaning of these bits has been negotiated.
  15212. auto make_frame = [](uint8_t first_byte) {
  15213. std::string frame;
  15214. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15215. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15216. frame += "Hello";
  15217. return frame;
  15218. };
  15219. // RSV1 set (0x40)
  15220. {
  15221. detail::BufferStream strm;
  15222. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15223. ws::Opcode opcode;
  15224. std::string payload;
  15225. bool fin;
  15226. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15227. false, 1024));
  15228. }
  15229. // RSV2 set (0x20)
  15230. {
  15231. detail::BufferStream strm;
  15232. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15233. ws::Opcode opcode;
  15234. std::string payload;
  15235. bool fin;
  15236. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15237. false, 1024));
  15238. }
  15239. // RSV3 set (0x10)
  15240. {
  15241. detail::BufferStream strm;
  15242. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15243. ws::Opcode opcode;
  15244. std::string payload;
  15245. bool fin;
  15246. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15247. false, 1024));
  15248. }
  15249. // No RSV bits set - should succeed
  15250. {
  15251. detail::BufferStream strm;
  15252. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15253. ws::Opcode opcode;
  15254. std::string payload;
  15255. bool fin;
  15256. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15257. false, 1024));
  15258. EXPECT_EQ(ws::Opcode::Text, opcode);
  15259. EXPECT_EQ("Hello", payload);
  15260. EXPECT_TRUE(fin);
  15261. }
  15262. }
  15263. TEST(WebSocketTest, ControlFrameValidation) {
  15264. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15265. // payload length <= 125.
  15266. // Ping with FIN=0 - must be rejected
  15267. {
  15268. detail::BufferStream strm;
  15269. std::string frame;
  15270. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15271. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15272. strm.write(frame.data(), frame.size());
  15273. ws::Opcode opcode;
  15274. std::string payload;
  15275. bool fin;
  15276. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15277. false, 1024));
  15278. }
  15279. // Close with FIN=0 - must be rejected
  15280. {
  15281. detail::BufferStream strm;
  15282. std::string frame;
  15283. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15284. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15285. strm.write(frame.data(), frame.size());
  15286. ws::Opcode opcode;
  15287. std::string payload;
  15288. bool fin;
  15289. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15290. false, 1024));
  15291. }
  15292. // Ping with payload_len=126 (extended length) - must be rejected
  15293. {
  15294. detail::BufferStream strm;
  15295. std::string frame;
  15296. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15297. frame += static_cast<char>(126); // payload_len=126 (>125)
  15298. frame += static_cast<char>(0x00); // extended length high byte
  15299. frame += static_cast<char>(126); // extended length low byte
  15300. frame += std::string(126, 'x');
  15301. strm.write(frame.data(), frame.size());
  15302. ws::Opcode opcode;
  15303. std::string payload;
  15304. bool fin;
  15305. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15306. false, 1024));
  15307. }
  15308. // Ping with FIN=1 and payload_len=125 - should succeed
  15309. {
  15310. detail::BufferStream strm;
  15311. std::string frame;
  15312. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15313. frame += static_cast<char>(125); // payload_len=125
  15314. frame += std::string(125, 'x');
  15315. strm.write(frame.data(), frame.size());
  15316. ws::Opcode opcode;
  15317. std::string payload;
  15318. bool fin;
  15319. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15320. false, 1024));
  15321. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15322. EXPECT_EQ(125u, payload.size());
  15323. EXPECT_TRUE(fin);
  15324. }
  15325. }
  15326. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15327. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15328. // length MUST be 0.
  15329. // MSB set - must be rejected
  15330. {
  15331. detail::BufferStream strm;
  15332. std::string frame;
  15333. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15334. frame += static_cast<char>(127); // 64-bit extended length
  15335. frame += static_cast<char>(0x80); // MSB set (invalid)
  15336. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15337. strm.write(frame.data(), frame.size());
  15338. ws::Opcode opcode;
  15339. std::string payload;
  15340. bool fin;
  15341. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15342. false, 1024));
  15343. }
  15344. // MSB clear - should pass length parsing (will be rejected by max_len,
  15345. // but that's a different check; use a small length to verify)
  15346. {
  15347. detail::BufferStream strm;
  15348. std::string frame;
  15349. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15350. frame += static_cast<char>(127); // 64-bit extended length
  15351. frame += std::string(7, '\0'); // high bytes = 0
  15352. frame += static_cast<char>(0x03); // length = 3
  15353. frame += "abc";
  15354. strm.write(frame.data(), frame.size());
  15355. ws::Opcode opcode;
  15356. std::string payload;
  15357. bool fin;
  15358. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15359. false, 1024));
  15360. EXPECT_EQ(ws::Opcode::Text, opcode);
  15361. EXPECT_EQ("abc", payload);
  15362. }
  15363. }
  15364. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15365. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15366. // Valid UTF-8
  15367. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15368. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15369. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15370. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15371. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15372. // Invalid UTF-8
  15373. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15374. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15375. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15376. EXPECT_FALSE(
  15377. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15378. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15379. }
  15380. TEST(WebSocketTest, ConnectAndDisconnect) {
  15381. Server svr;
  15382. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15383. std::string msg;
  15384. while (ws.read(msg)) {}
  15385. });
  15386. auto port = svr.bind_to_any_port(HOST);
  15387. std::thread t([&]() { svr.listen_after_bind(); });
  15388. svr.wait_until_ready();
  15389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15390. ASSERT_TRUE(client.connect());
  15391. EXPECT_TRUE(client.is_open());
  15392. client.close();
  15393. EXPECT_FALSE(client.is_open());
  15394. svr.stop();
  15395. t.join();
  15396. }
  15397. TEST(WebSocketTest, ValidURL) {
  15398. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15399. EXPECT_TRUE(ws1.is_valid());
  15400. ws::WebSocketClient ws2("ws://example.com/path");
  15401. EXPECT_TRUE(ws2.is_valid());
  15402. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15403. EXPECT_TRUE(ws3.is_valid());
  15404. #ifdef CPPHTTPLIB_SSL_ENABLED
  15405. ws::WebSocketClient wss1("wss://example.com/path");
  15406. EXPECT_TRUE(wss1.is_valid());
  15407. ws::WebSocketClient wss2("wss://example.com:443/path");
  15408. EXPECT_TRUE(wss2.is_valid());
  15409. #endif
  15410. }
  15411. TEST(WebSocketTest, InvalidURL) {
  15412. // No scheme
  15413. ws::WebSocketClient ws1("localhost:8080/path");
  15414. EXPECT_FALSE(ws1.is_valid());
  15415. // No path
  15416. ws::WebSocketClient ws2("ws://localhost:8080");
  15417. EXPECT_FALSE(ws2.is_valid());
  15418. // Empty string
  15419. ws::WebSocketClient ws3("");
  15420. EXPECT_FALSE(ws3.is_valid());
  15421. // Missing host
  15422. ws::WebSocketClient ws4("ws://:8080/path");
  15423. EXPECT_FALSE(ws4.is_valid());
  15424. // Port number overflow — should not crash
  15425. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15426. EXPECT_FALSE(ws5.is_valid());
  15427. // Port out of range
  15428. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15429. EXPECT_FALSE(ws6.is_valid());
  15430. }
  15431. TEST(WebSocketTest, UnsupportedScheme) {
  15432. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15433. ws::WebSocketClient ws1("http://localhost:8080/path");
  15434. EXPECT_FALSE(ws1.is_valid());
  15435. ws::WebSocketClient ws2("https://localhost:8080/path");
  15436. EXPECT_FALSE(ws2.is_valid());
  15437. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15438. EXPECT_FALSE(ws3.is_valid());
  15439. #else
  15440. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15441. std::invalid_argument);
  15442. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15443. std::invalid_argument);
  15444. #endif
  15445. }
  15446. TEST(WebSocketTest, ConnectWhenInvalid) {
  15447. ws::WebSocketClient ws("not a valid url");
  15448. EXPECT_FALSE(ws.is_valid());
  15449. EXPECT_FALSE(ws.connect());
  15450. }
  15451. TEST(WebSocketTest, DefaultPort) {
  15452. ws::WebSocketClient ws1("ws://example.com/path");
  15453. EXPECT_TRUE(ws1.is_valid());
  15454. // ws:// defaults to port 80 (verified by successful parse)
  15455. #ifdef CPPHTTPLIB_SSL_ENABLED
  15456. ws::WebSocketClient ws2("wss://example.com/path");
  15457. EXPECT_TRUE(ws2.is_valid());
  15458. // wss:// defaults to port 443 (verified by successful parse)
  15459. #endif
  15460. }
  15461. TEST(WebSocketTest, IPv6LiteralAddress) {
  15462. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15463. EXPECT_TRUE(ws1.is_valid());
  15464. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15465. EXPECT_TRUE(ws2.is_valid());
  15466. }
  15467. TEST(WebSocketTest, ComplexPath) {
  15468. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15469. EXPECT_TRUE(ws1.is_valid());
  15470. ws::WebSocketClient ws2("ws://localhost:8080/");
  15471. EXPECT_TRUE(ws2.is_valid());
  15472. }
  15473. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15474. Server svr;
  15475. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15476. std::string msg;
  15477. while (ws.read(msg)) {}
  15478. });
  15479. auto port = svr.bind_to_any_port(HOST);
  15480. std::thread t([&]() { svr.listen_after_bind(); });
  15481. svr.wait_until_ready();
  15482. auto another_host = "example.com";
  15483. auto wrong_ip = "192.0.2.1";
  15484. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15485. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15486. ASSERT_TRUE(client.connect());
  15487. EXPECT_TRUE(client.is_open());
  15488. client.close();
  15489. svr.stop();
  15490. t.join();
  15491. }
  15492. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15493. Server svr;
  15494. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15495. std::string msg;
  15496. while (ws.read(msg)) {}
  15497. });
  15498. auto port = svr.bind_to_any_port(HOST);
  15499. std::thread t([&]() { svr.listen_after_bind(); });
  15500. svr.wait_until_ready();
  15501. auto wrong_ip = "192.0.2.1";
  15502. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15503. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15504. client.set_connection_timeout(1);
  15505. client.set_read_timeout(1);
  15506. client.set_write_timeout(1);
  15507. EXPECT_FALSE(client.connect());
  15508. EXPECT_FALSE(client.is_open());
  15509. svr.stop();
  15510. t.join();
  15511. }
  15512. class WebSocketIntegrationTest : public ::testing::Test {
  15513. protected:
  15514. void SetUp() override {
  15515. server_ = httplib::detail::make_unique<Server>();
  15516. setup_server();
  15517. start_server();
  15518. }
  15519. void TearDown() override {
  15520. server_->stop();
  15521. if (server_thread_.joinable()) { server_thread_.join(); }
  15522. }
  15523. void setup_server() {
  15524. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15525. std::string msg;
  15526. ws::ReadResult ret;
  15527. while ((ret = ws.read(msg))) {
  15528. if (ret == ws::Binary) {
  15529. ws.send(msg.data(), msg.size());
  15530. } else {
  15531. ws.send(msg);
  15532. }
  15533. }
  15534. });
  15535. server_->WebSocket("/ws-echo-string",
  15536. [](const Request &, ws::WebSocket &ws) {
  15537. std::string msg;
  15538. while (ws.read(msg)) {
  15539. ws.send("echo: " + msg);
  15540. }
  15541. });
  15542. server_->WebSocket(
  15543. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15544. // Echo back request metadata
  15545. ws.send("path:" + req.path);
  15546. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15547. std::string msg;
  15548. while (ws.read(msg)) {}
  15549. });
  15550. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15551. std::string msg;
  15552. ws.read(msg); // wait for a message
  15553. ws.close();
  15554. });
  15555. server_->WebSocket("/ws-close-status",
  15556. [](const Request &, ws::WebSocket &ws) {
  15557. std::string msg;
  15558. ws.read(msg); // wait for a message
  15559. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15560. });
  15561. server_->WebSocket(
  15562. "/ws-subprotocol",
  15563. [](const Request &, ws::WebSocket &ws) {
  15564. std::string msg;
  15565. while (ws.read(msg)) {
  15566. ws.send(msg);
  15567. }
  15568. },
  15569. [](const std::vector<std::string> &protocols) -> std::string {
  15570. for (const auto &p : protocols) {
  15571. if (p == "graphql-ws") { return p; }
  15572. }
  15573. return "";
  15574. });
  15575. }
  15576. void start_server() {
  15577. port_ = server_->bind_to_any_port(HOST);
  15578. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15579. server_->wait_until_ready();
  15580. }
  15581. std::unique_ptr<Server> server_;
  15582. std::thread server_thread_;
  15583. int port_ = 0;
  15584. };
  15585. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15586. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15587. "/ws-echo");
  15588. ASSERT_TRUE(client.connect());
  15589. ASSERT_TRUE(client.is_open());
  15590. ASSERT_TRUE(client.send("Hello WebSocket"));
  15591. std::string msg;
  15592. EXPECT_EQ(ws::Text, client.read(msg));
  15593. EXPECT_EQ("Hello WebSocket", msg);
  15594. client.close();
  15595. }
  15596. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15597. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15598. "/ws-echo");
  15599. ASSERT_TRUE(client.connect());
  15600. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15601. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15602. std::string msg;
  15603. EXPECT_EQ(ws::Binary, client.read(msg));
  15604. EXPECT_EQ(binary_data, msg);
  15605. client.close();
  15606. }
  15607. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15608. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15609. "/ws-echo");
  15610. ASSERT_TRUE(client.connect());
  15611. for (int i = 0; i < 10; i++) {
  15612. auto text = "message " + std::to_string(i);
  15613. ASSERT_TRUE(client.send(text));
  15614. std::string msg;
  15615. ASSERT_TRUE(client.read(msg));
  15616. EXPECT_EQ(text, msg);
  15617. }
  15618. client.close();
  15619. }
  15620. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15621. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15622. "/ws-close");
  15623. ASSERT_TRUE(client.connect());
  15624. // Send a message to trigger the server to close
  15625. ASSERT_TRUE(client.send("trigger close"));
  15626. // The server will close, so read should return false
  15627. std::string msg;
  15628. EXPECT_FALSE(client.read(msg));
  15629. EXPECT_FALSE(client.is_open());
  15630. }
  15631. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15632. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15633. "/ws-echo");
  15634. ASSERT_TRUE(client.connect());
  15635. // 128KB message
  15636. std::string large_data(128 * 1024, 'X');
  15637. ASSERT_TRUE(client.send(large_data));
  15638. std::string msg;
  15639. ASSERT_TRUE(client.read(msg));
  15640. EXPECT_EQ(large_data, msg);
  15641. client.close();
  15642. }
  15643. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15644. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15645. "/ws-echo");
  15646. ASSERT_TRUE(client.connect());
  15647. const int num_threads = 4;
  15648. std::vector<std::thread> threads;
  15649. std::atomic<int> send_count{0};
  15650. for (int t = 0; t < num_threads; t++) {
  15651. threads.emplace_back([&client, &send_count, t]() {
  15652. for (int i = 0; i < 5; i++) {
  15653. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15654. if (client.send(text)) { send_count++; }
  15655. }
  15656. });
  15657. }
  15658. for (auto &th : threads) {
  15659. th.join();
  15660. }
  15661. int received = 0;
  15662. std::string msg;
  15663. while (received < send_count.load()) {
  15664. if (!client.read(msg)) { break; }
  15665. received++;
  15666. }
  15667. EXPECT_EQ(send_count.load(), received);
  15668. client.close();
  15669. }
  15670. TEST_F(WebSocketIntegrationTest, ReadString) {
  15671. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15672. "/ws-echo-string");
  15673. ASSERT_TRUE(client.connect());
  15674. ASSERT_TRUE(client.send("hello"));
  15675. std::string msg;
  15676. ASSERT_TRUE(client.read(msg));
  15677. EXPECT_EQ("echo: hello", msg);
  15678. ASSERT_TRUE(client.send("world"));
  15679. ASSERT_TRUE(client.read(msg));
  15680. EXPECT_EQ("echo: world", msg);
  15681. client.close();
  15682. }
  15683. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15684. Headers headers = {{"X-Test-Header", "test-value"}};
  15685. ws::WebSocketClient client(
  15686. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15687. ASSERT_TRUE(client.connect());
  15688. std::string msg;
  15689. ASSERT_TRUE(client.read(msg));
  15690. EXPECT_EQ("path:/ws-request-info", msg);
  15691. ASSERT_TRUE(client.read(msg));
  15692. EXPECT_EQ("header:test-value", msg);
  15693. client.close();
  15694. }
  15695. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15696. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15697. "/ws-echo");
  15698. client.set_read_timeout(1, 0); // 1 second
  15699. ASSERT_TRUE(client.connect());
  15700. // Don't send anything — server echo handler waits for a message,
  15701. // so read() should time out and return false.
  15702. std::string msg;
  15703. EXPECT_FALSE(client.read(msg));
  15704. }
  15705. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15707. "/ws-echo");
  15708. client.set_read_timeout(5, 0);
  15709. ASSERT_TRUE(client.connect());
  15710. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15711. // The server should reject it and close the connection.
  15712. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15713. client.send(oversized);
  15714. // The server's read() should have failed due to payload limit,
  15715. // so our read() should return false (connection closed).
  15716. std::string msg;
  15717. EXPECT_FALSE(client.read(msg));
  15718. }
  15719. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15720. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15721. "/ws-echo");
  15722. client.set_read_timeout(10, 0);
  15723. ASSERT_TRUE(client.connect());
  15724. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15725. // This should succeed.
  15726. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15727. ASSERT_TRUE(client.send(at_limit));
  15728. std::string msg;
  15729. ASSERT_TRUE(client.read(msg));
  15730. EXPECT_EQ(at_limit.size(), msg.size());
  15731. client.close();
  15732. }
  15733. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15734. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15735. "/nonexistent");
  15736. EXPECT_FALSE(client.connect());
  15737. EXPECT_FALSE(client.is_open());
  15738. }
  15739. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15741. "/ws-echo");
  15742. ASSERT_TRUE(client.connect());
  15743. ASSERT_TRUE(client.send(""));
  15744. std::string msg;
  15745. EXPECT_EQ(ws::Text, client.read(msg));
  15746. EXPECT_EQ("", msg);
  15747. client.close();
  15748. }
  15749. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15751. "/ws-echo");
  15752. // First connection
  15753. ASSERT_TRUE(client.connect());
  15754. ASSERT_TRUE(client.send("first"));
  15755. std::string msg;
  15756. ASSERT_TRUE(client.read(msg));
  15757. EXPECT_EQ("first", msg);
  15758. client.close();
  15759. EXPECT_FALSE(client.is_open());
  15760. // Reconnect using the same client object
  15761. ASSERT_TRUE(client.connect());
  15762. ASSERT_TRUE(client.is_open());
  15763. ASSERT_TRUE(client.send("second"));
  15764. ASSERT_TRUE(client.read(msg));
  15765. EXPECT_EQ("second", msg);
  15766. client.close();
  15767. }
  15768. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15769. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15770. "/ws-close-status");
  15771. ASSERT_TRUE(client.connect());
  15772. // Trigger the server to close with GoingAway status
  15773. ASSERT_TRUE(client.send("trigger"));
  15774. // read() should return false after receiving the close frame
  15775. std::string msg;
  15776. EXPECT_FALSE(client.read(msg));
  15777. EXPECT_FALSE(client.is_open());
  15778. }
  15779. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15780. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15781. "/ws-echo");
  15782. ASSERT_TRUE(client.connect());
  15783. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15784. EXPECT_FALSE(client.is_open());
  15785. }
  15786. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15787. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15788. ws::WebSocketClient client(
  15789. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15790. ASSERT_TRUE(client.connect());
  15791. // Server should have selected graphql-ws
  15792. EXPECT_EQ("graphql-ws", client.subprotocol());
  15793. client.close();
  15794. }
  15795. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15796. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15797. ws::WebSocketClient client(
  15798. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15799. ASSERT_TRUE(client.connect());
  15800. // Server should not have selected any subprotocol
  15801. EXPECT_TRUE(client.subprotocol().empty());
  15802. client.close();
  15803. }
  15804. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15805. // Connect without requesting any subprotocol
  15806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15807. "/ws-subprotocol");
  15808. ASSERT_TRUE(client.connect());
  15809. EXPECT_TRUE(client.subprotocol().empty());
  15810. client.close();
  15811. }
  15812. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15814. "/ws-echo");
  15815. client.set_tcp_nodelay(true);
  15816. client.set_connection_timeout(3, 0);
  15817. bool socket_options_called = false;
  15818. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15819. ASSERT_TRUE(client.connect());
  15820. ASSERT_TRUE(client.is_open());
  15821. EXPECT_TRUE(socket_options_called);
  15822. ASSERT_TRUE(client.send("hello"));
  15823. std::string msg;
  15824. auto result = client.read(msg);
  15825. EXPECT_EQ(result, ws::ReadResult::Text);
  15826. EXPECT_EQ(msg, "hello");
  15827. client.close();
  15828. }
  15829. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15830. Server svr;
  15831. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15832. if (!req.has_header("Authorization")) {
  15833. res.status = StatusCode::Unauthorized_401;
  15834. res.set_content("Unauthorized", "text/plain");
  15835. return Server::HandlerResponse::Handled;
  15836. }
  15837. return Server::HandlerResponse::Unhandled;
  15838. });
  15839. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15840. std::string msg;
  15841. while (ws.read(msg)) {
  15842. ws.send(msg);
  15843. }
  15844. });
  15845. auto port = svr.bind_to_any_port("localhost");
  15846. std::thread t([&]() { svr.listen_after_bind(); });
  15847. svr.wait_until_ready();
  15848. // Without Authorization header - should be rejected before upgrade
  15849. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15850. EXPECT_FALSE(client1.connect());
  15851. // With Authorization header - should succeed
  15852. Headers headers = {{"Authorization", "Bearer token123"}};
  15853. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15854. headers);
  15855. ASSERT_TRUE(client2.connect());
  15856. ASSERT_TRUE(client2.send("hello"));
  15857. std::string msg;
  15858. ASSERT_TRUE(client2.read(msg));
  15859. EXPECT_EQ("hello", msg);
  15860. client2.close();
  15861. svr.stop();
  15862. t.join();
  15863. }
  15864. TEST(WebSocketTest, QueryStringInHandshake) {
  15865. Server svr;
  15866. std::mutex mtx;
  15867. std::string received_target;
  15868. std::string received_token;
  15869. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15870. {
  15871. std::lock_guard<std::mutex> lock(mtx);
  15872. received_target = req.target;
  15873. if (req.has_param("token")) {
  15874. received_token = req.get_param_value("token");
  15875. }
  15876. }
  15877. std::string msg;
  15878. while (ws.read(msg)) {
  15879. ws.send(msg);
  15880. }
  15881. });
  15882. auto port = svr.bind_to_any_port("localhost");
  15883. std::thread t([&]() { svr.listen_after_bind(); });
  15884. svr.wait_until_ready();
  15885. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15886. "/ws?token=ABC&session=123");
  15887. ASSERT_TRUE(client.connect());
  15888. // Round-trip ensures the handler has run and captured the request.
  15889. ASSERT_TRUE(client.send("hello"));
  15890. std::string msg;
  15891. ASSERT_TRUE(client.read(msg));
  15892. EXPECT_EQ("hello", msg);
  15893. client.close();
  15894. {
  15895. std::lock_guard<std::mutex> lock(mtx);
  15896. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15897. EXPECT_EQ("ABC", received_token);
  15898. }
  15899. svr.stop();
  15900. t.join();
  15901. }
  15902. TEST(WebSocketTest, HostHeaderInHandshake) {
  15903. Server svr;
  15904. std::mutex mtx;
  15905. std::string received_host;
  15906. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15907. {
  15908. std::lock_guard<std::mutex> lock(mtx);
  15909. received_host = req.get_header_value("Host");
  15910. }
  15911. std::string msg;
  15912. while (ws.read(msg)) {
  15913. ws.send(msg);
  15914. }
  15915. });
  15916. auto port = svr.bind_to_any_port("localhost");
  15917. std::thread t([&]() { svr.listen_after_bind(); });
  15918. svr.wait_until_ready();
  15919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15920. ASSERT_TRUE(client.connect());
  15921. // Round-trip ensures the handler has run and captured the request.
  15922. ASSERT_TRUE(client.send("hello"));
  15923. std::string msg;
  15924. ASSERT_TRUE(client.read(msg));
  15925. client.close();
  15926. {
  15927. std::lock_guard<std::mutex> lock(mtx);
  15928. // Non-default port must be present in the Host header. Default ports
  15929. // (80/443) are omitted; that logic is covered by
  15930. // MakeHostAndPortStringTest.
  15931. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  15932. }
  15933. svr.stop();
  15934. t.join();
  15935. }
  15936. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15937. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15938. protected:
  15939. void SetUp() override {
  15940. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15941. SERVER_PRIVATE_KEY_FILE);
  15942. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15943. std::string msg;
  15944. ws::ReadResult ret;
  15945. while ((ret = ws.read(msg))) {
  15946. if (ret == ws::Binary) {
  15947. ws.send(msg.data(), msg.size());
  15948. } else {
  15949. ws.send(msg);
  15950. }
  15951. }
  15952. });
  15953. port_ = server_->bind_to_any_port(HOST);
  15954. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15955. server_->wait_until_ready();
  15956. }
  15957. void TearDown() override {
  15958. server_->stop();
  15959. if (server_thread_.joinable()) { server_thread_.join(); }
  15960. }
  15961. std::unique_ptr<SSLServer> server_;
  15962. std::thread server_thread_;
  15963. int port_ = 0;
  15964. };
  15965. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15966. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15967. "/ws-echo");
  15968. client.enable_server_certificate_verification(false);
  15969. ASSERT_TRUE(client.connect());
  15970. ASSERT_TRUE(client.is_open());
  15971. ASSERT_TRUE(client.send("Hello WSS"));
  15972. std::string msg;
  15973. EXPECT_EQ(ws::Text, client.read(msg));
  15974. EXPECT_EQ("Hello WSS", msg);
  15975. client.close();
  15976. }
  15977. #endif
  15978. #ifdef CPPHTTPLIB_SSL_ENABLED
  15979. class WebSocketSSLCATest : public ::testing::Test {
  15980. protected:
  15981. void SetUp() override {
  15982. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  15983. SERVER_PRIVATE_KEY_FILE);
  15984. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15985. std::string msg;
  15986. while (ws.read(msg)) {
  15987. ws.send(msg);
  15988. }
  15989. });
  15990. port_ = server_->bind_to_any_port("127.0.0.1");
  15991. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15992. server_->wait_until_ready();
  15993. }
  15994. void TearDown() override {
  15995. server_->stop();
  15996. if (server_thread_.joinable()) { server_thread_.join(); }
  15997. }
  15998. std::string url() const {
  15999. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16000. }
  16001. std::unique_ptr<SSLServer> server_;
  16002. std::thread server_thread_;
  16003. int port_ = 0;
  16004. };
  16005. // A custom CA loaded as PEM verifies the server with full certificate
  16006. // verification enabled
  16007. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16008. ws::WebSocketClient client(url());
  16009. std::string cert;
  16010. read_file(SERVER_CERT2_FILE, cert);
  16011. client.load_ca_cert_store(cert.c_str(), cert.size());
  16012. ASSERT_TRUE(client.connect());
  16013. ASSERT_TRUE(client.send("hello"));
  16014. std::string msg;
  16015. EXPECT_EQ(ws::Text, client.read(msg));
  16016. EXPECT_EQ("hello", msg);
  16017. client.close();
  16018. }
  16019. // A custom CA that does not cover the server must fail verification (the
  16020. // custom CA is exclusive; system certs are not loaded alongside it)
  16021. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16022. ws::WebSocketClient client(url());
  16023. std::string cert;
  16024. read_file(CLIENT_CA_CERT_FILE, cert);
  16025. client.load_ca_cert_store(cert.c_str(), cert.size());
  16026. ASSERT_FALSE(client.connect());
  16027. }
  16028. // Regression test: reconnecting with a native custom CA store used to reuse
  16029. // a store handle the previous TLS context had already freed (use-after-free
  16030. // under the OpenSSL backend). The context now lives as long as the client.
  16031. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16032. ws::WebSocketClient client(url());
  16033. std::string cert;
  16034. read_file(SERVER_CERT2_FILE, cert);
  16035. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16036. ASSERT_TRUE(client.connect());
  16037. client.close();
  16038. ASSERT_TRUE(client.connect());
  16039. ASSERT_TRUE(client.send("again"));
  16040. std::string msg;
  16041. EXPECT_EQ(ws::Text, client.read(msg));
  16042. EXPECT_EQ("again", msg);
  16043. client.close();
  16044. }
  16045. // Regression test: a certificate with a trusted chain but no identity match
  16046. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16047. // verification entirely for IP hosts, so this connection succeeded there.
  16048. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16049. // chain verification while the identity check must still fail.
  16050. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16052. ASSERT_TRUE(svr.is_valid());
  16053. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16054. std::string msg;
  16055. while (ws.read(msg)) {
  16056. ws.send(msg);
  16057. }
  16058. });
  16059. auto port = svr.bind_to_any_port("127.0.0.1");
  16060. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16061. auto se = detail::scope_exit([&] {
  16062. svr.stop();
  16063. t.join();
  16064. });
  16065. svr.wait_until_ready();
  16066. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16067. "/echo");
  16068. std::string cert;
  16069. read_file(SERVER_CERT_FILE, cert);
  16070. client.load_ca_cert_store(cert.c_str(), cert.size());
  16071. ASSERT_FALSE(client.connect());
  16072. }
  16073. #endif
  16074. #if !defined(_WIN32)
  16075. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16076. auto secret_dir = std::string("./symlink_test_secret");
  16077. auto served_dir = std::string("./symlink_test_served");
  16078. auto secret_file = secret_dir + "/secret.txt";
  16079. auto symlink_path = served_dir + "/escape";
  16080. // Setup: create directories and files
  16081. mkdir(secret_dir.c_str(), 0755);
  16082. mkdir(served_dir.c_str(), 0755);
  16083. {
  16084. std::ofstream ofs(secret_file);
  16085. ofs << "SECRET_DATA";
  16086. }
  16087. // Create symlink using absolute path so it resolves correctly
  16088. #ifdef PATH_MAX
  16089. char abs_secret[PATH_MAX];
  16090. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16091. #else
  16092. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16093. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16094. ASSERT_NE(nullptr, abs_secret);
  16095. #endif
  16096. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16097. auto se = detail::scope_exit([&] {
  16098. unlink(symlink_path.c_str());
  16099. unlink(secret_file.c_str());
  16100. rmdir(served_dir.c_str());
  16101. rmdir(secret_dir.c_str());
  16102. });
  16103. Server svr;
  16104. svr.set_mount_point("/", served_dir);
  16105. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16106. auto se2 = detail::scope_exit([&] {
  16107. svr.stop();
  16108. listen_thread.join();
  16109. });
  16110. svr.wait_until_ready();
  16111. Client cli("localhost", PORT);
  16112. // Symlink pointing outside base dir should be blocked
  16113. auto res = cli.Get("/escape/secret.txt");
  16114. ASSERT_TRUE(res);
  16115. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16116. }
  16117. #endif
  16118. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16119. // A GET request with Content-Length to a static file handler must have its
  16120. // body drained before the keep-alive connection is reused. Otherwise the
  16121. // unread body bytes are interpreted as the next HTTP request.
  16122. //
  16123. // The body is sent AFTER receiving the first response (as in the original
  16124. // PoC) so that the stream_line_reader cannot buffer it together with the
  16125. // headers of the first request.
  16126. Server svr;
  16127. svr.set_mount_point("/", "./www");
  16128. std::atomic<int> smuggled_count(0);
  16129. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16130. smuggled_count++;
  16131. res.set_content("oops", "text/plain");
  16132. });
  16133. auto port = svr.bind_to_any_port("localhost");
  16134. thread t = thread([&] { svr.listen_after_bind(); });
  16135. auto se = detail::scope_exit([&] {
  16136. svr.stop();
  16137. t.join();
  16138. });
  16139. svr.wait_until_ready();
  16140. auto error = Error::Success;
  16141. auto sock = detail::create_client_socket(
  16142. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16143. /*connection_timeout_sec=*/2, 0,
  16144. /*read_timeout_sec=*/2, 0,
  16145. /*write_timeout_sec=*/2, 0, std::string(), error);
  16146. ASSERT_NE(INVALID_SOCKET, sock);
  16147. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16148. // The "smuggled" request will be sent as the body of the outer GET
  16149. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16150. "Host: localhost\r\n"
  16151. "Connection: close\r\n"
  16152. "\r\n";
  16153. // Step 1: Send only the outer request headers (no body yet)
  16154. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16155. "Host: localhost\r\n"
  16156. "Content-Length: " +
  16157. std::to_string(smuggled.size()) +
  16158. "\r\n"
  16159. "\r\n";
  16160. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16161. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16162. // Step 2: Read the first response (server serves file without reading body)
  16163. std::string first_response;
  16164. char buf[4096];
  16165. for (;;) {
  16166. auto n = recv(sock, buf, sizeof(buf), 0);
  16167. if (n <= 0) break;
  16168. first_response.append(buf, static_cast<size_t>(n));
  16169. // Stop once we have a complete response (headers + body)
  16170. auto hdr_end = first_response.find("\r\n\r\n");
  16171. if (hdr_end != std::string::npos) {
  16172. // Check for Content-Length to know when the body is complete
  16173. auto cl_pos = first_response.find("Content-Length:");
  16174. if (cl_pos != std::string::npos) {
  16175. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16176. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16177. auto cl = std::stoul(
  16178. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16179. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16180. } else {
  16181. break; // No Content-Length, assume headers-only response
  16182. }
  16183. }
  16184. }
  16185. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16186. // Step 3: Now send the body, which looks like a new HTTP request.
  16187. // On a vulnerable server the keep-alive loop reads this as a second request.
  16188. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16189. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16190. // Step 4: Try to read a second response (should NOT exist after fix)
  16191. std::string second_response;
  16192. for (;;) {
  16193. auto n = recv(sock, buf, sizeof(buf), 0);
  16194. if (n <= 0) break;
  16195. second_response.append(buf, static_cast<size_t>(n));
  16196. }
  16197. // The smuggled request must NOT have been processed
  16198. EXPECT_EQ(0, smuggled_count.load());
  16199. }
  16200. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16201. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16202. // must be rejected with 400 Bad Request.
  16203. Server svr;
  16204. svr.Post("/test", [&](const Request &, Response &res) {
  16205. res.set_content("ok", "text/plain");
  16206. });
  16207. thread t = thread([&] { svr.listen(HOST, PORT); });
  16208. auto se = detail::scope_exit([&] {
  16209. svr.stop();
  16210. t.join();
  16211. ASSERT_FALSE(svr.is_running());
  16212. });
  16213. svr.wait_until_ready();
  16214. // Exact "chunked"
  16215. {
  16216. auto req = "POST /test HTTP/1.1\r\n"
  16217. "Host: localhost\r\n"
  16218. "Content-Length: 5\r\n"
  16219. "Transfer-Encoding: chunked\r\n"
  16220. "Connection: close\r\n"
  16221. "\r\n"
  16222. "hello";
  16223. std::string response;
  16224. ASSERT_TRUE(send_request(1, req, &response));
  16225. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16226. response.substr(0, response.find("\r\n")));
  16227. }
  16228. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16229. {
  16230. auto req = "POST /test HTTP/1.1\r\n"
  16231. "Host: localhost\r\n"
  16232. "Content-Length: 5\r\n"
  16233. "Transfer-Encoding: gzip, chunked\r\n"
  16234. "Connection: close\r\n"
  16235. "\r\n"
  16236. "hello";
  16237. std::string response;
  16238. ASSERT_TRUE(send_request(1, req, &response));
  16239. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16240. response.substr(0, response.find("\r\n")));
  16241. }
  16242. }
  16243. // Regression for issue #2450: a DELETE without Content-Length on a
  16244. // keep-alive connection must not let the post-response drain consume the
  16245. // next request's bytes.
  16246. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16247. Server svr;
  16248. std::atomic<int> delete_count(0);
  16249. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16250. delete_count++;
  16251. res.status = StatusCode::NoContent_204;
  16252. });
  16253. auto port = svr.bind_to_any_port(HOST);
  16254. thread t = thread([&] { svr.listen_after_bind(); });
  16255. auto se = detail::scope_exit([&] {
  16256. svr.stop();
  16257. t.join();
  16258. });
  16259. svr.wait_until_ready();
  16260. auto error = Error::Success;
  16261. auto sock = detail::create_client_socket(
  16262. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16263. /*connection_timeout_sec=*/2, 0,
  16264. /*read_timeout_sec=*/2, 0,
  16265. /*write_timeout_sec=*/2, 0, std::string(), error);
  16266. ASSERT_NE(INVALID_SOCKET, sock);
  16267. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16268. auto send_request_and_read_response = [&](const std::string &req,
  16269. std::string &out) -> bool {
  16270. auto sent = send(sock, req.data(), req.size(), 0);
  16271. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16272. char buf[4096];
  16273. for (;;) {
  16274. auto n = recv(sock, buf, sizeof(buf), 0);
  16275. if (n <= 0) { return !out.empty(); }
  16276. out.append(buf, static_cast<size_t>(n));
  16277. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16278. }
  16279. };
  16280. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16281. "Host: localhost\r\n"
  16282. "\r\n";
  16283. std::string resp1;
  16284. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16285. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16286. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16287. "Host: localhost\r\n"
  16288. "Connection: close\r\n"
  16289. "\r\n";
  16290. std::string resp2;
  16291. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16292. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16293. EXPECT_EQ(2, delete_count.load());
  16294. }
  16295. namespace no_proxy_test {
  16296. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16297. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16298. // calling listen().
  16299. class ScopedServer {
  16300. public:
  16301. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16302. ~ScopedServer() {
  16303. svr_.stop();
  16304. if (th_.joinable()) { th_.join(); }
  16305. }
  16306. Server &svr() { return svr_; }
  16307. int port() const { return port_; }
  16308. void listen() {
  16309. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16310. svr_.wait_until_ready();
  16311. }
  16312. private:
  16313. Server svr_;
  16314. std::thread th_;
  16315. int port_ = 0;
  16316. };
  16317. class ProxyAndTargetServers {
  16318. public:
  16319. ProxyAndTargetServers() {
  16320. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16321. proxy_hits_++;
  16322. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16323. res.set_content("via-proxy", "text/plain");
  16324. });
  16325. target_.Get(".*", [this](const Request &req, Response &res) {
  16326. target_hits_++;
  16327. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16328. res.set_content("direct", "text/plain");
  16329. });
  16330. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16331. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16332. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16333. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16334. proxy_mock_.wait_until_ready();
  16335. target_.wait_until_ready();
  16336. }
  16337. ~ProxyAndTargetServers() {
  16338. proxy_mock_.stop();
  16339. target_.stop();
  16340. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16341. if (target_thread_.joinable()) { target_thread_.join(); }
  16342. }
  16343. Server &proxy_mock() { return proxy_mock_; }
  16344. Server &target() { return target_; }
  16345. int proxy_port() const { return proxy_port_; }
  16346. int target_port() const { return target_port_; }
  16347. int proxy_hits() const { return proxy_hits_.load(); }
  16348. int target_hits() const { return target_hits_.load(); }
  16349. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16350. void reset_counters() {
  16351. proxy_hits_ = 0;
  16352. target_hits_ = 0;
  16353. last_had_proxy_authz_ = false;
  16354. }
  16355. private:
  16356. Server proxy_mock_;
  16357. Server target_;
  16358. std::thread proxy_thread_;
  16359. std::thread target_thread_;
  16360. int proxy_port_ = 0;
  16361. int target_port_ = 0;
  16362. std::atomic<int> proxy_hits_{0};
  16363. std::atomic<int> target_hits_{0};
  16364. std::atomic<bool> last_had_proxy_authz_{false};
  16365. };
  16366. inline std::unique_ptr<Client> make_client(const std::string &host,
  16367. ProxyAndTargetServers &s) {
  16368. auto cli = detail::make_unique<Client>(host, s.target_port());
  16369. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16370. cli->set_proxy("127.0.0.1", s.proxy_port());
  16371. return cli;
  16372. }
  16373. } // namespace no_proxy_test
  16374. using no_proxy_test::make_client;
  16375. using no_proxy_test::ProxyAndTargetServers;
  16376. TEST(NoProxyTest, ExactHostnameBypasses) {
  16377. ProxyAndTargetServers s;
  16378. auto cli = make_client("example.com", s);
  16379. cli->set_no_proxy({"example.com"});
  16380. auto res = cli->Get("/");
  16381. ASSERT_TRUE(res);
  16382. EXPECT_EQ(0, s.proxy_hits());
  16383. EXPECT_EQ(1, s.target_hits());
  16384. }
  16385. TEST(NoProxyTest, SubdomainBypasses) {
  16386. ProxyAndTargetServers s;
  16387. auto cli = make_client("foo.example.com", s);
  16388. cli->set_no_proxy({"example.com"});
  16389. auto res = cli->Get("/");
  16390. ASSERT_TRUE(res);
  16391. EXPECT_EQ(0, s.proxy_hits());
  16392. EXPECT_EQ(1, s.target_hits());
  16393. }
  16394. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16395. // Regression guard: "evilexample.com" must not be considered a subdomain
  16396. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16397. // check would let traffic bypass the proxy and leak credentials direct
  16398. // to the attacker host.
  16399. ProxyAndTargetServers s;
  16400. auto cli = make_client("evilexample.com", s);
  16401. cli->set_no_proxy({"example.com"});
  16402. auto res = cli->Get("/");
  16403. ASSERT_TRUE(res);
  16404. EXPECT_GE(s.proxy_hits(), 1);
  16405. EXPECT_EQ(0, s.target_hits());
  16406. }
  16407. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16408. ProxyAndTargetServers s;
  16409. auto cli = make_client("example.com.evil.com", s);
  16410. cli->set_no_proxy({"example.com"});
  16411. auto res = cli->Get("/");
  16412. ASSERT_TRUE(res);
  16413. EXPECT_GE(s.proxy_hits(), 1);
  16414. EXPECT_EQ(0, s.target_hits());
  16415. }
  16416. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16417. ProxyAndTargetServers s;
  16418. auto cli = make_client("example.com", s);
  16419. cli->set_no_proxy({".example.com"});
  16420. auto res = cli->Get("/");
  16421. ASSERT_TRUE(res);
  16422. EXPECT_EQ(0, s.proxy_hits());
  16423. EXPECT_EQ(1, s.target_hits());
  16424. }
  16425. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16426. ProxyAndTargetServers s;
  16427. auto cli = make_client("Example.COM", s);
  16428. cli->set_no_proxy({"EXAMPLE.com"});
  16429. auto res = cli->Get("/");
  16430. ASSERT_TRUE(res);
  16431. EXPECT_EQ(0, s.proxy_hits());
  16432. EXPECT_EQ(1, s.target_hits());
  16433. }
  16434. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16435. ProxyAndTargetServers s;
  16436. auto cli = make_client("example.com.", s);
  16437. cli->set_no_proxy({"example.com"});
  16438. auto res = cli->Get("/");
  16439. ASSERT_TRUE(res);
  16440. EXPECT_EQ(0, s.proxy_hits());
  16441. EXPECT_EQ(1, s.target_hits());
  16442. }
  16443. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16444. // Trailing dots must be normalized on BOTH sides — host and entry.
  16445. // An implementation that only strips the host-side trailing dot would
  16446. // fail to match host "example.com" against entry "example.com." because
  16447. // a literal substring search would compare 11 chars against 12.
  16448. ProxyAndTargetServers s;
  16449. auto cli = make_client("example.com", s);
  16450. cli->set_no_proxy({"example.com."});
  16451. auto res = cli->Get("/");
  16452. ASSERT_TRUE(res);
  16453. EXPECT_EQ(0, s.proxy_hits());
  16454. EXPECT_EQ(1, s.target_hits());
  16455. }
  16456. TEST(NoProxyTest, WildcardBypassesEverything) {
  16457. ProxyAndTargetServers s;
  16458. auto cli = make_client("anything.invalid.test", s);
  16459. cli->set_no_proxy({"*"});
  16460. auto res = cli->Get("/");
  16461. ASSERT_TRUE(res);
  16462. EXPECT_EQ(0, s.proxy_hits());
  16463. EXPECT_EQ(1, s.target_hits());
  16464. }
  16465. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16466. ProxyAndTargetServers s;
  16467. Client cli("127.0.0.1", s.target_port());
  16468. cli.set_proxy("127.0.0.1", s.proxy_port());
  16469. cli.set_no_proxy({"127.0.0.1"});
  16470. auto res = cli.Get("/");
  16471. ASSERT_TRUE(res);
  16472. EXPECT_EQ(0, s.proxy_hits());
  16473. EXPECT_EQ(1, s.target_hits());
  16474. }
  16475. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16476. ProxyAndTargetServers s;
  16477. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16478. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16479. cli.set_proxy("127.0.0.1", s.proxy_port());
  16480. cli.set_no_proxy({"::1"});
  16481. auto res = cli.Get("/");
  16482. ASSERT_TRUE(res);
  16483. EXPECT_EQ(0, s.proxy_hits());
  16484. EXPECT_EQ(1, s.target_hits());
  16485. }
  16486. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16487. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16488. // must still be recognized as IPv6 for CIDR matching. Implementations
  16489. // that detect IPv6 only when the host begins with '[' would parse the
  16490. // host as a hostname and miss the match.
  16491. ProxyAndTargetServers s;
  16492. Client cli("fe80::1", s.target_port());
  16493. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16494. cli.set_proxy("127.0.0.1", s.proxy_port());
  16495. cli.set_no_proxy({"fe80::/10"});
  16496. auto res = cli.Get("/");
  16497. ASSERT_TRUE(res);
  16498. EXPECT_EQ(0, s.proxy_hits());
  16499. EXPECT_EQ(1, s.target_hits());
  16500. }
  16501. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16502. ProxyAndTargetServers s;
  16503. Client cli("::1", s.target_port());
  16504. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16505. cli.set_proxy("127.0.0.1", s.proxy_port());
  16506. cli.set_no_proxy({"[::1]"});
  16507. auto res = cli.Get("/");
  16508. ASSERT_TRUE(res);
  16509. EXPECT_EQ(0, s.proxy_hits());
  16510. EXPECT_EQ(1, s.target_hits());
  16511. }
  16512. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16513. ProxyAndTargetServers s;
  16514. Client cli("fe80::1", s.target_port());
  16515. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16516. cli.set_proxy("127.0.0.1", s.proxy_port());
  16517. cli.set_no_proxy({"[fe80::]/10"});
  16518. auto res = cli.Get("/");
  16519. ASSERT_TRUE(res);
  16520. EXPECT_EQ(0, s.proxy_hits());
  16521. EXPECT_EQ(1, s.target_hits());
  16522. }
  16523. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16524. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16525. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16526. // tricks via address-family conversion.
  16527. ProxyAndTargetServers s;
  16528. Client cli("::ffff:127.0.0.1", s.target_port());
  16529. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16530. cli.set_proxy("127.0.0.1", s.proxy_port());
  16531. cli.set_no_proxy({"127.0.0.1"});
  16532. auto res = cli.Get("/");
  16533. ASSERT_TRUE(res);
  16534. EXPECT_GE(s.proxy_hits(), 1);
  16535. EXPECT_EQ(0, s.target_hits());
  16536. }
  16537. TEST(NoProxyTest, IPv4CidrMatch) {
  16538. ProxyAndTargetServers s;
  16539. Client cli("127.0.0.1", s.target_port());
  16540. cli.set_proxy("127.0.0.1", s.proxy_port());
  16541. cli.set_no_proxy({"127.0.0.0/8"});
  16542. auto res = cli.Get("/");
  16543. ASSERT_TRUE(res);
  16544. EXPECT_EQ(0, s.proxy_hits());
  16545. EXPECT_EQ(1, s.target_hits());
  16546. }
  16547. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16548. ProxyAndTargetServers s;
  16549. Client cli("127.0.0.1", s.target_port());
  16550. cli.set_proxy("127.0.0.1", s.proxy_port());
  16551. cli.set_no_proxy({"10.0.0.0/8"});
  16552. auto res = cli.Get("/");
  16553. ASSERT_TRUE(res);
  16554. EXPECT_GE(s.proxy_hits(), 1);
  16555. EXPECT_EQ(0, s.target_hits());
  16556. }
  16557. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16558. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16559. // IPv4 target matches.
  16560. ProxyAndTargetServers s;
  16561. Client cli("127.0.0.1", s.target_port());
  16562. cli.set_proxy("127.0.0.1", s.proxy_port());
  16563. cli.set_no_proxy({"0.0.0.0/0"});
  16564. auto res = cli.Get("/");
  16565. ASSERT_TRUE(res);
  16566. EXPECT_EQ(0, s.proxy_hits());
  16567. EXPECT_EQ(1, s.target_hits());
  16568. }
  16569. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16570. ProxyAndTargetServers s;
  16571. Client cli("127.0.0.1", s.target_port());
  16572. cli.set_proxy("127.0.0.1", s.proxy_port());
  16573. cli.set_no_proxy({"127.0.0.1"});
  16574. auto res = cli.Get("/");
  16575. ASSERT_TRUE(res);
  16576. EXPECT_EQ(0, s.proxy_hits());
  16577. EXPECT_EQ(1, s.target_hits());
  16578. }
  16579. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16580. ProxyAndTargetServers s;
  16581. Client cli("127.0.0.1", s.target_port());
  16582. cli.set_proxy("127.0.0.1", s.proxy_port());
  16583. cli.set_no_proxy({"127.0.0.0/33"});
  16584. auto res = cli.Get("/");
  16585. ASSERT_TRUE(res);
  16586. EXPECT_GE(s.proxy_hits(), 1);
  16587. EXPECT_EQ(0, s.target_hits());
  16588. }
  16589. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16590. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16591. ProxyAndTargetServers s;
  16592. Client cli("127.0.0.1", s.target_port());
  16593. cli.set_proxy("127.0.0.1", s.proxy_port());
  16594. cli.set_no_proxy({"127.0.0.1/"});
  16595. auto res = cli.Get("/");
  16596. ASSERT_TRUE(res);
  16597. EXPECT_GE(s.proxy_hits(), 1);
  16598. EXPECT_EQ(0, s.target_hits());
  16599. }
  16600. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16601. ProxyAndTargetServers s;
  16602. auto cli = make_client("internal.corp", s);
  16603. cli->set_proxy_basic_auth("u", "p");
  16604. cli->set_no_proxy({"internal.corp"});
  16605. auto res = cli->Get("/");
  16606. ASSERT_TRUE(res);
  16607. EXPECT_EQ(1, s.target_hits());
  16608. EXPECT_EQ(0, s.proxy_hits());
  16609. EXPECT_FALSE(s.last_had_proxy_authz())
  16610. << "Proxy-Authorization must not be sent direct to the target";
  16611. }
  16612. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16613. ProxyAndTargetServers s;
  16614. auto cli = make_client("public.example", s);
  16615. cli->set_proxy_basic_auth("u", "p");
  16616. cli->set_no_proxy({"internal.corp"}); // does not match
  16617. auto res = cli->Get("/");
  16618. ASSERT_TRUE(res);
  16619. EXPECT_GE(s.proxy_hits(), 1);
  16620. EXPECT_TRUE(s.last_had_proxy_authz());
  16621. }
  16622. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16623. ProxyAndTargetServers s;
  16624. auto cli = make_client("anything.test", s);
  16625. auto res = cli->Get("/");
  16626. ASSERT_TRUE(res);
  16627. EXPECT_GE(s.proxy_hits(), 1);
  16628. EXPECT_EQ(0, s.target_hits());
  16629. }
  16630. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16631. ProxyAndTargetServers s;
  16632. auto cli = make_client("example.com", s);
  16633. cli->set_no_proxy({"example.com:8080"});
  16634. auto res = cli->Get("/");
  16635. ASSERT_TRUE(res);
  16636. EXPECT_GE(s.proxy_hits(), 1);
  16637. EXPECT_EQ(0, s.target_hits());
  16638. }
  16639. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16640. ProxyAndTargetServers s;
  16641. auto cli = make_client("anything.test", s);
  16642. cli->set_no_proxy({"", " ", "\t"});
  16643. auto res = cli->Get("/");
  16644. ASSERT_TRUE(res);
  16645. EXPECT_GE(s.proxy_hits(), 1);
  16646. EXPECT_EQ(0, s.target_hits());
  16647. }
  16648. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16649. // An entry with leading/trailing whitespace must still match — env-style
  16650. // values are commonly pasted with stray spaces and an implementation
  16651. // that feeds the raw token directly to inet_pton would fail to match
  16652. // valid CIDRs because of the spaces.
  16653. ProxyAndTargetServers s;
  16654. Client cli("127.0.0.1", s.target_port());
  16655. cli.set_proxy("127.0.0.1", s.proxy_port());
  16656. cli.set_no_proxy({" 127.0.0.0/8 "});
  16657. auto res = cli.Get("/");
  16658. ASSERT_TRUE(res);
  16659. EXPECT_EQ(0, s.proxy_hits());
  16660. EXPECT_EQ(1, s.target_hits());
  16661. }
  16662. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16663. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16664. // go direct and must NOT carry Proxy-Authorization.
  16665. std::atomic<int> proxy_hits{0};
  16666. std::atomic<int> target_hits{0};
  16667. std::atomic<bool> target_saw_authz{false};
  16668. no_proxy_test::ScopedServer proxy_mock, target;
  16669. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16670. proxy_hits++;
  16671. res.status = 302;
  16672. res.set_header("Location", "http://127.0.0.1:" +
  16673. std::to_string(target.port()) + "/landed");
  16674. });
  16675. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16676. target_hits++;
  16677. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16678. res.set_content("direct", "text/plain");
  16679. });
  16680. proxy_mock.listen();
  16681. target.listen();
  16682. Client cli("public.example", target.port());
  16683. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16684. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16685. cli.set_proxy_basic_auth("u", "p");
  16686. cli.set_no_proxy({"127.0.0.1"});
  16687. cli.set_follow_location(true);
  16688. auto res = cli.Get("/redir");
  16689. ASSERT_TRUE(res);
  16690. EXPECT_GE(proxy_hits.load(), 1);
  16691. EXPECT_GE(target_hits.load(), 1);
  16692. EXPECT_FALSE(target_saw_authz.load());
  16693. }
  16694. #ifdef CPPHTTPLIB_SSL_ENABLED
  16695. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16696. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16697. // proxy creds would be sent to the (possibly hostile) origin.
  16698. std::atomic<int> target_hits{0};
  16699. std::atomic<bool> target_saw_proxy_authz{false};
  16700. no_proxy_test::ScopedServer target;
  16701. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16702. target_hits++;
  16703. if (req.has_header("Proxy-Authorization")) {
  16704. target_saw_proxy_authz = true;
  16705. }
  16706. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16707. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16708. "nonce=\"abc\", algorithm=MD5");
  16709. });
  16710. target.listen();
  16711. // The proxy address is set to the target's port: the bypass MUST kick in;
  16712. // if it doesn't, the test still routes "via proxy" to the same server and
  16713. // the Proxy-Authorization assertion below catches the leak.
  16714. Client cli("evil.example", target.port());
  16715. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16716. cli.set_proxy("127.0.0.1", target.port());
  16717. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16718. cli.set_no_proxy({"evil.example"});
  16719. auto res = cli.Get("/x");
  16720. ASSERT_TRUE(res);
  16721. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16722. EXPECT_EQ(1, target_hits.load());
  16723. EXPECT_FALSE(target_saw_proxy_authz.load());
  16724. }
  16725. #endif
  16726. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16727. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16728. std::atomic<int> proxy_hits{0};
  16729. std::atomic<int> bypass_hits{0};
  16730. std::atomic<bool> proxy_saw_c_url{false};
  16731. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16732. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16733. proxy_hits++;
  16734. if (req.path.find("/start") != std::string::npos) {
  16735. res.status = 302;
  16736. res.set_header("Location", "http://127.0.0.1:" +
  16737. std::to_string(bypass_server.port()) +
  16738. "/middle");
  16739. return;
  16740. }
  16741. if (req.path.find("/end") != std::string::npos) {
  16742. proxy_saw_c_url = true;
  16743. res.set_content("c-via-proxy", "text/plain");
  16744. return;
  16745. }
  16746. res.set_content("unexpected", "text/plain");
  16747. });
  16748. // public.example's "advertised" port is arbitrary (the request never lands
  16749. // there — it goes through the proxy), but use a dynamic value to stay
  16750. // friendly with sharded parallel runs.
  16751. int public_port = bypass_server.port();
  16752. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16753. bypass_hits++;
  16754. res.status = 302;
  16755. res.set_header("Location", "http://public.example:" +
  16756. std::to_string(public_port) + "/end");
  16757. });
  16758. proxy_mock.listen();
  16759. bypass_server.listen();
  16760. Client cli("public.example", public_port);
  16761. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16762. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16763. cli.set_no_proxy({"127.0.0.1"});
  16764. cli.set_follow_location(true);
  16765. auto res = cli.Get("/start");
  16766. ASSERT_TRUE(res);
  16767. EXPECT_EQ(StatusCode::OK_200, res->status);
  16768. EXPECT_EQ("c-via-proxy", res->body);
  16769. EXPECT_GE(proxy_hits.load(), 2);
  16770. EXPECT_GE(bypass_hits.load(), 1);
  16771. EXPECT_TRUE(proxy_saw_c_url.load());
  16772. }
  16773. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16774. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16775. // request reconnects to the correct endpoint.
  16776. std::atomic<int> proxy_hits{0};
  16777. std::atomic<int> target_hits{0};
  16778. no_proxy_test::ScopedServer proxy_mock, target;
  16779. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16780. proxy_hits++;
  16781. res.set_content("via-proxy", "text/plain");
  16782. });
  16783. target.svr().Get(".*", [&](const Request &, Response &res) {
  16784. target_hits++;
  16785. res.set_content("direct", "text/plain");
  16786. });
  16787. proxy_mock.listen();
  16788. target.listen();
  16789. Client cli("public.example", target.port());
  16790. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16791. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16792. cli.set_keep_alive(true);
  16793. auto res1 = cli.Get("/a");
  16794. ASSERT_TRUE(res1);
  16795. EXPECT_EQ("via-proxy", res1->body);
  16796. EXPECT_EQ(1, proxy_hits.load());
  16797. EXPECT_EQ(0, target_hits.load());
  16798. cli.set_no_proxy({"public.example"});
  16799. auto res2 = cli.Get("/b");
  16800. ASSERT_TRUE(res2);
  16801. EXPECT_EQ("direct", res2->body);
  16802. EXPECT_EQ(1, proxy_hits.load());
  16803. EXPECT_EQ(1, target_hits.load());
  16804. }
  16805. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16806. namespace proxy_tunnel_test {
  16807. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16808. class ScopedSSLServer {
  16809. public:
  16810. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16811. port_ = svr_.bind_to_any_port("127.0.0.1");
  16812. }
  16813. ~ScopedSSLServer() {
  16814. svr_.stop();
  16815. if (th_.joinable()) { th_.join(); }
  16816. }
  16817. SSLServer &svr() { return svr_; }
  16818. int port() const { return port_; }
  16819. void listen() {
  16820. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16821. svr_.wait_until_ready();
  16822. }
  16823. private:
  16824. SSLServer svr_;
  16825. std::thread th_;
  16826. int port_ = 0;
  16827. };
  16828. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16829. class ScopedConnectProxy {
  16830. public:
  16831. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16832. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16833. if (listen_fd_ < 0) { return; }
  16834. int yes = 1;
  16835. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16836. sockaddr_in a{};
  16837. a.sin_family = AF_INET;
  16838. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16839. a.sin_port = 0;
  16840. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16841. return;
  16842. }
  16843. socklen_t alen = sizeof(a);
  16844. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16845. 0) {
  16846. return;
  16847. }
  16848. port_ = ntohs(a.sin_port);
  16849. if (::listen(listen_fd_, 1) != 0) { return; }
  16850. th_ = std::thread([this] { run(); });
  16851. }
  16852. ~ScopedConnectProxy() {
  16853. stop_ = true;
  16854. if (listen_fd_ >= 0) {
  16855. ::shutdown(listen_fd_, SHUT_RDWR);
  16856. ::close(listen_fd_);
  16857. }
  16858. if (th_.joinable()) { th_.join(); }
  16859. }
  16860. int port() const { return port_; }
  16861. int connect_hits() const { return connect_hits_.load(); }
  16862. private:
  16863. void run() {
  16864. while (!stop_.load()) {
  16865. fd_set rfds;
  16866. FD_ZERO(&rfds);
  16867. FD_SET(listen_fd_, &rfds);
  16868. timeval tv{0, 100 * 1000};
  16869. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16870. if (sel <= 0) { continue; }
  16871. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16872. if (client_fd < 0) { continue; }
  16873. std::string req;
  16874. char buf[2048];
  16875. while (req.find("\r\n\r\n") == std::string::npos) {
  16876. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16877. if (n <= 0) { break; }
  16878. req.append(buf, static_cast<size_t>(n));
  16879. }
  16880. if (req.compare(0, 7, "CONNECT") != 0) {
  16881. ::close(client_fd);
  16882. continue;
  16883. }
  16884. connect_hits_++;
  16885. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16886. ::send(client_fd, ok, std::strlen(ok), 0);
  16887. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16888. sockaddr_in o{};
  16889. o.sin_family = AF_INET;
  16890. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16891. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16892. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16893. 0) {
  16894. ::close(client_fd);
  16895. ::close(origin_fd);
  16896. continue;
  16897. }
  16898. auto forward = [](int from, int to) {
  16899. char b[8192];
  16900. for (;;) {
  16901. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16902. if (n <= 0) { break; }
  16903. ssize_t off = 0;
  16904. while (off < n) {
  16905. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16906. if (s <= 0) {
  16907. off = n;
  16908. break;
  16909. }
  16910. off += s;
  16911. }
  16912. }
  16913. ::shutdown(to, SHUT_WR);
  16914. };
  16915. std::thread t1([&] { forward(client_fd, origin_fd); });
  16916. std::thread t2([&] { forward(origin_fd, client_fd); });
  16917. t1.join();
  16918. t2.join();
  16919. ::close(client_fd);
  16920. ::close(origin_fd);
  16921. }
  16922. }
  16923. int forward_port_ = -1;
  16924. int listen_fd_ = -1;
  16925. int port_ = 0;
  16926. std::thread th_;
  16927. std::atomic<bool> stop_{false};
  16928. std::atomic<int> connect_hits_{0};
  16929. };
  16930. } // namespace proxy_tunnel_test
  16931. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16932. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16933. // retry; otherwise proxy creds would be sent to the origin.
  16934. std::atomic<int> origin_hits{0};
  16935. std::atomic<bool> origin_saw_proxy_authz{false};
  16936. proxy_tunnel_test::ScopedSSLServer origin;
  16937. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16938. origin_hits++;
  16939. if (req.has_header("Proxy-Authorization")) {
  16940. origin_saw_proxy_authz = true;
  16941. }
  16942. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16943. res.set_header("Proxy-Authenticate",
  16944. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16945. "algorithm=MD5");
  16946. });
  16947. origin.listen();
  16948. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16949. ASSERT_NE(0, proxy.port());
  16950. SSLClient cli(HOST, origin.port());
  16951. cli.enable_server_certificate_verification(false);
  16952. cli.set_proxy(HOST, proxy.port());
  16953. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16954. auto res = cli.Get("/x");
  16955. ASSERT_TRUE(res);
  16956. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16957. EXPECT_EQ(1, origin_hits.load());
  16958. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16959. EXPECT_EQ(1, proxy.connect_hits());
  16960. }
  16961. #endif