test.cc 625 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267
  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 =
  811. cli.Get("/accept_ok",
  812. {{"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. {{"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 =
  1976. cli.Get(path, {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", {{"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", {{"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", {{"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", {{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 = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4207. ASSERT_TRUE(res);
  4208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4209. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4210. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4211. EXPECT_EQ(true, res->has_header("Content-Range"));
  4212. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4213. EXPECT_EQ(std::string("cd"), res->body);
  4214. }
  4215. TEST_F(ServerTest, StaticFileRanges) {
  4216. auto res =
  4217. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  4218. ASSERT_TRUE(res);
  4219. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4220. EXPECT_TRUE(
  4221. res->get_header_value("Content-Type")
  4222. .find(
  4223. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4224. 0);
  4225. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4226. }
  4227. TEST_F(ServerTest, StaticFileRangeHead) {
  4228. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4229. ASSERT_TRUE(res);
  4230. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4231. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4232. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4233. EXPECT_EQ(true, res->has_header("Content-Range"));
  4234. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4235. }
  4236. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4237. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4240. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4241. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4244. res->get_header_value("Content-Range"));
  4245. EXPECT_EQ("LAST\n", res->body);
  4246. }
  4247. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4248. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4251. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4252. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4253. EXPECT_EQ(true, res->has_header("Content-Range"));
  4254. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4255. }
  4256. TEST_F(ServerTest, StaticFileBigFile) {
  4257. auto res = cli_.Get("/dir/1MB.txt");
  4258. ASSERT_TRUE(res);
  4259. EXPECT_EQ(StatusCode::OK_200, res->status);
  4260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4261. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4262. }
  4263. TEST_F(ServerTest, InvalidBaseDirMount) {
  4264. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4265. }
  4266. TEST_F(ServerTest, Binary) {
  4267. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4268. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4269. "application/octet-stream");
  4270. ASSERT_TRUE(res);
  4271. ASSERT_EQ(StatusCode::OK_200, res->status);
  4272. ASSERT_EQ(4U, res->body.size());
  4273. res = cli_.Put("/binary", binary.data(), binary.size(),
  4274. "application/octet-stream");
  4275. ASSERT_TRUE(res);
  4276. ASSERT_EQ(StatusCode::OK_200, res->status);
  4277. ASSERT_EQ(4U, res->body.size());
  4278. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4279. "application/octet-stream");
  4280. ASSERT_TRUE(res);
  4281. ASSERT_EQ(StatusCode::OK_200, res->status);
  4282. ASSERT_EQ(4U, res->body.size());
  4283. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4284. "application/octet-stream");
  4285. ASSERT_TRUE(res);
  4286. ASSERT_EQ(StatusCode::OK_200, res->status);
  4287. ASSERT_EQ(4U, res->body.size());
  4288. }
  4289. TEST_F(ServerTest, BinaryString) {
  4290. auto binary = std::string("\x00\x01\x02\x03", 4);
  4291. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4292. ASSERT_TRUE(res);
  4293. ASSERT_EQ(StatusCode::OK_200, res->status);
  4294. ASSERT_EQ(4U, res->body.size());
  4295. res = cli_.Put("/binary", binary, "application/octet-stream");
  4296. ASSERT_TRUE(res);
  4297. ASSERT_EQ(StatusCode::OK_200, res->status);
  4298. ASSERT_EQ(4U, res->body.size());
  4299. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4300. ASSERT_TRUE(res);
  4301. ASSERT_EQ(StatusCode::OK_200, res->status);
  4302. ASSERT_EQ(4U, res->body.size());
  4303. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4304. ASSERT_TRUE(res);
  4305. ASSERT_EQ(StatusCode::OK_200, res->status);
  4306. ASSERT_EQ(4U, res->body.size());
  4307. }
  4308. TEST_F(ServerTest, EmptyRequest) {
  4309. auto res = cli_.Get("");
  4310. ASSERT_TRUE(!res);
  4311. EXPECT_EQ(Error::Connection, res.error());
  4312. }
  4313. TEST_F(ServerTest, LongRequest) {
  4314. std::string request;
  4315. for (size_t i = 0; i < 545; i++) {
  4316. request += "/TooLongRequest";
  4317. }
  4318. request += "OK";
  4319. auto res = cli_.Get(request.c_str());
  4320. ASSERT_TRUE(res);
  4321. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4322. }
  4323. TEST_F(ServerTest, TooLongRequest) {
  4324. std::string request;
  4325. for (size_t i = 0; i < 546; i++) {
  4326. request += "/TooLongRequest";
  4327. }
  4328. request += "_NG";
  4329. auto start = std::chrono::high_resolution_clock::now();
  4330. cli_.set_keep_alive(true);
  4331. auto res = cli_.Get(request.c_str());
  4332. auto end = std::chrono::high_resolution_clock::now();
  4333. auto elapsed =
  4334. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4335. .count();
  4336. ASSERT_TRUE(res);
  4337. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4338. EXPECT_LE(elapsed, 1000);
  4339. EXPECT_EQ("close", res->get_header_value("Connection"));
  4340. EXPECT_FALSE(cli_.is_socket_open());
  4341. }
  4342. TEST_F(ServerTest, AlmostTooLongRequest) {
  4343. // test for #2046 - URI length check shouldn't include other content on req
  4344. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4345. // leading /, space, HTTP/1.1)
  4346. std::string request =
  4347. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4348. auto res = cli_.Get(request.c_str());
  4349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4351. }
  4352. TEST_F(ServerTest, LongHeader) {
  4353. Request req;
  4354. req.method = "GET";
  4355. req.path = "/hi";
  4356. std::string host_and_port;
  4357. host_and_port += HOST;
  4358. host_and_port += ":";
  4359. host_and_port += std::to_string(PORT);
  4360. req.headers.emplace("Host", host_and_port.c_str());
  4361. req.headers.emplace("Accept", "*/*");
  4362. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4363. req.headers.emplace(
  4364. "Header-Name",
  4365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  4395. auto error = Error::Success;
  4396. auto ret = cli_.send(req, *res, error);
  4397. ASSERT_TRUE(ret);
  4398. EXPECT_EQ(StatusCode::OK_200, res->status);
  4399. }
  4400. TEST_F(ServerTest, LongQueryValue) {
  4401. auto start = std::chrono::high_resolution_clock::now();
  4402. cli_.set_keep_alive(true);
  4403. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4404. auto end = std::chrono::high_resolution_clock::now();
  4405. auto elapsed =
  4406. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4407. .count();
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4410. EXPECT_LE(elapsed, 1000);
  4411. EXPECT_EQ("close", res->get_header_value("Connection"));
  4412. EXPECT_FALSE(cli_.is_socket_open());
  4413. }
  4414. TEST_F(ServerTest, TooLongQueryValue) {
  4415. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4416. ASSERT_FALSE(res);
  4417. EXPECT_EQ(Error::Read, res.error());
  4418. }
  4419. TEST_F(ServerTest, TooLongHeader) {
  4420. Request req;
  4421. req.method = "GET";
  4422. req.path = "/hi";
  4423. std::string host_and_port;
  4424. host_and_port += HOST;
  4425. host_and_port += ":";
  4426. host_and_port += std::to_string(PORT);
  4427. req.headers.emplace("Host", host_and_port.c_str());
  4428. req.headers.emplace("Accept", "*/*");
  4429. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4430. req.headers.emplace(
  4431. "Header-Name",
  4432. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4433. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  4462. auto error = Error::Success;
  4463. auto ret = cli_.send(req, *res, error);
  4464. ASSERT_TRUE(ret);
  4465. EXPECT_EQ(StatusCode::OK_200, res->status);
  4466. }
  4467. TEST_F(ServerTest, HeaderCountAtLimit) {
  4468. // Test with headers just under the 100 limit
  4469. httplib::Headers headers;
  4470. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4471. // This should keep us just under the 100 header limit
  4472. for (int i = 0; i < 95; i++) {
  4473. std::string name = "X-Test-Header-" + std::to_string(i);
  4474. std::string value = "value" + std::to_string(i);
  4475. headers.emplace(name, value);
  4476. }
  4477. // This should work fine as we're under the limit
  4478. auto res = cli_.Get("/hi", headers);
  4479. EXPECT_TRUE(res);
  4480. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4481. }
  4482. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4483. // Test with many headers to exceed the 100 limit
  4484. httplib::Headers headers;
  4485. // Add 150 headers to definitely exceed the 100 limit
  4486. for (int i = 0; i < 150; i++) {
  4487. std::string name = "X-Test-Header-" + std::to_string(i);
  4488. std::string value = "value" + std::to_string(i);
  4489. headers.emplace(name, value);
  4490. }
  4491. // This should fail due to exceeding header count limit
  4492. cli_.set_keep_alive(true);
  4493. auto res = cli_.Get("/hi", headers);
  4494. // The server should respond with 400 Bad Request
  4495. ASSERT_TRUE(res);
  4496. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4497. EXPECT_EQ("close", res->get_header_value("Connection"));
  4498. EXPECT_FALSE(cli_.is_socket_open());
  4499. }
  4500. TEST_F(ServerTest, PercentEncoding) {
  4501. auto res = cli_.Get("/e%6edwith%");
  4502. ASSERT_TRUE(res);
  4503. EXPECT_EQ(StatusCode::OK_200, res->status);
  4504. }
  4505. TEST_F(ServerTest, PercentEncodingUnicode) {
  4506. auto res = cli_.Get("/e%u006edwith%");
  4507. ASSERT_TRUE(res);
  4508. EXPECT_EQ(StatusCode::OK_200, res->status);
  4509. }
  4510. TEST_F(ServerTest, InvalidPercentEncoding) {
  4511. auto res = cli_.Get("/%endwith%");
  4512. ASSERT_TRUE(res);
  4513. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4514. }
  4515. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4516. auto res = cli_.Get("/%uendwith%");
  4517. ASSERT_TRUE(res);
  4518. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4519. }
  4520. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4521. auto res = cli_.Get("/hello?aaa=bbb%");
  4522. ASSERT_TRUE(res);
  4523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4524. }
  4525. TEST_F(ServerTest, PlusSignEncoding) {
  4526. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4527. ASSERT_TRUE(res);
  4528. EXPECT_EQ(StatusCode::OK_200, res->status);
  4529. EXPECT_EQ("a +b", res->body);
  4530. }
  4531. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4532. // This test simulates a potential DoS attack using many headers
  4533. // to verify our security fix prevents memory exhaustion
  4534. httplib::Headers attack_headers;
  4535. // Attempt to add many headers like an attacker would (200 headers to far
  4536. // exceed limit)
  4537. for (int i = 0; i < 200; i++) {
  4538. std::string name = "X-Attack-Header-" + std::to_string(i);
  4539. std::string value = "attack_payload_" + std::to_string(i);
  4540. attack_headers.emplace(name, value);
  4541. }
  4542. // Try to POST with excessive headers
  4543. cli_.set_keep_alive(true);
  4544. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4545. // Should either fail or return 400 Bad Request due to security limit
  4546. if (res) {
  4547. // If we get a response, it should be 400 Bad Request
  4548. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4549. EXPECT_EQ("close", res->get_header_value("Connection"));
  4550. }
  4551. EXPECT_FALSE(cli_.is_socket_open());
  4552. }
  4553. TEST_F(ServerTest, MultipartFormData) {
  4554. UploadFormDataItems items = {
  4555. {"text1", "text default", "", ""},
  4556. {"text2", "aωb", "", ""},
  4557. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4558. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4559. {"file3", "", "", "application/octet-stream"},
  4560. {"file4", "", "", " application/json tmp-string "}};
  4561. auto res = cli_.Post("/multipart", items);
  4562. ASSERT_TRUE(res);
  4563. EXPECT_EQ(StatusCode::OK_200, res->status);
  4564. }
  4565. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4566. UploadFormDataItems items = {
  4567. {"text", "default text", "", ""},
  4568. {"multi_text1", "aaaaa", "", ""},
  4569. {"multi_text1", "bbbbb", "", ""},
  4570. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4571. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4572. "application/json"},
  4573. };
  4574. auto res = cli_.Post("/multipart/multi_file_values", items);
  4575. ASSERT_TRUE(res);
  4576. EXPECT_EQ(StatusCode::OK_200, res->status);
  4577. }
  4578. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4579. auto res = cli_.Get("/hi");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4583. EXPECT_EQ("Hello World!", res->body);
  4584. }
  4585. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4586. Request req;
  4587. req.method = "POST";
  4588. req.path = "/chunked";
  4589. std::string host_and_port;
  4590. host_and_port += HOST;
  4591. host_and_port += ":";
  4592. host_and_port += std::to_string(PORT);
  4593. req.headers.emplace("Host", host_and_port.c_str());
  4594. req.headers.emplace("Accept", "*/*");
  4595. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4596. req.headers.emplace("Content-Type", "text/plain");
  4597. req.headers.emplace("Content-Length", "0");
  4598. req.headers.emplace(
  4599. "Transfer-Encoding",
  4600. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4601. // Client does not chunk, so make a chunked body manually.
  4602. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4603. auto res = std::make_shared<Response>();
  4604. auto error = Error::Success;
  4605. auto ret = cli_.send(req, *res, error);
  4606. ASSERT_TRUE(ret);
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. }
  4609. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4610. // rather than treat them as valid lengths.
  4611. template <typename ClientT>
  4612. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4613. Request req;
  4614. req.method = "POST";
  4615. req.path = "/chunked";
  4616. std::string host_and_port;
  4617. host_and_port += HOST;
  4618. host_and_port += ":";
  4619. host_and_port += std::to_string(PORT);
  4620. req.headers.emplace("Host", host_and_port.c_str());
  4621. req.headers.emplace("Content-Length", "0");
  4622. req.headers.emplace("Transfer-Encoding", "chunked");
  4623. req.body = body;
  4624. auto res = std::make_shared<Response>();
  4625. auto error = Error::Success;
  4626. ASSERT_TRUE(cli.send(req, *res, error));
  4627. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4628. }
  4629. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4630. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4631. }
  4632. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4633. expect_chunked_body_rejected(
  4634. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4635. }
  4636. TEST_F(ServerTest, GetStreamed2) {
  4637. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4640. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4641. EXPECT_EQ(true, res->has_header("Content-Range"));
  4642. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4643. EXPECT_EQ(std::string("ab"), res->body);
  4644. }
  4645. TEST_F(ServerTest, GetStreamed) {
  4646. auto res = cli_.Get("/streamed");
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(StatusCode::OK_200, res->status);
  4649. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4650. EXPECT_EQ(std::string("aaabbb"), res->body);
  4651. }
  4652. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4653. auto res =
  4654. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. EXPECT_EQ(false, res->has_header("Content-Length"));
  4658. EXPECT_EQ(false, res->has_header("Content-Range"));
  4659. EXPECT_EQ(std::string("abcdefg"), res->body);
  4660. }
  4661. TEST_F(ServerTest, GetStreamedWithRange1) {
  4662. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4663. ASSERT_TRUE(res);
  4664. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4665. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4666. EXPECT_EQ(true, res->has_header("Content-Range"));
  4667. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4668. EXPECT_EQ(std::string("def"), res->body);
  4669. }
  4670. TEST_F(ServerTest, GetStreamedWithRange2) {
  4671. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4674. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4675. EXPECT_EQ(true, res->has_header("Content-Range"));
  4676. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4677. EXPECT_EQ(std::string("bcdefg"), res->body);
  4678. }
  4679. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4680. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4681. ASSERT_TRUE(res);
  4682. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4683. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4684. EXPECT_EQ(true, res->has_header("Content-Range"));
  4685. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4686. EXPECT_EQ(std::string("efg"), res->body);
  4687. }
  4688. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4689. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4692. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4693. EXPECT_EQ(false, res->has_header("Content-Range"));
  4694. EXPECT_EQ(0U, res->body.size());
  4695. }
  4696. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4697. auto res = cli_.Get("/streamed-with-range",
  4698. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4699. "92233720368547758079223372036854775807"}});
  4700. ASSERT_TRUE(res);
  4701. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4702. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4703. EXPECT_EQ(false, res->has_header("Content-Range"));
  4704. EXPECT_EQ(0U, res->body.size());
  4705. }
  4706. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4707. auto res = cli_.Get(
  4708. "/with-range",
  4709. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4710. {"Accept-Encoding", ""}});
  4711. ASSERT_TRUE(res);
  4712. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4713. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4714. EXPECT_EQ(true, res->has_header("Content-Range"));
  4715. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4716. EXPECT_EQ(std::string("abcdefg"), res->body);
  4717. }
  4718. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4719. auto res = cli_.Get("/with-range", {
  4720. {"Range", "bytes=0-"},
  4721. {"Accept-Encoding", ""},
  4722. });
  4723. ASSERT_TRUE(res);
  4724. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4725. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4726. EXPECT_EQ(true, res->has_header("Content-Range"));
  4727. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4728. EXPECT_EQ(std::string("abcdefg"), res->body);
  4729. }
  4730. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4731. auto res =
  4732. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4733. ASSERT_TRUE(res);
  4734. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4735. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4736. EXPECT_EQ(false, res->has_header("Content-Range"));
  4737. EXPECT_EQ(267U, res->body.size());
  4738. // Check that both range contents are present
  4739. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4740. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4741. // Check that Content-Range headers are present for both ranges
  4742. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4743. std::string::npos);
  4744. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4745. std::string::npos);
  4746. }
  4747. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4748. Ranges ranges;
  4749. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4750. ranges.emplace_back(0, -1);
  4751. }
  4752. auto res =
  4753. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4754. ASSERT_TRUE(res);
  4755. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4756. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4757. EXPECT_EQ(false, res->has_header("Content-Range"));
  4758. EXPECT_EQ(0U, res->body.size());
  4759. }
  4760. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4761. auto res =
  4762. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4765. EXPECT_EQ(5U, res->body.size());
  4766. // Check that overlapping ranges are coalesced into a single range
  4767. EXPECT_EQ("bcdef", res->body);
  4768. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4769. // Should be single range, not multipart
  4770. EXPECT_TRUE(res->has_header("Content-Range"));
  4771. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4772. }
  4773. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4774. auto res =
  4775. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4778. EXPECT_EQ(268U, res->body.size());
  4779. // Check that both range contents are present
  4780. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4781. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4782. // Check that Content-Range headers are present for both ranges
  4783. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4784. std::string::npos);
  4785. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4786. std::string::npos);
  4787. }
  4788. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4789. auto res =
  4790. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4793. EXPECT_EQ(269U, res->body.size());
  4794. // Check that both duplicate range contents are present
  4795. size_t first_abc = res->body.find("abc\r\n");
  4796. EXPECT_TRUE(first_abc != std::string::npos);
  4797. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4798. EXPECT_TRUE(second_abc != std::string::npos);
  4799. // Check that Content-Range headers are present for both ranges
  4800. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4801. EXPECT_TRUE(first_range != std::string::npos);
  4802. size_t second_range =
  4803. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4804. EXPECT_TRUE(second_range != std::string::npos);
  4805. }
  4806. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4807. auto res = cli_.Get("/streamed-with-range?error",
  4808. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4809. ASSERT_TRUE(res);
  4810. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4811. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4812. EXPECT_EQ(false, res->has_header("Content-Range"));
  4813. EXPECT_EQ(0U, res->body.size());
  4814. }
  4815. TEST_F(ServerTest, GetStreamedEndless) {
  4816. uint64_t offset = 0;
  4817. auto res = cli_.Get("/streamed-cancel",
  4818. [&](const char * /*data*/, uint64_t data_length) {
  4819. if (offset < 100) {
  4820. offset += data_length;
  4821. return true;
  4822. }
  4823. return false;
  4824. });
  4825. ASSERT_TRUE(!res);
  4826. EXPECT_EQ(Error::Canceled, res.error());
  4827. }
  4828. TEST_F(ServerTest, ClientStop) {
  4829. std::atomic_size_t count{4};
  4830. std::vector<std::thread> threads;
  4831. for (auto i = count.load(); i != 0; --i) {
  4832. threads.emplace_back([&]() {
  4833. auto res = cli_.Get("/streamed-cancel",
  4834. [&](const char *, uint64_t) { return true; });
  4835. --count;
  4836. ASSERT_TRUE(!res);
  4837. EXPECT_TRUE(res.error() == Error::Canceled ||
  4838. res.error() == Error::Read || res.error() == Error::Write);
  4839. });
  4840. }
  4841. std::this_thread::sleep_for(std::chrono::seconds(2));
  4842. while (count != 0) {
  4843. cli_.stop();
  4844. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4845. }
  4846. for (auto &t : threads) {
  4847. t.join();
  4848. }
  4849. }
  4850. TEST_F(ServerTest, GetWithRange1) {
  4851. auto res = cli_.Get("/with-range", {
  4852. make_range_header({{3, 5}}),
  4853. {"Accept-Encoding", ""},
  4854. });
  4855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4856. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4857. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4858. EXPECT_EQ(true, res->has_header("Content-Range"));
  4859. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4860. EXPECT_EQ(std::string("def"), res->body);
  4861. }
  4862. TEST_F(ServerTest, GetWithRange2) {
  4863. auto res = cli_.Get("/with-range", {
  4864. make_range_header({{1, -1}}),
  4865. {"Accept-Encoding", ""},
  4866. });
  4867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4868. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4869. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4870. EXPECT_EQ(true, res->has_header("Content-Range"));
  4871. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4872. EXPECT_EQ(std::string("bcdefg"), res->body);
  4873. }
  4874. TEST_F(ServerTest, GetWithRange3) {
  4875. auto res = cli_.Get("/with-range", {
  4876. make_range_header({{0, 0}}),
  4877. {"Accept-Encoding", ""},
  4878. });
  4879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4880. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4881. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4882. EXPECT_EQ(true, res->has_header("Content-Range"));
  4883. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4884. EXPECT_EQ(std::string("a"), res->body);
  4885. }
  4886. TEST_F(ServerTest, GetWithRange4) {
  4887. auto res = cli_.Get("/with-range", {
  4888. make_range_header({{-1, 2}}),
  4889. {"Accept-Encoding", ""},
  4890. });
  4891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4893. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4894. EXPECT_EQ(true, res->has_header("Content-Range"));
  4895. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4896. EXPECT_EQ(std::string("fg"), res->body);
  4897. }
  4898. TEST_F(ServerTest, GetWithRange5) {
  4899. auto res = cli_.Get("/with-range", {
  4900. make_range_header({{0, 5}}),
  4901. {"Accept-Encoding", ""},
  4902. });
  4903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4904. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4905. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4906. EXPECT_EQ(true, res->has_header("Content-Range"));
  4907. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4908. EXPECT_EQ(std::string("abcdef"), res->body);
  4909. }
  4910. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4911. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4912. ASSERT_TRUE(res);
  4913. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4914. }
  4915. TEST_F(ServerTest, GetWithRangeMultipart) {
  4916. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4917. ASSERT_TRUE(res);
  4918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4919. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4920. EXPECT_EQ(false, res->has_header("Content-Range"));
  4921. EXPECT_EQ(267U, res->body.size());
  4922. }
  4923. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4924. auto res =
  4925. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4926. ASSERT_TRUE(res);
  4927. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4928. }
  4929. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4930. auto res = cli_.Get("/with-range-customized-response",
  4931. {{make_range_header({{1, 2}})}});
  4932. ASSERT_TRUE(res);
  4933. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4934. EXPECT_EQ(true, res->has_header("Content-Length"));
  4935. EXPECT_EQ(false, res->has_header("Content-Range"));
  4936. EXPECT_EQ(JSON_DATA, res->body);
  4937. }
  4938. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4939. auto res = cli_.Get("/with-range-customized-response",
  4940. {{make_range_header({{1, 2}, {4, 5}})}});
  4941. ASSERT_TRUE(res);
  4942. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4943. EXPECT_EQ(true, res->has_header("Content-Length"));
  4944. EXPECT_EQ(false, res->has_header("Content-Range"));
  4945. EXPECT_EQ(JSON_DATA, res->body);
  4946. }
  4947. TEST_F(ServerTest, Issue1772) {
  4948. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4949. ASSERT_TRUE(res);
  4950. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4951. }
  4952. TEST_F(ServerTest, Issue609) {
  4953. auto res = cli_.Delete("/issue609");
  4954. ASSERT_TRUE(res);
  4955. EXPECT_EQ(StatusCode::OK_200, res->status);
  4956. EXPECT_EQ(std::string("ok"), res->body);
  4957. }
  4958. TEST_F(ServerTest, GetStreamedChunked) {
  4959. auto res = cli_.Get("/streamed-chunked");
  4960. ASSERT_TRUE(res);
  4961. EXPECT_EQ(StatusCode::OK_200, res->status);
  4962. EXPECT_EQ(std::string("123456789"), res->body);
  4963. }
  4964. TEST_F(ServerTest, GetStreamedChunked2) {
  4965. auto res = cli_.Get("/streamed-chunked2");
  4966. ASSERT_TRUE(res);
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. EXPECT_EQ(std::string("123456789"), res->body);
  4969. }
  4970. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4971. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4972. ASSERT_TRUE(res);
  4973. EXPECT_EQ(StatusCode::OK_200, res->status);
  4974. EXPECT_EQ(std::string("123456789"), res->body);
  4975. EXPECT_TRUE(res->has_header("Trailer"));
  4976. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4977. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4978. // Trailers are now stored separately from headers (security fix)
  4979. EXPECT_EQ(2U, res->trailers.size());
  4980. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4981. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4982. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4983. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4984. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4985. // Verify trailers are NOT in headers (security verification)
  4986. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4987. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4988. }
  4989. TEST_F(ServerTest, LargeChunkedPost) {
  4990. Request req;
  4991. req.method = "POST";
  4992. req.path = "/large-chunked";
  4993. std::string host_and_port;
  4994. host_and_port += HOST;
  4995. host_and_port += ":";
  4996. host_and_port += std::to_string(PORT);
  4997. req.headers.emplace("Host", host_and_port.c_str());
  4998. req.headers.emplace("Accept", "*/*");
  4999. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5000. req.headers.emplace("Content-Type", "text/plain");
  5001. req.headers.emplace("Content-Length", "0");
  5002. req.headers.emplace("Transfer-Encoding", "chunked");
  5003. std::string long_string(30 * 1024u, 'a');
  5004. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5005. // Attempt to make a large enough post to exceed OS buffers, to test that
  5006. // the server handles short reads if the full chunk data isn't available.
  5007. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5008. auto res = std::make_shared<Response>();
  5009. auto error = Error::Success;
  5010. auto ret = cli_.send(req, *res, error);
  5011. ASSERT_TRUE(ret);
  5012. EXPECT_EQ(StatusCode::OK_200, res->status);
  5013. }
  5014. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5015. auto res = cli_.Get("/remote_addr");
  5016. ASSERT_TRUE(res);
  5017. EXPECT_EQ(StatusCode::OK_200, res->status);
  5018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5019. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5020. }
  5021. TEST_F(ServerTest, GetMethodLocalAddr) {
  5022. auto res = cli_.Get("/local_addr");
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(StatusCode::OK_200, res->status);
  5025. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5026. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5027. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5028. }
  5029. TEST_F(ServerTest, HTTPResponseSplitting) {
  5030. auto res = cli_.Get("/http_response_splitting");
  5031. ASSERT_TRUE(res);
  5032. EXPECT_EQ(StatusCode::OK_200, res->status);
  5033. }
  5034. TEST_F(ServerTest, SlowRequest) {
  5035. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5036. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5037. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5038. }
  5039. #if 0
  5040. TEST_F(ServerTest, SlowPost) {
  5041. char buffer[64 * 1024];
  5042. memset(buffer, 0x42, sizeof(buffer));
  5043. auto res = cli_.Post(
  5044. "/slowpost", 64 * 1024 * 1024,
  5045. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5046. auto ret = sink.write(buffer, sizeof(buffer));
  5047. EXPECT_TRUE(ret);
  5048. return true;
  5049. },
  5050. "text/plain");
  5051. ASSERT_TRUE(res);
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. }
  5054. TEST_F(ServerTest, SlowPostFail) {
  5055. char buffer[64 * 1024];
  5056. memset(buffer, 0x42, sizeof(buffer));
  5057. cli_.set_write_timeout(std::chrono::seconds(0));
  5058. auto res = cli_.Post(
  5059. "/slowpost", 64 * 1024 * 1024,
  5060. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5061. sink.write(buffer, sizeof(buffer));
  5062. return true;
  5063. },
  5064. "text/plain");
  5065. ASSERT_TRUE(!res);
  5066. EXPECT_EQ(Error::Write, res.error());
  5067. }
  5068. #endif
  5069. TEST_F(ServerTest, Put) {
  5070. auto res = cli_.Put("/put", "PUT", "text/plain");
  5071. ASSERT_TRUE(res);
  5072. EXPECT_EQ(StatusCode::OK_200, res->status);
  5073. EXPECT_EQ("PUT", res->body);
  5074. }
  5075. TEST_F(ServerTest, PutWithContentProvider) {
  5076. auto res = cli_.Put(
  5077. "/put", 3,
  5078. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5079. sink.os << "PUT";
  5080. return true;
  5081. },
  5082. "text/plain");
  5083. ASSERT_TRUE(res);
  5084. EXPECT_EQ(StatusCode::OK_200, res->status);
  5085. EXPECT_EQ("PUT", res->body);
  5086. }
  5087. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5088. auto res = cli_.Post(
  5089. "/post", 42,
  5090. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5091. return false;
  5092. },
  5093. "text/plain");
  5094. ASSERT_TRUE(!res);
  5095. EXPECT_EQ(Error::Canceled, res.error());
  5096. }
  5097. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5098. auto res = cli_.Put(
  5099. "/put",
  5100. [](size_t /*offset*/, DataSink &sink) {
  5101. sink.os << "PUT";
  5102. sink.done();
  5103. return true;
  5104. },
  5105. "text/plain");
  5106. ASSERT_TRUE(res);
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. EXPECT_EQ("PUT", res->body);
  5109. }
  5110. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5111. auto res = cli_.Post(
  5112. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5113. "text/plain");
  5114. ASSERT_TRUE(!res);
  5115. EXPECT_EQ(Error::Canceled, res.error());
  5116. }
  5117. TEST_F(ServerTest, PostLoopBack) {
  5118. std::string body;
  5119. auto res = cli_.Post(
  5120. "/post-loopback", 9,
  5121. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5122. EXPECT_EQ(9u, length);
  5123. sink.write("123", 3);
  5124. sink.write("456", 3);
  5125. sink.write("789", 3);
  5126. return true;
  5127. },
  5128. "text/plain",
  5129. [&body](const char *data, size_t data_length) {
  5130. body.append(data, data_length);
  5131. return true;
  5132. });
  5133. ASSERT_TRUE(res);
  5134. EXPECT_EQ(StatusCode::OK_200, res->status);
  5135. EXPECT_EQ("123456789", body);
  5136. }
  5137. TEST_F(ServerTest, PutLoopBack) {
  5138. std::string body;
  5139. auto res = cli_.Put(
  5140. "/put-loopback", 9,
  5141. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5142. EXPECT_EQ(9u, length);
  5143. sink.write("123", 3);
  5144. sink.write("456", 3);
  5145. sink.write("789", 3);
  5146. return true;
  5147. },
  5148. "text/plain",
  5149. [&body](const char *data, size_t data_length) {
  5150. body.append(data, data_length);
  5151. return true;
  5152. });
  5153. ASSERT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. EXPECT_EQ("123456789", body);
  5156. }
  5157. TEST_F(ServerTest, PatchLoopBack) {
  5158. std::string body;
  5159. auto res = cli_.Patch(
  5160. "/patch-loopback", 9,
  5161. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5162. EXPECT_EQ(9u, length);
  5163. sink.write("123", 3);
  5164. sink.write("456", 3);
  5165. sink.write("789", 3);
  5166. return true;
  5167. },
  5168. "text/plain",
  5169. [&body](const char *data, size_t data_length) {
  5170. body.append(data, data_length);
  5171. return true;
  5172. });
  5173. ASSERT_TRUE(res);
  5174. EXPECT_EQ(StatusCode::OK_200, res->status);
  5175. EXPECT_EQ("123456789", body);
  5176. }
  5177. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5178. std::string body;
  5179. auto res = cli_.Post(
  5180. "/post-loopback",
  5181. [](size_t /*offset*/, DataSink &sink) {
  5182. sink.write("123", 3);
  5183. sink.write("456", 3);
  5184. sink.write("789", 3);
  5185. sink.done();
  5186. return true;
  5187. },
  5188. "text/plain",
  5189. [&body](const char *data, size_t data_length) {
  5190. body.append(data, data_length);
  5191. return true;
  5192. });
  5193. ASSERT_TRUE(res);
  5194. EXPECT_EQ(StatusCode::OK_200, res->status);
  5195. EXPECT_EQ("123456789", body);
  5196. }
  5197. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5198. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5199. cli_.set_compress(true);
  5200. auto res = cli_.Put(
  5201. "/put", 3,
  5202. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5203. sink.os << "PUT";
  5204. return true;
  5205. },
  5206. "text/plain");
  5207. ASSERT_TRUE(res);
  5208. EXPECT_EQ(StatusCode::OK_200, res->status);
  5209. EXPECT_EQ("PUT", res->body);
  5210. }
  5211. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5212. cli_.set_compress(true);
  5213. auto res = cli_.Post(
  5214. "/post", 42,
  5215. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5216. return false;
  5217. },
  5218. "text/plain");
  5219. ASSERT_TRUE(!res);
  5220. EXPECT_EQ(Error::Canceled, res.error());
  5221. }
  5222. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5223. cli_.set_compress(true);
  5224. auto res = cli_.Put(
  5225. "/put",
  5226. [](size_t /*offset*/, DataSink &sink) {
  5227. sink.os << "PUT";
  5228. sink.done();
  5229. return true;
  5230. },
  5231. "text/plain");
  5232. ASSERT_TRUE(res);
  5233. EXPECT_EQ(StatusCode::OK_200, res->status);
  5234. EXPECT_EQ("PUT", res->body);
  5235. }
  5236. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5237. cli_.set_compress(true);
  5238. auto res = cli_.Post(
  5239. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5240. "text/plain");
  5241. ASSERT_TRUE(!res);
  5242. EXPECT_EQ(Error::Canceled, res.error());
  5243. }
  5244. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5245. cli_.set_compress(true);
  5246. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5247. ASSERT_TRUE(res);
  5248. EXPECT_EQ(StatusCode::OK_200, res->status);
  5249. EXPECT_EQ(LARGE_DATA, res->body);
  5250. }
  5251. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5252. #ifdef CPPHTTPLIB_SSL_ENABLED
  5253. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5254. Client cli(s.c_str());
  5255. cli.enable_server_certificate_verification(false);
  5256. #else
  5257. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5258. Client cli(s.c_str());
  5259. #endif
  5260. cli.set_compress(true);
  5261. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5262. ASSERT_TRUE(res);
  5263. EXPECT_EQ(StatusCode::OK_200, res->status);
  5264. EXPECT_EQ(LARGE_DATA, res->body);
  5265. // The compressed size should be less than a 10th of the original. May vary
  5266. // depending on the zlib library.
  5267. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5268. static_cast<uint64_t>(10 * 1024 * 1024));
  5269. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5270. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5271. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5272. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5273. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5274. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5275. #endif
  5276. }
  5277. TEST_F(ServerTest, PutContentWithDeflate) {
  5278. cli_.set_compress(false);
  5279. Headers headers;
  5280. headers.emplace("Content-Encoding", "deflate");
  5281. // PUT in deflate format:
  5282. auto res = cli_.Put("/put", headers,
  5283. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5284. ASSERT_TRUE(res);
  5285. EXPECT_EQ(StatusCode::OK_200, res->status);
  5286. EXPECT_EQ("PUT", res->body);
  5287. }
  5288. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5289. Headers headers;
  5290. headers.emplace("Accept-Encoding", "gzip, deflate");
  5291. auto res = cli_.Get("/streamed-chunked", headers);
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. EXPECT_EQ(std::string("123456789"), res->body);
  5295. }
  5296. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5297. Headers headers;
  5298. headers.emplace("Accept-Encoding", "gzip, deflate");
  5299. auto res = cli_.Get("/streamed-chunked2", headers);
  5300. ASSERT_TRUE(res);
  5301. EXPECT_EQ(StatusCode::OK_200, res->status);
  5302. EXPECT_EQ(std::string("123456789"), res->body);
  5303. }
  5304. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5305. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5306. ASSERT_TRUE(res);
  5307. EXPECT_EQ(StatusCode::OK_200, res->status);
  5308. }
  5309. TEST(GzipDecompressor, ChunkedDecompression) {
  5310. std::string data;
  5311. for (size_t i = 0; i < 32 * 1024; ++i) {
  5312. data.push_back(static_cast<char>('a' + i % 26));
  5313. }
  5314. std::string compressed_data;
  5315. {
  5316. httplib::detail::gzip_compressor compressor;
  5317. bool result = compressor.compress(
  5318. data.data(), data.size(),
  5319. /*last=*/true,
  5320. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5321. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5322. compressed_data_size);
  5323. return true;
  5324. });
  5325. ASSERT_TRUE(result);
  5326. }
  5327. std::string decompressed_data;
  5328. {
  5329. httplib::detail::gzip_decompressor decompressor;
  5330. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5331. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5332. size_t chunk_size = 130;
  5333. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5334. chunk_begin += chunk_size) {
  5335. size_t current_chunk_size =
  5336. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5337. bool result = decompressor.decompress(
  5338. compressed_data.data() + chunk_begin, current_chunk_size,
  5339. [&](const char *decompressed_data_chunk,
  5340. size_t decompressed_data_chunk_size) {
  5341. decompressed_data.insert(decompressed_data.size(),
  5342. decompressed_data_chunk,
  5343. decompressed_data_chunk_size);
  5344. return true;
  5345. });
  5346. ASSERT_TRUE(result);
  5347. }
  5348. }
  5349. ASSERT_EQ(data, decompressed_data);
  5350. }
  5351. TEST(GzipDecompressor, DeflateDecompression) {
  5352. std::string original_text = "Raw deflate without gzip";
  5353. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5354. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5355. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5356. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5357. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5358. std::string decompressed_data;
  5359. {
  5360. httplib::detail::gzip_decompressor decompressor;
  5361. bool result = decompressor.decompress(
  5362. compressed_data.data(), compressed_data.size(),
  5363. [&](const char *decompressed_data_chunk,
  5364. size_t decompressed_data_chunk_size) {
  5365. decompressed_data.insert(decompressed_data.size(),
  5366. decompressed_data_chunk,
  5367. decompressed_data_chunk_size);
  5368. return true;
  5369. });
  5370. ASSERT_TRUE(result);
  5371. }
  5372. ASSERT_EQ(original_text, decompressed_data);
  5373. }
  5374. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5375. std::string original_text = "Raw deflate without gzip";
  5376. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5377. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5378. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5379. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5380. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5381. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5382. std::string decompressed_data;
  5383. {
  5384. httplib::detail::gzip_decompressor decompressor;
  5385. bool result = decompressor.decompress(
  5386. compressed_data.data(), compressed_data.size(),
  5387. [&](const char *decompressed_data_chunk,
  5388. size_t decompressed_data_chunk_size) {
  5389. decompressed_data.insert(decompressed_data.size(),
  5390. decompressed_data_chunk,
  5391. decompressed_data_chunk_size);
  5392. return true;
  5393. });
  5394. ASSERT_TRUE(result);
  5395. }
  5396. ASSERT_EQ(original_text, decompressed_data);
  5397. }
  5398. #endif
  5399. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5400. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5401. Headers headers;
  5402. headers.emplace("Accept-Encoding", "br");
  5403. auto res = cli_.Get("/streamed-chunked", headers);
  5404. ASSERT_TRUE(res);
  5405. EXPECT_EQ(StatusCode::OK_200, res->status);
  5406. EXPECT_EQ(std::string("123456789"), res->body);
  5407. }
  5408. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5409. Headers headers;
  5410. headers.emplace("Accept-Encoding", "br");
  5411. auto res = cli_.Get("/streamed-chunked2", headers);
  5412. ASSERT_TRUE(res);
  5413. EXPECT_EQ(StatusCode::OK_200, res->status);
  5414. EXPECT_EQ(std::string("123456789"), res->body);
  5415. }
  5416. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5417. cli_.set_compress(true);
  5418. auto res = cli_.Put(
  5419. "/put", 3,
  5420. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5421. sink.os << "PUT";
  5422. return true;
  5423. },
  5424. "text/plain");
  5425. ASSERT_TRUE(res);
  5426. EXPECT_EQ(StatusCode::OK_200, res->status);
  5427. EXPECT_EQ("PUT", res->body);
  5428. }
  5429. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5430. cli_.set_compress(true);
  5431. auto res = cli_.Put(
  5432. "/put",
  5433. [](size_t /*offset*/, DataSink &sink) {
  5434. sink.os << "PUT";
  5435. sink.done();
  5436. return true;
  5437. },
  5438. "text/plain");
  5439. ASSERT_TRUE(res);
  5440. EXPECT_EQ(StatusCode::OK_200, res->status);
  5441. EXPECT_EQ("PUT", res->body);
  5442. }
  5443. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5444. cli_.set_compress(true);
  5445. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5446. ASSERT_TRUE(res);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. EXPECT_EQ(LARGE_DATA, res->body);
  5449. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5450. }
  5451. #endif
  5452. TEST_F(ServerTest, Patch) {
  5453. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ(StatusCode::OK_200, res->status);
  5456. EXPECT_EQ("PATCH", res->body);
  5457. }
  5458. TEST_F(ServerTest, Delete) {
  5459. auto res = cli_.Delete("/delete");
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ(StatusCode::OK_200, res->status);
  5462. EXPECT_EQ("DELETE", res->body);
  5463. }
  5464. TEST_F(ServerTest, DeleteContentReceiver) {
  5465. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5466. ASSERT_TRUE(res);
  5467. EXPECT_EQ(StatusCode::OK_200, res->status);
  5468. EXPECT_EQ("content", res->body);
  5469. }
  5470. TEST_F(ServerTest, Options) {
  5471. auto res = cli_.Options("*");
  5472. ASSERT_TRUE(res);
  5473. EXPECT_EQ(StatusCode::OK_200, res->status);
  5474. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5475. EXPECT_TRUE(res->body.empty());
  5476. }
  5477. TEST_F(ServerTest, URL) {
  5478. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5479. ASSERT_TRUE(res);
  5480. EXPECT_EQ(StatusCode::OK_200, res->status);
  5481. }
  5482. TEST_F(ServerTest, ArrayParam) {
  5483. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. }
  5487. TEST_F(ServerTest, ArrayParamValues) {
  5488. auto res =
  5489. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5490. ASSERT_TRUE(res);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. }
  5493. TEST_F(ServerTest, NoMultipleHeaders) {
  5494. Headers headers = {{"Content-Length", "5"}};
  5495. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5496. "text/plain");
  5497. ASSERT_TRUE(res);
  5498. EXPECT_EQ(StatusCode::OK_200, res->status);
  5499. }
  5500. TEST_F(ServerTest, PostContentReceiver) {
  5501. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5502. ASSERT_TRUE(res);
  5503. ASSERT_EQ(StatusCode::OK_200, res->status);
  5504. ASSERT_EQ("content", res->body);
  5505. }
  5506. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5507. UploadFormDataItems items = {
  5508. {"text1", "text default", "", ""},
  5509. {"text2", "aωb", "", ""},
  5510. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5511. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5512. {"file3", "", "", "application/octet-stream"},
  5513. };
  5514. auto res = cli_.Post("/content_receiver", items);
  5515. ASSERT_TRUE(res);
  5516. EXPECT_EQ(StatusCode::OK_200, res->status);
  5517. }
  5518. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5519. UploadFormDataItems items = {
  5520. {"text1", "text default", "", ""},
  5521. {"text2", "aωb", "", ""},
  5522. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5523. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5524. {"file3", "", "", "application/octet-stream"},
  5525. };
  5526. auto boundary = std::string("+++++");
  5527. std::string body;
  5528. for (const auto &item : items) {
  5529. body += "--" + boundary + "\r\n";
  5530. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5531. if (!item.filename.empty()) {
  5532. body += "; filename=\"" + item.filename + "\"";
  5533. }
  5534. body += "\r\n";
  5535. if (!item.content_type.empty()) {
  5536. body += "Content-Type: " + item.content_type + "\r\n";
  5537. }
  5538. body += "\r\n";
  5539. body += item.content + "\r\n";
  5540. }
  5541. body += "--" + boundary + "--\r\n";
  5542. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5543. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5544. ASSERT_TRUE(res);
  5545. EXPECT_EQ(StatusCode::OK_200, res->status);
  5546. }
  5547. TEST(MultipartFormDataTest, FieldEscaping) {
  5548. Server svr;
  5549. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5550. const ContentReader &content_reader) {
  5551. ASSERT_TRUE(req.is_multipart_form_data());
  5552. std::vector<FormData> received;
  5553. content_reader(
  5554. [&](const FormData &file) {
  5555. received.push_back(file);
  5556. return true;
  5557. },
  5558. [&](const char *data, size_t data_length) {
  5559. received.back().content.append(data, data_length);
  5560. return true;
  5561. });
  5562. // '"', CR and LF in names and filenames are escaped following the
  5563. // WHATWG HTML standard, so each part still parses as a single part
  5564. // with no injected headers. Content types get CR/LF escaped too,
  5565. // while '"' (legal there, e.g. quoted charset) is preserved.
  5566. ASSERT_EQ(4U, received.size());
  5567. EXPECT_EQ("na%22me", received[0].name);
  5568. EXPECT_EQ("quoted name", received[0].content);
  5569. EXPECT_EQ("file", received[1].name);
  5570. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5571. received[1].filename);
  5572. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5573. EXPECT_EQ("injected", received[1].content);
  5574. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5575. EXPECT_EQ("my%22file.txt", received[2].filename);
  5576. EXPECT_EQ("cr lf name", received[2].content);
  5577. EXPECT_EQ("typed", received[3].name);
  5578. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5579. received[3].content_type);
  5580. EXPECT_EQ("typed content", received[3].content);
  5581. });
  5582. auto port = svr.bind_to_any_port("localhost");
  5583. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5584. auto se = detail::scope_exit([&] {
  5585. svr.stop();
  5586. t.join();
  5587. ASSERT_FALSE(svr.is_running());
  5588. });
  5589. svr.wait_until_ready();
  5590. Client cli("localhost", port);
  5591. UploadFormDataItems items = {
  5592. {"na\"me", "quoted name", "", ""},
  5593. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5594. "application/octet-stream"},
  5595. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5596. {"typed", "typed content", "",
  5597. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5598. };
  5599. auto res = cli.Post("/post", items);
  5600. ASSERT_TRUE(res);
  5601. EXPECT_EQ(StatusCode::OK_200, res->status);
  5602. }
  5603. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5604. const UploadFormDataItems items = {
  5605. {"name1", "Content 1", "", ""},
  5606. {"name2", "Content 2", "file2.txt", "text/plain"},
  5607. };
  5608. Server svr;
  5609. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5610. const ContentReader &content_reader) {
  5611. ASSERT_TRUE(req.is_multipart_form_data());
  5612. std::vector<FormData> received;
  5613. content_reader(
  5614. [&](const FormData &file) {
  5615. received.push_back(file);
  5616. return true;
  5617. },
  5618. [&](const char *data, size_t data_length) {
  5619. received.back().content.append(data, data_length);
  5620. return true;
  5621. });
  5622. ASSERT_EQ(2U, received.size());
  5623. EXPECT_EQ("name1", received[0].name);
  5624. EXPECT_EQ("Content 1", received[0].content);
  5625. EXPECT_EQ("name2", received[1].name);
  5626. EXPECT_EQ("Content 2", received[1].content);
  5627. EXPECT_EQ("file2.txt", received[1].filename);
  5628. EXPECT_EQ("text/plain", received[1].content_type);
  5629. });
  5630. auto port = svr.bind_to_any_port("localhost");
  5631. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5632. auto se = detail::scope_exit([&] {
  5633. svr.stop();
  5634. t.join();
  5635. ASSERT_FALSE(svr.is_running());
  5636. });
  5637. svr.wait_until_ready();
  5638. Client cli("localhost", port);
  5639. // Whole-body serialization with a generated boundary
  5640. {
  5641. MultipartFormDataWriter writer;
  5642. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5643. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5644. writer.content_type());
  5645. auto body = writer.serialize(items);
  5646. EXPECT_EQ(body.size(), writer.content_length(items));
  5647. auto res = cli.Post("/post", body, writer.content_type());
  5648. ASSERT_TRUE(res);
  5649. EXPECT_EQ(StatusCode::OK_200, res->status);
  5650. }
  5651. // Per-part framing with a custom boundary via a content provider
  5652. {
  5653. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5654. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5655. MultipartFormDataWriter writer("custom-boundary_123");
  5656. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5657. std::string body;
  5658. for (const auto &item : items) {
  5659. body += writer.item_begin(item);
  5660. body += item.content;
  5661. body += MultipartFormDataWriter::item_end();
  5662. }
  5663. body += writer.finish();
  5664. EXPECT_EQ(body.size(), writer.content_length(items));
  5665. auto res = cli.Post(
  5666. "/post", body.size(),
  5667. [&](size_t offset, size_t length, DataSink &sink) {
  5668. sink.write(body.data() + offset, length);
  5669. return true;
  5670. },
  5671. writer.content_type());
  5672. ASSERT_TRUE(res);
  5673. EXPECT_EQ(StatusCode::OK_200, res->status);
  5674. }
  5675. }
  5676. TEST_F(ServerTest, PostContentReceiverGzip) {
  5677. cli_.set_compress(true);
  5678. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5679. ASSERT_TRUE(res);
  5680. ASSERT_EQ(StatusCode::OK_200, res->status);
  5681. ASSERT_EQ("content", res->body);
  5682. }
  5683. TEST_F(ServerTest, PutContentReceiver) {
  5684. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5685. ASSERT_TRUE(res);
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. ASSERT_EQ("content", res->body);
  5688. }
  5689. TEST_F(ServerTest, PatchContentReceiver) {
  5690. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5691. ASSERT_TRUE(res);
  5692. ASSERT_EQ(StatusCode::OK_200, res->status);
  5693. ASSERT_EQ("content", res->body);
  5694. }
  5695. template <typename ClientType>
  5696. void TestWithHeadersAndContentReceiver(
  5697. ClientType &cli,
  5698. std::function<Result(ClientType &, const std::string &, const Headers &,
  5699. const std::string &, const std::string &,
  5700. ContentReceiver, DownloadProgress)>
  5701. request_func) {
  5702. Headers headers;
  5703. headers.emplace("X-Custom-Header", "test-value");
  5704. std::string received_body;
  5705. auto res = request_func(
  5706. cli, "/content_receiver", headers, "content", "application/json",
  5707. [&](const char *data, size_t data_length) {
  5708. received_body.append(data, data_length);
  5709. return true;
  5710. },
  5711. nullptr);
  5712. ASSERT_TRUE(res);
  5713. EXPECT_EQ(StatusCode::OK_200, res->status);
  5714. EXPECT_EQ("content", received_body);
  5715. }
  5716. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5717. #ifdef CPPHTTPLIB_SSL_ENABLED
  5718. using ClientT = SSLClient;
  5719. #else
  5720. using ClientT = Client;
  5721. #endif
  5722. TestWithHeadersAndContentReceiver<ClientT>(
  5723. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5724. const std::string &body, const std::string &content_type,
  5725. ContentReceiver receiver, DownloadProgress progress) {
  5726. return cli.Post(path, headers, body, content_type, receiver, progress);
  5727. });
  5728. }
  5729. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5730. #ifdef CPPHTTPLIB_SSL_ENABLED
  5731. using ClientT = SSLClient;
  5732. #else
  5733. using ClientT = Client;
  5734. #endif
  5735. TestWithHeadersAndContentReceiver<ClientT>(
  5736. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5737. const std::string &body, const std::string &content_type,
  5738. ContentReceiver receiver, DownloadProgress progress) {
  5739. return cli.Put(path, headers, body, content_type, receiver, progress);
  5740. });
  5741. }
  5742. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5743. #ifdef CPPHTTPLIB_SSL_ENABLED
  5744. using ClientT = SSLClient;
  5745. #else
  5746. using ClientT = Client;
  5747. #endif
  5748. TestWithHeadersAndContentReceiver<ClientT>(
  5749. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5750. const std::string &body, const std::string &content_type,
  5751. ContentReceiver receiver, DownloadProgress progress) {
  5752. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5753. });
  5754. }
  5755. template <typename ClientType>
  5756. void TestWithHeadersAndContentReceiverWithProgress(
  5757. ClientType &cli,
  5758. std::function<Result(ClientType &, const std::string &, const Headers &,
  5759. const std::string &, const std::string &,
  5760. ContentReceiver, DownloadProgress)>
  5761. request_func) {
  5762. Headers headers;
  5763. headers.emplace("X-Test-Header", "progress-test");
  5764. std::string received_body;
  5765. auto progress_called = false;
  5766. auto res = request_func(
  5767. cli, "/content_receiver", headers, "content", "text/plain",
  5768. [&](const char *data, size_t data_length) {
  5769. received_body.append(data, data_length);
  5770. return true;
  5771. },
  5772. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5773. progress_called = true;
  5774. return true;
  5775. });
  5776. ASSERT_TRUE(res);
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. EXPECT_EQ("content", received_body);
  5779. EXPECT_TRUE(progress_called);
  5780. }
  5781. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5782. #ifdef CPPHTTPLIB_SSL_ENABLED
  5783. using ClientT = SSLClient;
  5784. #else
  5785. using ClientT = Client;
  5786. #endif
  5787. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5788. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5789. const std::string &body, const std::string &content_type,
  5790. ContentReceiver receiver, DownloadProgress progress) {
  5791. return cli.Post(path, headers, body, content_type, receiver, progress);
  5792. });
  5793. }
  5794. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5795. #ifdef CPPHTTPLIB_SSL_ENABLED
  5796. using ClientT = SSLClient;
  5797. #else
  5798. using ClientT = Client;
  5799. #endif
  5800. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5801. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5802. const std::string &body, const std::string &content_type,
  5803. ContentReceiver receiver, DownloadProgress progress) {
  5804. return cli.Put(path, headers, body, content_type, receiver, progress);
  5805. });
  5806. }
  5807. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5808. #ifdef CPPHTTPLIB_SSL_ENABLED
  5809. using ClientT = SSLClient;
  5810. #else
  5811. using ClientT = Client;
  5812. #endif
  5813. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5814. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5815. const std::string &body, const std::string &content_type,
  5816. ContentReceiver receiver, DownloadProgress progress) {
  5817. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5818. });
  5819. }
  5820. template <typename ClientType>
  5821. void TestWithHeadersAndContentReceiverError(
  5822. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5823. const Headers &, const std::string &,
  5824. const std::string &, ContentReceiver)>
  5825. request_func) {
  5826. Headers headers;
  5827. headers.emplace("X-Error-Test", "true");
  5828. std::string received_body;
  5829. auto receiver_failed = false;
  5830. auto res =
  5831. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5832. [&](const char *data, size_t data_length) {
  5833. received_body.append(data, data_length);
  5834. receiver_failed = true;
  5835. return false;
  5836. });
  5837. ASSERT_FALSE(res);
  5838. EXPECT_TRUE(receiver_failed);
  5839. }
  5840. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5841. #ifdef CPPHTTPLIB_SSL_ENABLED
  5842. using ClientT = SSLClient;
  5843. #else
  5844. using ClientT = Client;
  5845. #endif
  5846. TestWithHeadersAndContentReceiverError<ClientT>(
  5847. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5848. const std::string &body, const std::string &content_type,
  5849. ContentReceiver receiver) {
  5850. return cli.Post(path, headers, body, content_type, receiver);
  5851. });
  5852. }
  5853. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5854. #ifdef CPPHTTPLIB_SSL_ENABLED
  5855. using ClientT = SSLClient;
  5856. #else
  5857. using ClientT = Client;
  5858. #endif
  5859. TestWithHeadersAndContentReceiverError<ClientT>(
  5860. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5861. const std::string &body, const std::string &content_type,
  5862. ContentReceiver receiver) {
  5863. return cli.Put(path, headers, body, content_type, receiver);
  5864. });
  5865. }
  5866. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5867. #ifdef CPPHTTPLIB_SSL_ENABLED
  5868. using ClientT = SSLClient;
  5869. #else
  5870. using ClientT = Client;
  5871. #endif
  5872. TestWithHeadersAndContentReceiverError<ClientT>(
  5873. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5874. const std::string &body, const std::string &content_type,
  5875. ContentReceiver receiver) {
  5876. return cli.Patch(path, headers, body, content_type, receiver);
  5877. });
  5878. }
  5879. TEST_F(ServerTest, PostQueryStringAndBody) {
  5880. auto res =
  5881. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5882. ASSERT_TRUE(res);
  5883. ASSERT_EQ(StatusCode::OK_200, res->status);
  5884. }
  5885. TEST_F(ServerTest, HTTP2Magic) {
  5886. Request req;
  5887. req.method = "PRI";
  5888. req.path = "*";
  5889. req.body = "SM";
  5890. auto res = std::make_shared<Response>();
  5891. auto error = Error::Success;
  5892. auto ret = cli_.send(req, *res, error);
  5893. ASSERT_TRUE(ret);
  5894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5895. }
  5896. TEST_F(ServerTest, KeepAlive) {
  5897. auto res = cli_.Get("/hi");
  5898. ASSERT_TRUE(res);
  5899. EXPECT_EQ(StatusCode::OK_200, res->status);
  5900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5901. EXPECT_EQ("Hello World!", res->body);
  5902. res = cli_.Get("/hi");
  5903. ASSERT_TRUE(res);
  5904. EXPECT_EQ(StatusCode::OK_200, res->status);
  5905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5906. EXPECT_EQ("Hello World!", res->body);
  5907. 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("/not-exist");
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5915. res = cli_.Post("/empty", "", "text/plain");
  5916. ASSERT_TRUE(res);
  5917. EXPECT_EQ(StatusCode::OK_200, res->status);
  5918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5919. EXPECT_EQ("empty", res->body);
  5920. EXPECT_EQ("close", res->get_header_value("Connection"));
  5921. res = cli_.Post(
  5922. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5923. "text/plain");
  5924. ASSERT_TRUE(res);
  5925. EXPECT_EQ(StatusCode::OK_200, res->status);
  5926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5927. EXPECT_EQ("empty", res->body);
  5928. cli_.set_keep_alive(false);
  5929. res = cli_.Get("/last-request");
  5930. ASSERT_TRUE(res);
  5931. EXPECT_EQ(StatusCode::OK_200, res->status);
  5932. EXPECT_EQ("close", res->get_header_value("Connection"));
  5933. }
  5934. TEST_F(ServerTest, TooManyRedirect) {
  5935. cli_.set_follow_location(true);
  5936. auto res = cli_.Get("/redirect/0");
  5937. ASSERT_TRUE(!res);
  5938. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5939. }
  5940. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5941. Request req;
  5942. req.method = "FOOBAR";
  5943. req.path = "/hi";
  5944. cli_.set_keep_alive(true);
  5945. auto res = cli_.send(req);
  5946. ASSERT_TRUE(res);
  5947. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5948. EXPECT_EQ("close", res->get_header_value("Connection"));
  5949. EXPECT_FALSE(cli_.is_socket_open());
  5950. }
  5951. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5952. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5953. TEST_F(ServerTest, Gzip) {
  5954. Headers headers;
  5955. headers.emplace("Accept-Encoding", "gzip, deflate");
  5956. auto res = cli_.Get("/compress", headers);
  5957. ASSERT_TRUE(res);
  5958. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5960. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5961. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5962. "7890123456789012345678901234567890",
  5963. res->body);
  5964. EXPECT_EQ(StatusCode::OK_200, res->status);
  5965. }
  5966. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5967. Headers headers;
  5968. headers.emplace("Accept-Encoding", "gzip, deflate");
  5969. auto res = cli_.Get("/compress-with-charset", headers);
  5970. ASSERT_TRUE(res);
  5971. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5972. EXPECT_EQ("application/json; charset=utf-8",
  5973. res->get_header_value("Content-Type"));
  5974. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5975. "7890123456789012345678901234567890",
  5976. res->body);
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. }
  5979. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5980. Headers headers;
  5981. headers.emplace("Accept-Encoding", "");
  5982. auto res = cli_.Get("/compress", headers);
  5983. ASSERT_TRUE(res);
  5984. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5985. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5986. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5987. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5988. "7890123456789012345678901234567890",
  5989. res->body);
  5990. EXPECT_EQ(StatusCode::OK_200, res->status);
  5991. }
  5992. TEST_F(ServerTest, GzipWithContentReceiver) {
  5993. Headers headers;
  5994. headers.emplace("Accept-Encoding", "gzip, deflate");
  5995. std::string body;
  5996. auto res = cli_.Get("/compress", headers,
  5997. [&](const char *data, uint64_t data_length) {
  5998. EXPECT_EQ(100U, data_length);
  5999. body.append(data, data_length);
  6000. return true;
  6001. });
  6002. ASSERT_TRUE(res);
  6003. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6005. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6006. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6007. "7890123456789012345678901234567890",
  6008. body);
  6009. EXPECT_EQ(StatusCode::OK_200, res->status);
  6010. }
  6011. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6012. Headers headers;
  6013. headers.emplace("Accept-Encoding", "gzip, deflate");
  6014. cli_.set_decompress(false);
  6015. auto res = cli_.Get("/compress", headers);
  6016. ASSERT_TRUE(res);
  6017. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6019. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6020. EXPECT_EQ(33U, res->body.size());
  6021. EXPECT_EQ(StatusCode::OK_200, res->status);
  6022. }
  6023. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6024. Headers headers;
  6025. headers.emplace("Accept-Encoding", "");
  6026. std::string body;
  6027. auto res = cli_.Get("/compress", headers,
  6028. [&](const char *data, uint64_t data_length) {
  6029. EXPECT_EQ(100U, data_length);
  6030. body.append(data, data_length);
  6031. return true;
  6032. });
  6033. ASSERT_TRUE(res);
  6034. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6036. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6037. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6038. "7890123456789012345678901234567890",
  6039. body);
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. }
  6042. TEST_F(ServerTest, NoGzip) {
  6043. Headers headers;
  6044. headers.emplace("Accept-Encoding", "gzip, deflate");
  6045. auto res = cli_.Get("/nocompress", headers);
  6046. ASSERT_TRUE(res);
  6047. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6048. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6049. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6050. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6051. "7890123456789012345678901234567890",
  6052. res->body);
  6053. EXPECT_EQ(StatusCode::OK_200, res->status);
  6054. }
  6055. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6056. Headers headers;
  6057. headers.emplace("Accept-Encoding", "gzip, deflate");
  6058. std::string body;
  6059. auto res = cli_.Get("/nocompress", headers,
  6060. [&](const char *data, uint64_t data_length) {
  6061. EXPECT_EQ(100U, data_length);
  6062. body.append(data, data_length);
  6063. return true;
  6064. });
  6065. ASSERT_TRUE(res);
  6066. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6067. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6068. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6069. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6070. "7890123456789012345678901234567890",
  6071. body);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. }
  6074. TEST_F(ServerTest, MultipartFormDataGzip) {
  6075. UploadFormDataItems items = {
  6076. {"key1", "test", "", ""},
  6077. {"key2", "--abcdefg123", "", ""},
  6078. };
  6079. cli_.set_compress(true);
  6080. auto res = cli_.Post("/compress-multipart", items);
  6081. ASSERT_TRUE(res);
  6082. EXPECT_EQ(StatusCode::OK_200, res->status);
  6083. }
  6084. #endif
  6085. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6086. TEST_F(ServerTest, Brotli) {
  6087. Headers headers;
  6088. headers.emplace("Accept-Encoding", "br");
  6089. auto res = cli_.Get("/compress", headers);
  6090. ASSERT_TRUE(res);
  6091. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6093. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6094. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6095. "7890123456789012345678901234567890",
  6096. res->body);
  6097. EXPECT_EQ(StatusCode::OK_200, res->status);
  6098. }
  6099. #endif
  6100. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6101. TEST_F(ServerTest, Zstd) {
  6102. Headers headers;
  6103. headers.emplace("Accept-Encoding", "zstd");
  6104. auto res = cli_.Get("/compress", headers);
  6105. ASSERT_TRUE(res);
  6106. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6108. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6109. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6110. "7890123456789012345678901234567890",
  6111. res->body);
  6112. EXPECT_EQ(StatusCode::OK_200, res->status);
  6113. }
  6114. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6115. Headers headers;
  6116. headers.emplace("Accept-Encoding", "");
  6117. auto res = cli_.Get("/compress", headers);
  6118. ASSERT_TRUE(res);
  6119. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6121. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6122. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6123. "7890123456789012345678901234567890",
  6124. res->body);
  6125. EXPECT_EQ(StatusCode::OK_200, res->status);
  6126. }
  6127. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6128. Headers headers;
  6129. headers.emplace("Accept-Encoding", "zstd");
  6130. std::string body;
  6131. auto res = cli_.Get("/compress", headers,
  6132. [&](const char *data, uint64_t data_length) {
  6133. EXPECT_EQ(100U, data_length);
  6134. body.append(data, data_length);
  6135. return true;
  6136. });
  6137. ASSERT_TRUE(res);
  6138. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6139. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6140. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6141. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6142. "7890123456789012345678901234567890",
  6143. body);
  6144. EXPECT_EQ(StatusCode::OK_200, res->status);
  6145. }
  6146. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6147. Headers headers;
  6148. headers.emplace("Accept-Encoding", "zstd");
  6149. cli_.set_decompress(false);
  6150. auto res = cli_.Get("/compress", headers);
  6151. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6152. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6153. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6154. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6155. ASSERT_TRUE(res);
  6156. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6158. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6159. EXPECT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ(26U, res->body.size());
  6161. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6162. 0);
  6163. }
  6164. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6165. Headers headers;
  6166. headers.emplace("Accept-Encoding", "");
  6167. std::string body;
  6168. auto res = cli_.Get("/compress", headers,
  6169. [&](const char *data, uint64_t data_length) {
  6170. EXPECT_EQ(100U, data_length);
  6171. body.append(data, data_length);
  6172. return true;
  6173. });
  6174. ASSERT_TRUE(res);
  6175. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6177. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6178. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6179. "7890123456789012345678901234567890",
  6180. body);
  6181. EXPECT_EQ(StatusCode::OK_200, res->status);
  6182. }
  6183. TEST_F(ServerTest, NoZstd) {
  6184. Headers headers;
  6185. headers.emplace("Accept-Encoding", "zstd");
  6186. auto res = cli_.Get("/nocompress", headers);
  6187. ASSERT_TRUE(res);
  6188. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6189. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6190. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6191. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6192. "7890123456789012345678901234567890",
  6193. res->body);
  6194. EXPECT_EQ(StatusCode::OK_200, res->status);
  6195. }
  6196. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6197. Headers headers;
  6198. headers.emplace("Accept-Encoding", "zstd");
  6199. std::string body;
  6200. auto res = cli_.Get("/nocompress", headers,
  6201. [&](const char *data, uint64_t data_length) {
  6202. EXPECT_EQ(100U, data_length);
  6203. body.append(data, data_length);
  6204. return true;
  6205. });
  6206. ASSERT_TRUE(res);
  6207. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6208. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6209. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6210. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6211. "7890123456789012345678901234567890",
  6212. body);
  6213. EXPECT_EQ(StatusCode::OK_200, res->status);
  6214. }
  6215. // TODO: How to enable zstd ??
  6216. TEST_F(ServerTest, MultipartFormDataZstd) {
  6217. UploadFormDataItems items = {
  6218. {"key1", "test", "", ""},
  6219. {"key2", "--abcdefg123", "", ""},
  6220. };
  6221. Headers headers;
  6222. headers.emplace("Accept-Encoding", "zstd");
  6223. cli_.set_compress(true);
  6224. auto res = cli_.Post("/compress-multipart", headers, items);
  6225. ASSERT_TRUE(res);
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6229. Headers headers;
  6230. headers.emplace("Accept-Encoding", "zstd");
  6231. cli_.set_compress(true);
  6232. auto res = cli_.Put(
  6233. "/put", headers, 3,
  6234. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6235. sink.os << "PUT";
  6236. return true;
  6237. },
  6238. "text/plain");
  6239. ASSERT_TRUE(res);
  6240. EXPECT_EQ(StatusCode::OK_200, res->status);
  6241. EXPECT_EQ("PUT", res->body);
  6242. }
  6243. // Pre-compression logging tests
  6244. TEST_F(ServerTest, PreCompressionLogging) {
  6245. // Test data for compression (matches the actual /compress endpoint content)
  6246. const std::string test_content =
  6247. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6248. "3456789012345678901234567890";
  6249. // Variables to capture logging data
  6250. std::string pre_compression_body;
  6251. std::string pre_compression_content_type;
  6252. std::string pre_compression_content_encoding;
  6253. std::string post_compression_body;
  6254. std::string post_compression_content_type;
  6255. std::string post_compression_content_encoding;
  6256. // Set up pre-compression logger
  6257. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6258. const Response &res) {
  6259. pre_compression_body = res.body;
  6260. pre_compression_content_type = res.get_header_value("Content-Type");
  6261. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6262. });
  6263. // Set up post-compression logger
  6264. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6265. post_compression_body = res.body;
  6266. post_compression_content_type = res.get_header_value("Content-Type");
  6267. post_compression_content_encoding =
  6268. res.get_header_value("Content-Encoding");
  6269. });
  6270. // Test with gzip compression
  6271. Headers headers;
  6272. headers.emplace("Accept-Encoding", "gzip");
  6273. auto res = cli_.Get("/compress", headers);
  6274. // Verify response was compressed
  6275. ASSERT_TRUE(res);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6278. // Verify pre-compression logger captured uncompressed content
  6279. EXPECT_EQ(test_content, pre_compression_body);
  6280. EXPECT_EQ("text/plain", pre_compression_content_type);
  6281. EXPECT_TRUE(pre_compression_content_encoding
  6282. .empty()); // No encoding header before compression
  6283. // Verify post-compression logger captured compressed content
  6284. EXPECT_NE(test_content,
  6285. post_compression_body); // Should be different after compression
  6286. EXPECT_EQ("text/plain", post_compression_content_type);
  6287. EXPECT_EQ("gzip", post_compression_content_encoding);
  6288. // Verify compressed content is smaller
  6289. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6290. }
  6291. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6292. const std::string test_content =
  6293. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6294. "3456789012345678901234567890";
  6295. std::string pre_compression_body;
  6296. std::string post_compression_body;
  6297. svr_.set_pre_compression_logger(
  6298. [&](const Request & /*req*/, const Response &res) {
  6299. pre_compression_body = res.body;
  6300. });
  6301. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6302. post_compression_body = res.body;
  6303. });
  6304. Headers headers;
  6305. headers.emplace("Accept-Encoding", "br");
  6306. auto res = cli_.Get("/compress", headers);
  6307. ASSERT_TRUE(res);
  6308. EXPECT_EQ(StatusCode::OK_200, res->status);
  6309. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6310. // Verify pre-compression content is uncompressed
  6311. EXPECT_EQ(test_content, pre_compression_body);
  6312. // Verify post-compression content is compressed
  6313. EXPECT_NE(test_content, post_compression_body);
  6314. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6315. }
  6316. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6317. const std::string test_content =
  6318. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6319. "3456789012345678901234567890";
  6320. std::string pre_compression_body;
  6321. std::string post_compression_body;
  6322. svr_.set_pre_compression_logger(
  6323. [&](const Request & /*req*/, const Response &res) {
  6324. pre_compression_body = res.body;
  6325. });
  6326. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6327. post_compression_body = res.body;
  6328. });
  6329. // Request without compression (use /nocompress endpoint)
  6330. Headers headers;
  6331. auto res = cli_.Get("/nocompress", headers);
  6332. ASSERT_TRUE(res);
  6333. EXPECT_EQ(StatusCode::OK_200, res->status);
  6334. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6335. // Pre-compression logger should not be called when no compression is applied
  6336. EXPECT_TRUE(
  6337. pre_compression_body.empty()); // Pre-compression logger not called
  6338. EXPECT_EQ(
  6339. test_content,
  6340. post_compression_body); // Post-compression logger captures final content
  6341. }
  6342. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6343. const std::string test_content =
  6344. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6345. "3456789012345678901234567890";
  6346. std::string pre_compression_body;
  6347. bool pre_logger_called = false;
  6348. // Set only pre-compression logger
  6349. svr_.set_pre_compression_logger(
  6350. [&](const Request & /*req*/, const Response &res) {
  6351. pre_compression_body = res.body;
  6352. pre_logger_called = true;
  6353. });
  6354. Headers headers;
  6355. headers.emplace("Accept-Encoding", "gzip");
  6356. auto res = cli_.Get("/compress", headers);
  6357. ASSERT_TRUE(res);
  6358. EXPECT_EQ(StatusCode::OK_200, res->status);
  6359. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6360. // Verify pre-compression logger was called
  6361. EXPECT_TRUE(pre_logger_called);
  6362. EXPECT_EQ(test_content, pre_compression_body);
  6363. }
  6364. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6365. {
  6366. // Test with Expect: 100-continue header - success case
  6367. // Server returns 100 Continue, client sends body, server returns 200 OK
  6368. Request req;
  6369. req.method = "POST";
  6370. req.path = "/post-large";
  6371. req.set_header("Expect", "100-continue");
  6372. req.body = LARGE_DATA;
  6373. Response res;
  6374. auto error = Error::Success;
  6375. cli_.set_keep_alive(true);
  6376. auto ret = cli_.send(req, res, error);
  6377. EXPECT_TRUE(ret);
  6378. EXPECT_EQ(StatusCode::OK_200, res.status);
  6379. EXPECT_EQ(LARGE_DATA, res.body);
  6380. }
  6381. {
  6382. // Test with Expect: 100-continue header - error case
  6383. // Client should not send the body when server returns an error
  6384. Request req;
  6385. req.method = "POST";
  6386. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6387. req.set_header("Expect", "100-continue");
  6388. req.body = LARGE_DATA;
  6389. Response res;
  6390. auto error = Error::Success;
  6391. auto start = std::chrono::high_resolution_clock::now();
  6392. cli_.set_keep_alive(true);
  6393. auto ret = cli_.send(req, res, error);
  6394. auto end = std::chrono::high_resolution_clock::now();
  6395. auto elapsed =
  6396. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6397. .count();
  6398. // With Expect: 100-continue, request completes successfully but with error
  6399. EXPECT_TRUE(ret);
  6400. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6401. EXPECT_EQ("close", res.get_header_value("Connection"));
  6402. EXPECT_FALSE(cli_.is_socket_open());
  6403. EXPECT_LE(elapsed, 2000);
  6404. }
  6405. {
  6406. // Send an extra GET request to ensure error recovery without hanging
  6407. Request req;
  6408. req.method = "GET";
  6409. req.path = "/hi";
  6410. auto start = std::chrono::high_resolution_clock::now();
  6411. auto res = cli_.send(req);
  6412. auto end = std::chrono::high_resolution_clock::now();
  6413. auto elapsed =
  6414. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6415. .count();
  6416. ASSERT_TRUE(res);
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. EXPECT_EQ("Hello World!", res->body);
  6419. EXPECT_LE(elapsed, 500);
  6420. }
  6421. }
  6422. TEST(ZstdDecompressor, ChunkedDecompression) {
  6423. std::string data;
  6424. for (size_t i = 0; i < 32 * 1024; ++i) {
  6425. data.push_back(static_cast<char>('a' + i % 26));
  6426. }
  6427. std::string compressed_data;
  6428. {
  6429. httplib::detail::zstd_compressor compressor;
  6430. bool result = compressor.compress(
  6431. data.data(), data.size(),
  6432. /*last=*/true,
  6433. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6434. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6435. compressed_data_size);
  6436. return true;
  6437. });
  6438. ASSERT_TRUE(result);
  6439. }
  6440. std::string decompressed_data;
  6441. {
  6442. httplib::detail::zstd_decompressor decompressor;
  6443. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6444. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6445. size_t chunk_size = 130;
  6446. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6447. chunk_begin += chunk_size) {
  6448. size_t current_chunk_size =
  6449. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6450. bool result = decompressor.decompress(
  6451. compressed_data.data() + chunk_begin, current_chunk_size,
  6452. [&](const char *decompressed_data_chunk,
  6453. size_t decompressed_data_chunk_size) {
  6454. decompressed_data.insert(decompressed_data.size(),
  6455. decompressed_data_chunk,
  6456. decompressed_data_chunk_size);
  6457. return true;
  6458. });
  6459. ASSERT_TRUE(result);
  6460. }
  6461. }
  6462. ASSERT_EQ(data, decompressed_data);
  6463. }
  6464. TEST(ZstdDecompressor, Decompress) {
  6465. std::string original_text = "Compressed with ZSTD";
  6466. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6467. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6468. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6469. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6470. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6471. std::string decompressed_data;
  6472. {
  6473. httplib::detail::zstd_decompressor decompressor;
  6474. bool result = decompressor.decompress(
  6475. compressed_data.data(), compressed_data.size(),
  6476. [&](const char *decompressed_data_chunk,
  6477. size_t decompressed_data_chunk_size) {
  6478. decompressed_data.insert(decompressed_data.size(),
  6479. decompressed_data_chunk,
  6480. decompressed_data_chunk_size);
  6481. return true;
  6482. });
  6483. ASSERT_TRUE(result);
  6484. }
  6485. ASSERT_EQ(original_text, decompressed_data);
  6486. }
  6487. #endif
  6488. // Sends a raw request to a server listening at HOST:PORT.
  6489. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6490. std::string *resp = nullptr) {
  6491. auto error = Error::Success;
  6492. auto client_sock = detail::create_client_socket(
  6493. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6494. /*connection_timeout_sec=*/5, 0,
  6495. /*read_timeout_sec=*/5, 0,
  6496. /*write_timeout_sec=*/5, 0, std::string(), error);
  6497. if (client_sock == INVALID_SOCKET) { return false; }
  6498. auto ret = detail::process_client_socket(
  6499. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6500. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6501. if (req.size() !=
  6502. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6503. return false;
  6504. }
  6505. char buf[512];
  6506. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6507. while (line_reader.getline()) {
  6508. if (resp) { *resp += line_reader.ptr(); }
  6509. }
  6510. return true;
  6511. });
  6512. detail::close_socket(client_sock);
  6513. return ret;
  6514. }
  6515. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6516. Server svr;
  6517. std::string header_value;
  6518. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6519. header_value = req.get_header_value("foo");
  6520. res.set_content("ok", "text/plain");
  6521. });
  6522. thread t = thread([&] { svr.listen(HOST, PORT); });
  6523. auto se = detail::scope_exit([&] {
  6524. svr.stop();
  6525. t.join();
  6526. ASSERT_FALSE(svr.is_running());
  6527. });
  6528. svr.wait_until_ready();
  6529. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6530. // like characters are not treated the same - use vertical tab and escape.
  6531. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6532. "foo: \t \v bar \x1B\t \r\n"
  6533. "Connection: close\r\n"
  6534. "\r\n";
  6535. std::string res;
  6536. ASSERT_TRUE(send_request(5, req, &res));
  6537. EXPECT_EQ(header_value, "");
  6538. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6539. }
  6540. // Sends a raw request and verifies that there isn't a crash or exception.
  6541. static void test_raw_request(const std::string &req,
  6542. std::string *out = nullptr) {
  6543. Server svr;
  6544. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6545. res.set_content("ok", "text/plain");
  6546. });
  6547. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6548. res.set_content("ok", "text/plain");
  6549. });
  6550. svr.Get("/header_field_value_check",
  6551. [&](const Request & /*req*/, Response &res) {
  6552. res.set_content("ok", "text/plain");
  6553. });
  6554. // Server read timeout must be longer than the client read timeout for the
  6555. // bug to reproduce, probably to force the server to process a request
  6556. // without a trailing blank line.
  6557. const time_t client_read_timeout_sec = 1;
  6558. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6559. bool listen_thread_ok = false;
  6560. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6561. auto se = detail::scope_exit([&] {
  6562. svr.stop();
  6563. t.join();
  6564. ASSERT_FALSE(svr.is_running());
  6565. EXPECT_TRUE(listen_thread_ok);
  6566. });
  6567. svr.wait_until_ready();
  6568. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6569. }
  6570. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6571. // A certain header line causes an exception if the header property is parsed
  6572. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6573. test_raw_request(
  6574. "GET /hi HTTP/1.1\r\n"
  6575. " : "
  6576. " "
  6577. " ");
  6578. }
  6579. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6580. // A certain header line causes an exception if the header property *name* is
  6581. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6582. // greedy matcher and requires backtracking when there are a lot of ":"
  6583. // characters.
  6584. // This occurs with libc++ but not libstdc++.
  6585. test_raw_request(
  6586. "GET /hi HTTP/1.1\r\n"
  6587. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6588. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6589. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6590. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6591. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6592. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6593. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6594. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6595. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6596. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6597. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6598. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6599. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6600. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6601. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6602. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6603. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6604. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6605. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6606. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6607. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6608. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6609. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6610. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6611. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6612. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6613. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6614. "&&&%%%");
  6615. }
  6616. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6617. // Make sure this doesn't crash the server.
  6618. // In a previous version of the header line regex, the "\r" rendered the line
  6619. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6620. // a new position where the leading white space ended and the field value
  6621. // began.
  6622. // The crash occurs with libc++ but not libstdc++.
  6623. test_raw_request("GET /hi HTTP/1.1\r\n"
  6624. "a:" +
  6625. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6626. "\r\n"
  6627. "\r\n");
  6628. }
  6629. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6630. std::string out;
  6631. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6632. "Content-Type: text/plain\r\n"
  6633. "Transfer-Encoding: chunked\r\n"
  6634. "\r\n"
  6635. "nothex\r\n",
  6636. &out);
  6637. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6638. }
  6639. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  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. "3\r\n"
  6646. "xyz\r\n"
  6647. "NaN\r\n",
  6648. &out);
  6649. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6650. }
  6651. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6652. std::string out;
  6653. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6654. "Content-Type: text/plain\r\n"
  6655. "Transfer-Encoding: chunked\r\n"
  6656. "\r\n"
  6657. // Length is too large for 64 bits.
  6658. "1ffffffffffffffff\r\n"
  6659. "xyz\r\n",
  6660. &out);
  6661. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6662. }
  6663. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6664. test_raw_request("GET /hi HTTP/1.1\r\n"
  6665. "Content-Type: text/plain\r\n\r");
  6666. }
  6667. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6668. std::string out;
  6669. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6670. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6671. }
  6672. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6673. Server svr;
  6674. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6675. EXPECT_TRUE(!req.remote_addr.empty());
  6676. });
  6677. thread t = thread([&] { svr.listen(HOST, PORT); });
  6678. auto se = detail::scope_exit([&] {
  6679. svr.stop();
  6680. t.join();
  6681. ASSERT_FALSE(svr.is_running());
  6682. });
  6683. svr.wait_until_ready();
  6684. // Send an invalid request line to trigger Bad Request
  6685. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6686. std::string out;
  6687. ASSERT_TRUE(send_request(5, bad_req, &out));
  6688. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6689. }
  6690. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6691. std::string out;
  6692. std::string request(
  6693. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6694. test_raw_request(request, &out);
  6695. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6696. }
  6697. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6698. std::string out;
  6699. std::string request(
  6700. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6701. test_raw_request(request, &out);
  6702. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6703. }
  6704. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6705. std::string out;
  6706. std::string request(
  6707. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6708. test_raw_request(request, &out);
  6709. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6710. }
  6711. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6712. std::string out;
  6713. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6714. "Test: \r\n\r\n",
  6715. &out);
  6716. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6717. }
  6718. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6719. Server svr;
  6720. std::string x_custom;
  6721. std::string cookie;
  6722. std::string xff;
  6723. std::string x_unicode;
  6724. std::string x_iis;
  6725. svr.Get("/check", [&](const Request &req, Response &res) {
  6726. x_custom = req.get_header_value("X-Custom");
  6727. cookie = req.get_header_value("Cookie");
  6728. xff = req.get_header_value("X-Forwarded-For");
  6729. x_unicode = req.get_header_value("X-Unicode");
  6730. x_iis = req.get_header_value("X-IIS");
  6731. res.set_content("ok", "text/plain");
  6732. });
  6733. thread t = thread([&] { svr.listen(HOST, PORT); });
  6734. auto se = detail::scope_exit([&] {
  6735. svr.stop();
  6736. t.join();
  6737. ASSERT_FALSE(svr.is_running());
  6738. });
  6739. svr.wait_until_ready();
  6740. const std::string req = "GET /check HTTP/1.1\r\n"
  6741. "Host: localhost\r\n"
  6742. "X-Custom: a%0D%0AInjected: b\r\n"
  6743. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6744. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6745. "X-Unicode: %E3%81%82\r\n"
  6746. "X-IIS: %u00E9\r\n"
  6747. "Connection: close\r\n"
  6748. "\r\n";
  6749. std::string res;
  6750. ASSERT_TRUE(send_request(5, req, &res));
  6751. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6752. // Every value must be returned verbatim (wire form), with no decoding.
  6753. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6754. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6755. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6756. EXPECT_EQ("%E3%81%82", x_unicode);
  6757. EXPECT_EQ("%u00E9", x_iis);
  6758. }
  6759. // Applications that previously relied on automatic percent-decoding can
  6760. // reproduce the old behavior by explicitly calling decode_path_component()
  6761. // or, for RFC 3986 conformance, decode_uri_component().
  6762. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6763. Server svr;
  6764. std::string decoded;
  6765. svr.Get("/check", [&](const Request &req, Response &res) {
  6766. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6767. res.set_content("ok", "text/plain");
  6768. });
  6769. thread t = thread([&] { svr.listen(HOST, PORT); });
  6770. auto se = detail::scope_exit([&] {
  6771. svr.stop();
  6772. t.join();
  6773. ASSERT_FALSE(svr.is_running());
  6774. });
  6775. svr.wait_until_ready();
  6776. const std::string req = "GET /check HTTP/1.1\r\n"
  6777. "Host: localhost\r\n"
  6778. "X-Custom: hello%20world\r\n"
  6779. "Connection: close\r\n"
  6780. "\r\n";
  6781. std::string res;
  6782. ASSERT_TRUE(send_request(5, req, &res));
  6783. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6784. EXPECT_EQ("hello world", decoded);
  6785. }
  6786. // Regression test for #2033. Browsers send Referer values that include
  6787. // percent-encoded characters such as %0A inside the URL. Decoding the
  6788. // header value would either trip the post-decode CR/LF/NUL guard (the
  6789. // original bug, returning 400) or, after that guard was relaxed, silently
  6790. // store a literal LF — both unacceptable. The wire form must round-trip.
  6791. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6792. Server svr;
  6793. std::string referer;
  6794. svr.Get("/check", [&](const Request &req, Response &res) {
  6795. referer = req.get_header_value("Referer");
  6796. res.set_content("ok", "text/plain");
  6797. });
  6798. thread t = thread([&] { svr.listen(HOST, PORT); });
  6799. auto se = detail::scope_exit([&] {
  6800. svr.stop();
  6801. t.join();
  6802. ASSERT_FALSE(svr.is_running());
  6803. });
  6804. svr.wait_until_ready();
  6805. const std::string req = "GET /check HTTP/1.1\r\n"
  6806. "Host: localhost\r\n"
  6807. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6808. "Connection: close\r\n"
  6809. "\r\n";
  6810. std::string res;
  6811. ASSERT_TRUE(send_request(5, req, &res));
  6812. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6813. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6814. }
  6815. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6816. Server svr;
  6817. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6818. res.set_header("Cache-Control", "no-cache");
  6819. res.set_chunked_content_provider(
  6820. "text/event-stream", [](size_t offset, DataSink &sink) {
  6821. std::string s = "data:";
  6822. s += std::to_string(offset);
  6823. s += "\n\n";
  6824. auto ret = sink.write(s.data(), s.size());
  6825. EXPECT_TRUE(ret);
  6826. std::this_thread::sleep_for(std::chrono::seconds(1));
  6827. return true;
  6828. });
  6829. });
  6830. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6831. svr.wait_until_ready();
  6832. Client client(HOST, PORT);
  6833. const Headers headers = {{"Accept", "text/event-stream"}};
  6834. auto get_thread = std::thread([&client, &headers]() {
  6835. auto res = client.Get(
  6836. "/events", headers,
  6837. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6838. });
  6839. auto se = detail::scope_exit([&] {
  6840. svr.stop();
  6841. get_thread.join();
  6842. listen_thread.join();
  6843. ASSERT_FALSE(svr.is_running());
  6844. });
  6845. // Give GET time to get a few messages.
  6846. std::this_thread::sleep_for(std::chrono::seconds(2));
  6847. }
  6848. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6849. httplib::Server svr;
  6850. svr.Post("/hi",
  6851. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6852. res.status = StatusCode::OK_200;
  6853. });
  6854. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6855. svr.wait_until_ready();
  6856. Client cli(HOST, PORT);
  6857. auto res = cli.Post("/hi", "data", "text/plain");
  6858. ASSERT_TRUE(res);
  6859. EXPECT_EQ(StatusCode::OK_200, res->status);
  6860. svr.stop();
  6861. thread.join();
  6862. ASSERT_FALSE(svr.is_running());
  6863. res = cli.Post("/hi", "data", "text/plain");
  6864. ASSERT_FALSE(res);
  6865. }
  6866. TEST(ServerStopTest, ListenFailure) {
  6867. Server svr;
  6868. auto t = thread([&]() {
  6869. auto ret = svr.listen("????", PORT);
  6870. EXPECT_FALSE(ret);
  6871. });
  6872. svr.wait_until_ready();
  6873. svr.stop();
  6874. t.join();
  6875. }
  6876. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6877. TEST(ServerStopTest, Decommision) {
  6878. Server svr;
  6879. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6880. for (int i = 0; i < 4; i++) {
  6881. auto is_even = !(i % 2);
  6882. std::thread t{[&] {
  6883. try {
  6884. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6885. if (is_even) {
  6886. throw std::runtime_error("Some thing that happens to go wrong.");
  6887. }
  6888. svr.listen(HOST, PORT);
  6889. } catch (...) { svr.decommission(); }
  6890. }};
  6891. svr.wait_until_ready();
  6892. // Server is up
  6893. {
  6894. Client cli(HOST, PORT);
  6895. auto res = cli.Get("/hi");
  6896. if (is_even) {
  6897. EXPECT_FALSE(res);
  6898. } else {
  6899. EXPECT_TRUE(res);
  6900. EXPECT_EQ("hi...", res->body);
  6901. }
  6902. }
  6903. svr.stop();
  6904. t.join();
  6905. // Server is down...
  6906. {
  6907. Client cli(HOST, PORT);
  6908. auto res = cli.Get("/hi");
  6909. EXPECT_FALSE(res);
  6910. }
  6911. }
  6912. }
  6913. #endif
  6914. // Helper function for string body upload progress tests
  6915. template <typename SetupHandler, typename ClientCall>
  6916. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6917. ClientCall &&client_call,
  6918. const string &body) {
  6919. Server svr;
  6920. setup_handler(svr);
  6921. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6922. auto se = detail::scope_exit([&] {
  6923. svr.stop();
  6924. t.join();
  6925. });
  6926. svr.wait_until_ready();
  6927. Client cli(HOST, PORT);
  6928. vector<uint64_t> progress_values;
  6929. bool progress_called = false;
  6930. auto res =
  6931. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6932. progress_values.push_back(current);
  6933. progress_called = true;
  6934. return true;
  6935. });
  6936. ASSERT_TRUE(res);
  6937. EXPECT_EQ(200, res->status);
  6938. EXPECT_TRUE(progress_called);
  6939. }
  6940. TEST(UploadProgressTest, PostStringBodyBasic) {
  6941. TestStringBodyUploadProgress(
  6942. [](Server &svr) {
  6943. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6944. res.set_content("received", "text/plain");
  6945. });
  6946. },
  6947. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6948. return cli.Post("/test", body, "text/plain", progress_callback);
  6949. },
  6950. "test data for upload progress");
  6951. }
  6952. TEST(UploadProgressTest, PutStringBodyBasic) {
  6953. TestStringBodyUploadProgress(
  6954. [](Server &svr) {
  6955. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6956. res.set_content("put received", "text/plain");
  6957. });
  6958. },
  6959. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6960. return cli.Put("/test", body, "text/plain", progress_callback);
  6961. },
  6962. "put test data for upload progress");
  6963. }
  6964. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6965. TestStringBodyUploadProgress(
  6966. [](Server &svr) {
  6967. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6968. res.set_content("patch received", "text/plain");
  6969. });
  6970. },
  6971. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6972. return cli.Patch("/test", body, "text/plain", progress_callback);
  6973. },
  6974. "patch test data for upload progress");
  6975. }
  6976. // Helper function for content provider upload progress tests
  6977. template <typename SetupHandler, typename ClientCall>
  6978. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6979. ClientCall &&client_call) {
  6980. Server svr;
  6981. setup_handler(svr);
  6982. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6983. auto se = detail::scope_exit([&] {
  6984. svr.stop();
  6985. t.join();
  6986. });
  6987. svr.wait_until_ready();
  6988. Client cli(HOST, PORT);
  6989. vector<uint64_t> progress_values;
  6990. auto res =
  6991. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6992. progress_values.push_back(current);
  6993. return true;
  6994. });
  6995. ASSERT_TRUE(res);
  6996. EXPECT_EQ(200, res->status);
  6997. EXPECT_FALSE(progress_values.empty());
  6998. }
  6999. TEST(UploadProgressTest, PostContentProviderProgress) {
  7000. TestContentProviderUploadProgress(
  7001. [](Server &svr) {
  7002. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7003. res.set_content("provider received", "text/plain");
  7004. });
  7005. },
  7006. [](Client &cli, UploadProgress progress_callback) {
  7007. return cli.Post(
  7008. "/test", 10,
  7009. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7010. sink.os << "test data";
  7011. return true;
  7012. },
  7013. "text/plain", progress_callback);
  7014. });
  7015. }
  7016. // Helper function for multipart upload progress tests
  7017. template <typename SetupHandler, typename ClientCall>
  7018. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7019. ClientCall &&client_call,
  7020. const string &endpoint) {
  7021. Server svr;
  7022. setup_handler(svr);
  7023. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7024. auto se = detail::scope_exit([&] {
  7025. svr.stop();
  7026. t.join();
  7027. });
  7028. svr.wait_until_ready();
  7029. Client cli(HOST, PORT);
  7030. vector<uint64_t> progress_values;
  7031. UploadFormDataItems items = {
  7032. {"field1", "value1", "", ""},
  7033. {"field2", "longer value for progress tracking test", "", ""},
  7034. {"file1", "file content data for upload progress", "test.txt",
  7035. "text/plain"}};
  7036. auto res = client_call(cli, endpoint, items,
  7037. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7038. progress_values.push_back(current);
  7039. return true;
  7040. });
  7041. ASSERT_TRUE(res);
  7042. EXPECT_EQ(200, res->status);
  7043. EXPECT_FALSE(progress_values.empty());
  7044. }
  7045. TEST(UploadProgressTest, PostMultipartProgress) {
  7046. TestMultipartUploadProgress(
  7047. [](Server &svr) {
  7048. svr.Post("/multipart", [](const Request &req, Response &res) {
  7049. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7050. res.set_content("multipart received", "text/plain");
  7051. });
  7052. },
  7053. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7054. UploadProgress progress_callback) {
  7055. return cli.Post(endpoint, items, progress_callback);
  7056. },
  7057. "/multipart");
  7058. }
  7059. // Helper function for basic download progress tests
  7060. template <typename SetupHandler, typename ClientCall>
  7061. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7062. ClientCall &&client_call, const string &endpoint,
  7063. size_t expected_content_size) {
  7064. Server svr;
  7065. setup_handler(svr);
  7066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7067. auto se = detail::scope_exit([&] {
  7068. svr.stop();
  7069. t.join();
  7070. });
  7071. svr.wait_until_ready();
  7072. Client cli(HOST, PORT);
  7073. vector<uint64_t> progress_values;
  7074. auto res = client_call(cli, endpoint,
  7075. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7076. progress_values.push_back(current);
  7077. return true;
  7078. });
  7079. ASSERT_TRUE(res);
  7080. EXPECT_EQ(200, res->status);
  7081. EXPECT_FALSE(progress_values.empty());
  7082. EXPECT_EQ(expected_content_size, res->body.size());
  7083. }
  7084. TEST(DownloadProgressTest, GetBasic) {
  7085. TestBasicDownloadProgress(
  7086. [](Server &svr) {
  7087. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7088. string content(1000, 'D');
  7089. res.set_content(content, "text/plain");
  7090. });
  7091. },
  7092. [](Client &cli, const string &endpoint,
  7093. DownloadProgress progress_callback) {
  7094. return cli.Get(endpoint, progress_callback);
  7095. },
  7096. "/download", 1000u);
  7097. }
  7098. // Helper function for content receiver download progress tests
  7099. template <typename SetupHandler, typename ClientCall>
  7100. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7101. ClientCall &&client_call,
  7102. const string &endpoint,
  7103. size_t expected_content_size) {
  7104. Server svr;
  7105. setup_handler(svr);
  7106. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7107. auto se = detail::scope_exit([&] {
  7108. svr.stop();
  7109. t.join();
  7110. });
  7111. svr.wait_until_ready();
  7112. Client cli(HOST, PORT);
  7113. vector<uint64_t> progress_values;
  7114. string received_body;
  7115. auto res = client_call(
  7116. cli, endpoint,
  7117. [&](const char *data, size_t data_length) -> bool {
  7118. received_body.append(data, data_length);
  7119. return true;
  7120. },
  7121. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7122. progress_values.push_back(current);
  7123. return true;
  7124. });
  7125. ASSERT_TRUE(res);
  7126. EXPECT_EQ(200, res->status);
  7127. EXPECT_FALSE(progress_values.empty());
  7128. EXPECT_EQ(expected_content_size, received_body.size());
  7129. EXPECT_TRUE(res->body.empty());
  7130. }
  7131. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7132. TestContentReceiverDownloadProgress(
  7133. [](Server &svr) {
  7134. svr.Get("/download-receiver",
  7135. [](const Request & /*req*/, Response &res) {
  7136. string content(2000, 'R');
  7137. res.set_content(content, "text/plain");
  7138. });
  7139. },
  7140. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7141. DownloadProgress progress_callback) {
  7142. return cli.Get(endpoint, content_receiver, progress_callback);
  7143. },
  7144. "/download-receiver", 2000u);
  7145. }
  7146. TEST(StreamingTest, NoContentLengthStreaming) {
  7147. Server svr;
  7148. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7149. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7150. if (offset < 6) {
  7151. sink.os << (offset < 3 ? "a" : "b");
  7152. } else {
  7153. sink.done();
  7154. }
  7155. return true;
  7156. });
  7157. });
  7158. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7159. auto listen_se = detail::scope_exit([&] {
  7160. svr.stop();
  7161. listen_thread.join();
  7162. ASSERT_FALSE(svr.is_running());
  7163. });
  7164. svr.wait_until_ready();
  7165. Client client(HOST, PORT);
  7166. auto get_thread = std::thread([&client]() {
  7167. std::string s;
  7168. auto res =
  7169. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7170. s += std::string(data, len);
  7171. return true;
  7172. });
  7173. ASSERT_TRUE(res);
  7174. EXPECT_EQ(StatusCode::OK_200, res->status);
  7175. EXPECT_EQ("aaabbb", s);
  7176. });
  7177. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7178. // Give GET time to get a few messages.
  7179. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7180. }
  7181. TEST(MountTest, Unmount) {
  7182. Server svr;
  7183. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7184. auto se = detail::scope_exit([&] {
  7185. svr.stop();
  7186. listen_thread.join();
  7187. ASSERT_FALSE(svr.is_running());
  7188. });
  7189. svr.wait_until_ready();
  7190. Client cli("localhost", PORT);
  7191. svr.set_mount_point("/mount2", "./www2");
  7192. auto res = cli.Get("/");
  7193. ASSERT_TRUE(res);
  7194. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7195. res = cli.Get("/mount2/dir/test.html");
  7196. ASSERT_TRUE(res);
  7197. EXPECT_EQ(StatusCode::OK_200, res->status);
  7198. svr.set_mount_point("/", "./www");
  7199. res = cli.Get("/dir/");
  7200. ASSERT_TRUE(res);
  7201. EXPECT_EQ(StatusCode::OK_200, res->status);
  7202. svr.remove_mount_point("/");
  7203. res = cli.Get("/dir/");
  7204. ASSERT_TRUE(res);
  7205. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7206. svr.remove_mount_point("/mount2");
  7207. res = cli.Get("/mount2/dir/test.html");
  7208. ASSERT_TRUE(res);
  7209. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7210. }
  7211. TEST(MountTest, Redicect) {
  7212. Server svr;
  7213. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7214. auto se = detail::scope_exit([&] {
  7215. svr.stop();
  7216. listen_thread.join();
  7217. ASSERT_FALSE(svr.is_running());
  7218. });
  7219. svr.set_mount_point("/", "./www");
  7220. svr.wait_until_ready();
  7221. Client cli("localhost", PORT);
  7222. auto res = cli.Get("/dir/");
  7223. ASSERT_TRUE(res);
  7224. EXPECT_EQ(StatusCode::OK_200, res->status);
  7225. res = cli.Get("/dir");
  7226. ASSERT_TRUE(res);
  7227. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7228. res = cli.Get("/file");
  7229. ASSERT_TRUE(res);
  7230. EXPECT_EQ(StatusCode::OK_200, res->status);
  7231. res = cli.Get("/file/");
  7232. ASSERT_TRUE(res);
  7233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7234. cli.set_follow_location(true);
  7235. res = cli.Get("/dir");
  7236. ASSERT_TRUE(res);
  7237. EXPECT_EQ(StatusCode::OK_200, res->status);
  7238. }
  7239. TEST(MountTest, MultibytesPathName) {
  7240. Server svr;
  7241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7242. auto se = detail::scope_exit([&] {
  7243. svr.stop();
  7244. listen_thread.join();
  7245. ASSERT_FALSE(svr.is_running());
  7246. });
  7247. svr.set_mount_point("/", "./www");
  7248. svr.wait_until_ready();
  7249. Client cli("localhost", PORT);
  7250. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7251. ASSERT_TRUE(res);
  7252. EXPECT_EQ(StatusCode::OK_200, res->status);
  7253. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7254. }
  7255. #ifdef _WIN32
  7256. // Issue #2435: mmap::open() must succeed even when another handle holds
  7257. // the file open for writing (e.g. an active log file).
  7258. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7259. const char *path = "mmap_concurrent_writer_test.txt";
  7260. const char *content = "hello";
  7261. {
  7262. std::ofstream f(path, std::ios::binary);
  7263. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7264. }
  7265. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7266. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7267. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7268. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7269. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7270. detail::mmap m(path);
  7271. ASSERT_TRUE(m.is_open());
  7272. EXPECT_EQ(strlen(content), m.size());
  7273. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7274. }
  7275. #endif
  7276. TEST(KeepAliveTest, ReadTimeout) {
  7277. Server svr;
  7278. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7279. std::this_thread::sleep_for(std::chrono::seconds(2));
  7280. res.set_content("a", "text/plain");
  7281. });
  7282. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7283. res.set_content("b", "text/plain");
  7284. });
  7285. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7286. auto se = detail::scope_exit([&] {
  7287. svr.stop();
  7288. listen_thread.join();
  7289. ASSERT_FALSE(svr.is_running());
  7290. });
  7291. svr.wait_until_ready();
  7292. Client cli("localhost", PORT);
  7293. cli.set_keep_alive(true);
  7294. cli.set_read_timeout(std::chrono::seconds(1));
  7295. auto resa = cli.Get("/a");
  7296. ASSERT_FALSE(resa);
  7297. EXPECT_EQ(Error::Read, resa.error());
  7298. auto resb = cli.Get("/b");
  7299. ASSERT_TRUE(resb);
  7300. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7301. EXPECT_EQ("b", resb->body);
  7302. }
  7303. TEST(KeepAliveTest, MaxCount) {
  7304. size_t keep_alive_max_count = 3;
  7305. Server svr;
  7306. svr.set_keep_alive_max_count(keep_alive_max_count);
  7307. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7308. res.set_content("Hello World!", "text/plain");
  7309. });
  7310. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7311. auto se = detail::scope_exit([&] {
  7312. svr.stop();
  7313. listen_thread.join();
  7314. ASSERT_FALSE(svr.is_running());
  7315. });
  7316. svr.wait_until_ready();
  7317. Client cli(HOST, PORT);
  7318. cli.set_keep_alive(true);
  7319. for (size_t i = 0; i < 5; i++) {
  7320. auto result = cli.Get("/hi");
  7321. ASSERT_TRUE(result);
  7322. EXPECT_EQ(StatusCode::OK_200, result->status);
  7323. if (i == keep_alive_max_count - 1) {
  7324. EXPECT_EQ("close", result->get_header_value("Connection"));
  7325. } else {
  7326. EXPECT_FALSE(result->has_header("Connection"));
  7327. }
  7328. }
  7329. }
  7330. TEST(KeepAliveTest, Issue1041) {
  7331. Server svr;
  7332. svr.set_keep_alive_timeout(3);
  7333. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7334. res.set_content("Hello World!", "text/plain");
  7335. });
  7336. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7337. auto se = detail::scope_exit([&] {
  7338. svr.stop();
  7339. listen_thread.join();
  7340. ASSERT_FALSE(svr.is_running());
  7341. });
  7342. svr.wait_until_ready();
  7343. Client cli(HOST, PORT);
  7344. cli.set_keep_alive(true);
  7345. auto result = cli.Get("/hi");
  7346. ASSERT_TRUE(result);
  7347. EXPECT_EQ(StatusCode::OK_200, result->status);
  7348. std::this_thread::sleep_for(std::chrono::seconds(5));
  7349. result = cli.Get("/hi");
  7350. ASSERT_TRUE(result);
  7351. EXPECT_EQ(StatusCode::OK_200, result->status);
  7352. }
  7353. TEST(KeepAliveTest, Issue1959) {
  7354. Server svr;
  7355. svr.set_keep_alive_timeout(5);
  7356. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7357. res.set_content("a", "text/plain");
  7358. });
  7359. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7360. auto se = detail::scope_exit([&] {
  7361. if (!svr.is_running()) return;
  7362. svr.stop();
  7363. listen_thread.join();
  7364. ASSERT_FALSE(svr.is_running());
  7365. });
  7366. svr.wait_until_ready();
  7367. Client cli("localhost", PORT);
  7368. cli.set_keep_alive(true);
  7369. using namespace std::chrono;
  7370. auto start = steady_clock::now();
  7371. cli.Get("/a");
  7372. svr.stop();
  7373. listen_thread.join();
  7374. auto end = steady_clock::now();
  7375. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7376. EXPECT_LT(elapsed, 5000);
  7377. }
  7378. #ifdef CPPHTTPLIB_SSL_ENABLED
  7379. TEST(KeepAliveTest, SSLClientReconnection) {
  7380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7381. ASSERT_TRUE(svr.is_valid());
  7382. svr.set_keep_alive_timeout(1);
  7383. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7384. res.set_content("Hello World!", "text/plain");
  7385. });
  7386. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7387. auto se = detail::scope_exit([&] {
  7388. svr.stop();
  7389. listen_thread.join();
  7390. ASSERT_FALSE(svr.is_running());
  7391. });
  7392. svr.wait_until_ready();
  7393. SSLClient cli(HOST, PORT);
  7394. cli.enable_server_certificate_verification(false);
  7395. cli.set_keep_alive(true);
  7396. auto result = cli.Get("/hi");
  7397. ASSERT_TRUE(result);
  7398. EXPECT_EQ(StatusCode::OK_200, result->status);
  7399. result = cli.Get("/hi");
  7400. ASSERT_TRUE(result);
  7401. EXPECT_EQ(StatusCode::OK_200, result->status);
  7402. std::this_thread::sleep_for(std::chrono::seconds(2));
  7403. // Recoonect
  7404. result = cli.Get("/hi");
  7405. ASSERT_TRUE(result);
  7406. EXPECT_EQ(StatusCode::OK_200, result->status);
  7407. result = cli.Get("/hi");
  7408. ASSERT_TRUE(result);
  7409. EXPECT_EQ(StatusCode::OK_200, result->status);
  7410. }
  7411. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7413. ASSERT_TRUE(svr.is_valid());
  7414. svr.set_keep_alive_timeout(1);
  7415. std::string content = "reconnect";
  7416. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7417. res.set_content("Hello World!", "text/plain");
  7418. });
  7419. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7420. auto se = detail::scope_exit([&] {
  7421. svr.stop();
  7422. listen_thread.join();
  7423. ASSERT_FALSE(svr.is_running());
  7424. });
  7425. svr.wait_until_ready();
  7426. SSLClient cli(HOST, PORT);
  7427. cli.enable_server_certificate_verification(false);
  7428. cli.set_keep_alive(true);
  7429. auto result = cli.Post(
  7430. "/hi", content.size(),
  7431. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7432. sink.write(content.c_str(), content.size());
  7433. return true;
  7434. },
  7435. "text/plain");
  7436. ASSERT_TRUE(result);
  7437. EXPECT_EQ(200, result->status);
  7438. std::this_thread::sleep_for(std::chrono::seconds(2));
  7439. // Recoonect
  7440. result = cli.Post(
  7441. "/hi", content.size(),
  7442. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7443. sink.write(content.c_str(), content.size());
  7444. return true;
  7445. },
  7446. "text/plain");
  7447. ASSERT_TRUE(result);
  7448. EXPECT_EQ(200, result->status);
  7449. result = cli.Post(
  7450. "/hi", content.size(),
  7451. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7452. sink.write(content.c_str(), content.size());
  7453. return true;
  7454. },
  7455. "text/plain");
  7456. ASSERT_TRUE(result);
  7457. EXPECT_EQ(200, result->status);
  7458. }
  7459. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7460. using namespace httplib::tls;
  7461. {
  7462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7463. ASSERT_TRUE(svr.is_valid());
  7464. svr.Get("/sni", [&](const Request &req, Response &res) {
  7465. std::string expected = req.sni();
  7466. EXPECT_EQ(expected, req.get_param_value("expected"));
  7467. res.set_content("ok", "text/plain");
  7468. });
  7469. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7470. auto se = detail::scope_exit([&] {
  7471. svr.stop();
  7472. listen_thread.join();
  7473. ASSERT_FALSE(svr.is_running());
  7474. });
  7475. svr.wait_until_ready();
  7476. {
  7477. SSLClient cli("localhost", PORT);
  7478. cli.enable_server_certificate_verification(false);
  7479. auto res = cli.Get("/sni?expected=localhost");
  7480. ASSERT_TRUE(res);
  7481. }
  7482. {
  7483. SSLClient cli("::1", PORT);
  7484. cli.enable_server_certificate_verification(false);
  7485. auto res = cli.Get("/sni?expected=");
  7486. // NOTE: This may fail if the server is listening on IPv4 only
  7487. // (e.g., when localhost resolves to 127.0.0.1 only)
  7488. if (res) {
  7489. EXPECT_EQ(StatusCode::OK_200, res->status);
  7490. } else {
  7491. EXPECT_EQ(Error::Connection, res.error());
  7492. }
  7493. }
  7494. }
  7495. }
  7496. #endif
  7497. TEST(ClientProblemDetectionTest, ContentProvider) {
  7498. Server svr;
  7499. size_t content_length = 1024 * 1024;
  7500. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7501. res.set_content_provider(
  7502. content_length, "text/plain",
  7503. [&](size_t offset, size_t length, DataSink &sink) {
  7504. auto out_len = std::min(length, static_cast<size_t>(1024));
  7505. std::string out(out_len, '@');
  7506. sink.write(out.data(), out_len);
  7507. return offset < 4096;
  7508. },
  7509. [](bool success) { ASSERT_FALSE(success); });
  7510. });
  7511. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7512. res.set_content_provider(
  7513. 0, "text/plain",
  7514. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7515. EXPECT_TRUE(false);
  7516. return true;
  7517. },
  7518. [](bool success) { ASSERT_FALSE(success); });
  7519. });
  7520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7521. auto se = detail::scope_exit([&] {
  7522. svr.stop();
  7523. listen_thread.join();
  7524. ASSERT_FALSE(svr.is_running());
  7525. });
  7526. svr.wait_until_ready();
  7527. Client cli("localhost", PORT);
  7528. {
  7529. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7530. size_t /*data_length*/) { return false; });
  7531. ASSERT_FALSE(res);
  7532. }
  7533. {
  7534. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7535. size_t /*data_length*/) { return false; });
  7536. ASSERT_TRUE(res);
  7537. }
  7538. }
  7539. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7540. Server svr;
  7541. svr.set_error_handler([](Request const &, Response &res) -> void {
  7542. res.set_chunked_content_provider(
  7543. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7544. sink.os << "hello";
  7545. sink.os << "world";
  7546. sink.done();
  7547. return true;
  7548. });
  7549. });
  7550. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7551. auto se = detail::scope_exit([&] {
  7552. svr.stop();
  7553. listen_thread.join();
  7554. ASSERT_FALSE(svr.is_running());
  7555. });
  7556. svr.wait_until_ready();
  7557. Client cli("localhost", PORT);
  7558. auto res = cli.Get("/");
  7559. ASSERT_TRUE(res);
  7560. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7561. EXPECT_EQ("helloworld", res->body);
  7562. }
  7563. TEST(LongPollingTest, ClientCloseDetection) {
  7564. Server svr;
  7565. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7566. res.set_chunked_content_provider(
  7567. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7568. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7569. sink.os << "hello";
  7570. auto count = 10;
  7571. while (count > 0 && sink.is_writable()) {
  7572. this_thread::sleep_for(chrono::milliseconds(10));
  7573. count--;
  7574. }
  7575. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7576. return true;
  7577. });
  7578. });
  7579. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7580. auto se = detail::scope_exit([&] {
  7581. svr.stop();
  7582. listen_thread.join();
  7583. ASSERT_FALSE(svr.is_running());
  7584. });
  7585. svr.wait_until_ready();
  7586. Client cli("localhost", PORT);
  7587. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7588. EXPECT_EQ("hello", string(data, data_length));
  7589. return false; // close the socket immediately.
  7590. });
  7591. ASSERT_FALSE(res);
  7592. }
  7593. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7594. Server svr;
  7595. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7596. res.set_chunked_content_provider(
  7597. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7598. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7599. sink.os << "hello";
  7600. EXPECT_TRUE(sink.os.good());
  7601. // Wait for the client to close the connection
  7602. auto count = 10;
  7603. while (count > 0 && sink.is_writable()) {
  7604. this_thread::sleep_for(chrono::milliseconds(10));
  7605. count--;
  7606. }
  7607. // After client disconnect, write repeatedly until the socket
  7608. // write actually fails (small writes may be absorbed by the
  7609. // kernel buffer)
  7610. std::string chunk(1024, 'x');
  7611. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7612. sink.os << chunk;
  7613. }
  7614. EXPECT_TRUE(sink.os.fail());
  7615. return true;
  7616. });
  7617. });
  7618. auto port = svr.bind_to_any_port("localhost");
  7619. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7620. auto se = detail::scope_exit([&] {
  7621. svr.stop();
  7622. listen_thread.join();
  7623. ASSERT_FALSE(svr.is_running());
  7624. });
  7625. svr.wait_until_ready();
  7626. Client cli("localhost", port);
  7627. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7628. EXPECT_EQ("hello", string(data, data_length));
  7629. return false; // close the socket immediately.
  7630. });
  7631. ASSERT_FALSE(res);
  7632. }
  7633. TEST(GetWithParametersTest, GetWithParameters) {
  7634. Server svr;
  7635. svr.Get("/", [&](const Request &req, Response &) {
  7636. EXPECT_EQ("world", req.get_param_value("hello"));
  7637. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7638. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7639. });
  7640. svr.Get("/params", [&](const Request &req, Response &) {
  7641. EXPECT_EQ("world", req.get_param_value("hello"));
  7642. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7643. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7644. });
  7645. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7646. EXPECT_EQ("resource-id", req.matches[1]);
  7647. EXPECT_EQ("foo", req.get_param_value("param1"));
  7648. EXPECT_EQ("bar", req.get_param_value("param2"));
  7649. });
  7650. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7651. EXPECT_EQ("user-id", req.path_params.at("id"));
  7652. EXPECT_EQ("foo", req.get_param_value("param1"));
  7653. EXPECT_EQ("bar", req.get_param_value("param2"));
  7654. });
  7655. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7656. auto se = detail::scope_exit([&] {
  7657. svr.stop();
  7658. listen_thread.join();
  7659. ASSERT_FALSE(svr.is_running());
  7660. });
  7661. svr.wait_until_ready();
  7662. {
  7663. Client cli(HOST, PORT);
  7664. Params params;
  7665. params.emplace("hello", "world");
  7666. params.emplace("hello2", "world2");
  7667. params.emplace("hello3", "world3");
  7668. auto res = cli.Get("/", params, Headers{});
  7669. ASSERT_TRUE(res);
  7670. EXPECT_EQ(StatusCode::OK_200, res->status);
  7671. }
  7672. {
  7673. Client cli(HOST, PORT);
  7674. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7675. ASSERT_TRUE(res);
  7676. EXPECT_EQ(StatusCode::OK_200, res->status);
  7677. }
  7678. {
  7679. Client cli(HOST, PORT);
  7680. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7681. ASSERT_TRUE(res);
  7682. EXPECT_EQ(StatusCode::OK_200, res->status);
  7683. }
  7684. {
  7685. Client cli(HOST, PORT);
  7686. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7687. ASSERT_TRUE(res);
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. }
  7690. }
  7691. TEST(GetWithParametersTest, GetWithParameters2) {
  7692. Server svr;
  7693. svr.Get("/", [&](const Request &req, Response &res) {
  7694. auto text = req.get_param_value("hello");
  7695. res.set_content(text, "text/plain");
  7696. });
  7697. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7698. auto se = detail::scope_exit([&] {
  7699. svr.stop();
  7700. listen_thread.join();
  7701. ASSERT_FALSE(svr.is_running());
  7702. });
  7703. svr.wait_until_ready();
  7704. Client cli("localhost", PORT);
  7705. Params params;
  7706. params.emplace("hello", "world");
  7707. std::string body;
  7708. auto res = cli.Get("/", params, Headers{},
  7709. [&](const char *data, size_t data_length) {
  7710. body.append(data, data_length);
  7711. return true;
  7712. });
  7713. ASSERT_TRUE(res);
  7714. EXPECT_EQ(StatusCode::OK_200, res->status);
  7715. EXPECT_EQ("world", body);
  7716. }
  7717. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7718. auto host = "httpbingo.org";
  7719. auto path = std::string{"/range/32"};
  7720. #ifdef CPPHTTPLIB_SSL_ENABLED
  7721. SSLClient cli(host);
  7722. #else
  7723. Client cli(host);
  7724. #endif
  7725. cli.set_default_headers({make_range_header({{1, 10}})});
  7726. cli.set_connection_timeout(5);
  7727. {
  7728. auto res = cli.Get(path);
  7729. ASSERT_TRUE(res);
  7730. EXPECT_EQ("bcdefghijk", res->body);
  7731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7732. }
  7733. {
  7734. auto res = cli.Get(path);
  7735. ASSERT_TRUE(res);
  7736. EXPECT_EQ("bcdefghijk", res->body);
  7737. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7738. }
  7739. }
  7740. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7741. Server svr;
  7742. svr.set_default_headers({{"Hello", "World"}});
  7743. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7744. res.set_content("ok", "text/plain");
  7745. });
  7746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7747. auto se = detail::scope_exit([&] {
  7748. svr.stop();
  7749. listen_thread.join();
  7750. ASSERT_FALSE(svr.is_running());
  7751. });
  7752. svr.wait_until_ready();
  7753. Client cli("localhost", PORT);
  7754. auto res = cli.Get("/");
  7755. ASSERT_TRUE(res);
  7756. EXPECT_EQ(StatusCode::OK_200, res->status);
  7757. EXPECT_EQ("ok", res->body);
  7758. EXPECT_EQ("World", res->get_header_value("Hello"));
  7759. }
  7760. #ifdef CPPHTTPLIB_SSL_ENABLED
  7761. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7763. ASSERT_TRUE(svr.is_valid());
  7764. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7765. std::this_thread::sleep_for(std::chrono::seconds(2));
  7766. res.set_content("a", "text/plain");
  7767. });
  7768. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7769. res.set_content("b", "text/plain");
  7770. });
  7771. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7772. auto se = detail::scope_exit([&] {
  7773. svr.stop();
  7774. listen_thread.join();
  7775. ASSERT_FALSE(svr.is_running());
  7776. });
  7777. svr.wait_until_ready();
  7778. SSLClient cli("localhost", PORT);
  7779. cli.enable_server_certificate_verification(false);
  7780. cli.set_keep_alive(true);
  7781. cli.set_read_timeout(std::chrono::seconds(1));
  7782. auto resa = cli.Get("/a");
  7783. ASSERT_TRUE(!resa);
  7784. EXPECT_EQ(Error::Read, resa.error());
  7785. auto resb = cli.Get("/b");
  7786. ASSERT_TRUE(resb);
  7787. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7788. EXPECT_EQ("b", resb->body);
  7789. }
  7790. #endif
  7791. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7792. protected:
  7793. ServerTestWithAI_PASSIVE()
  7794. : cli_(HOST, PORT)
  7795. #ifdef CPPHTTPLIB_SSL_ENABLED
  7796. ,
  7797. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7798. #endif
  7799. {
  7800. #ifdef CPPHTTPLIB_SSL_ENABLED
  7801. cli_.enable_server_certificate_verification(false);
  7802. #endif
  7803. }
  7804. virtual void SetUp() {
  7805. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7806. res.set_content("Hello World!", "text/plain");
  7807. });
  7808. t_ = thread(
  7809. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7810. svr_.wait_until_ready();
  7811. }
  7812. virtual void TearDown() {
  7813. svr_.stop();
  7814. t_.join();
  7815. }
  7816. #ifdef CPPHTTPLIB_SSL_ENABLED
  7817. SSLClient cli_;
  7818. SSLServer svr_;
  7819. #else
  7820. Client cli_;
  7821. Server svr_;
  7822. #endif
  7823. thread t_;
  7824. };
  7825. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7826. auto res = cli_.Get("/hi");
  7827. ASSERT_TRUE(res);
  7828. EXPECT_EQ(StatusCode::OK_200, res->status);
  7829. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7830. EXPECT_EQ("Hello World!", res->body);
  7831. }
  7832. class ServerUpDownTest : public ::testing::Test {
  7833. protected:
  7834. ServerUpDownTest() : cli_(HOST, PORT) {}
  7835. virtual void SetUp() {
  7836. t_ = thread([&]() {
  7837. svr_.bind_to_any_port(HOST);
  7838. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7839. ASSERT_TRUE(svr_.listen_after_bind());
  7840. });
  7841. svr_.wait_until_ready();
  7842. }
  7843. virtual void TearDown() {
  7844. svr_.stop();
  7845. t_.join();
  7846. }
  7847. Client cli_;
  7848. Server svr_;
  7849. thread t_;
  7850. };
  7851. TEST_F(ServerUpDownTest, QuickStartStop) {
  7852. // Should not crash, especially when run with
  7853. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7854. }
  7855. class PayloadMaxLengthTest : public ::testing::Test {
  7856. protected:
  7857. PayloadMaxLengthTest()
  7858. : cli_(HOST, PORT)
  7859. #ifdef CPPHTTPLIB_SSL_ENABLED
  7860. ,
  7861. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7862. #endif
  7863. {
  7864. #ifdef CPPHTTPLIB_SSL_ENABLED
  7865. cli_.enable_server_certificate_verification(false);
  7866. #endif
  7867. }
  7868. virtual void SetUp() {
  7869. svr_.set_payload_max_length(8);
  7870. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7871. res.set_content("test", "text/plain");
  7872. });
  7873. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7874. svr_.wait_until_ready();
  7875. }
  7876. virtual void TearDown() {
  7877. svr_.stop();
  7878. t_.join();
  7879. }
  7880. #ifdef CPPHTTPLIB_SSL_ENABLED
  7881. SSLClient cli_;
  7882. SSLServer svr_;
  7883. #else
  7884. Client cli_;
  7885. Server svr_;
  7886. #endif
  7887. thread t_;
  7888. };
  7889. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7890. auto res = cli_.Post("/test", "123456789", "text/plain");
  7891. ASSERT_TRUE(res);
  7892. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7893. res = cli_.Post("/test", "12345678", "text/plain");
  7894. ASSERT_TRUE(res);
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. }
  7897. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7898. // Test chunked encoding with payload exceeding the 8-byte limit
  7899. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7900. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7901. ASSERT_TRUE(res);
  7902. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7903. }
  7904. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7905. // Test chunked encoding with payload within the 8-byte limit
  7906. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7907. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7908. ASSERT_TRUE(res);
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. }
  7911. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7912. // Test using send_request to send chunked data exceeding payload limit
  7913. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7914. "Host: " +
  7915. std::string(HOST) + ":" + std::to_string(PORT) +
  7916. "\r\n"
  7917. "Transfer-Encoding: chunked\r\n"
  7918. "Connection: close\r\n"
  7919. "\r\n"
  7920. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7921. "0123456789\r\n"
  7922. "0\r\n" // End chunk
  7923. "\r\n";
  7924. std::string response;
  7925. bool result = send_request(1, chunked_request, &response);
  7926. if (!result) {
  7927. // If send_request fails, it might be because the server closed the
  7928. // connection due to payload limit enforcement, which is acceptable
  7929. SUCCEED()
  7930. << "Server rejected oversized chunked request (connection closed)";
  7931. } else {
  7932. // If we got a response, check if it's an error response or connection was
  7933. // closed early Short response length indicates connection was closed due to
  7934. // payload limit
  7935. if (response.length() <= 10) {
  7936. SUCCEED() << "Server closed connection for oversized chunked request";
  7937. } else {
  7938. // Check for error status codes
  7939. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7940. response.find("Payload Too Large") != std::string::npos ||
  7941. response.find("400") != std::string::npos);
  7942. }
  7943. }
  7944. }
  7945. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7946. // Test request without Content-Length header exceeding payload limit
  7947. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7948. "Host: " +
  7949. std::string(HOST) + ":" +
  7950. std::to_string(PORT) +
  7951. "\r\n"
  7952. "Connection: close\r\n"
  7953. "\r\n";
  7954. // Add payload exceeding the 8-byte limit
  7955. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7956. request_without_content_length += large_payload;
  7957. std::string response;
  7958. bool result = send_request(1, request_without_content_length, &response);
  7959. if (!result) {
  7960. // If send_request fails, server likely closed connection due to payload
  7961. // limit
  7962. SUCCEED() << "Server rejected oversized request without Content-Length "
  7963. "(connection closed)";
  7964. } else {
  7965. // Check if server responded with error or closed connection early
  7966. if (response.length() <= 10) {
  7967. SUCCEED() << "Server closed connection for oversized request without "
  7968. "Content-Length";
  7969. } else {
  7970. // Check for error status codes
  7971. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7972. response.find("Payload Too Large") != std::string::npos ||
  7973. response.find("400") != std::string::npos);
  7974. }
  7975. }
  7976. }
  7977. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7978. // Test request without Content-Length header within payload limit
  7979. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7980. "Host: " +
  7981. std::string(HOST) + ":" +
  7982. std::to_string(PORT) +
  7983. "\r\n"
  7984. "Connection: close\r\n"
  7985. "\r\n";
  7986. // Add payload within the 8-byte limit
  7987. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7988. request_without_content_length += small_payload;
  7989. std::string response;
  7990. bool result = send_request(1, request_without_content_length, &response);
  7991. // For requests without Content-Length, the server may have different behavior
  7992. // The key is that it should not reject due to payload limit for small
  7993. // payloads
  7994. if (result) {
  7995. // Check for any HTTP response (success or error, but not connection closed)
  7996. if (response.length() > 10) {
  7997. SUCCEED()
  7998. << "Server processed request without Content-Length within limit";
  7999. } else {
  8000. // Short response might indicate connection closed, which is acceptable
  8001. SUCCEED() << "Server closed connection for request without "
  8002. "Content-Length (acceptable behavior)";
  8003. }
  8004. } else {
  8005. // Connection failure might be due to protocol requirements
  8006. SUCCEED() << "Connection issue with request without Content-Length "
  8007. "(environment-specific)";
  8008. }
  8009. }
  8010. class LargePayloadMaxLengthTest : public ::testing::Test {
  8011. protected:
  8012. LargePayloadMaxLengthTest()
  8013. : cli_(HOST, PORT)
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. ,
  8016. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8017. #endif
  8018. {
  8019. #ifdef CPPHTTPLIB_SSL_ENABLED
  8020. cli_.enable_server_certificate_verification(false);
  8021. #endif
  8022. }
  8023. virtual void SetUp() {
  8024. // Set 10MB payload limit
  8025. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8026. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8027. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8028. res.set_content("Large payload test", "text/plain");
  8029. });
  8030. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8031. svr_.wait_until_ready();
  8032. }
  8033. virtual void TearDown() {
  8034. svr_.stop();
  8035. t_.join();
  8036. }
  8037. #ifdef CPPHTTPLIB_SSL_ENABLED
  8038. SSLClient cli_;
  8039. SSLServer svr_;
  8040. #else
  8041. Client cli_;
  8042. Server svr_;
  8043. #endif
  8044. thread t_;
  8045. };
  8046. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8047. // Test chunked encoding with payload within 10MB limit
  8048. std::string medium_payload(5 * 1024 * 1024,
  8049. 'A'); // 5MB payload, within 10MB limit
  8050. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8051. ASSERT_TRUE(res);
  8052. EXPECT_EQ(StatusCode::OK_200, res->status);
  8053. }
  8054. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8055. // Test chunked encoding with payload exceeding 10MB limit
  8056. std::string large_payload(12 * 1024 * 1024,
  8057. 'B'); // 12MB payload, exceeds 10MB limit
  8058. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8059. // Server may either return 413 or close the connection
  8060. if (res) {
  8061. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8062. } else {
  8063. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8064. }
  8065. }
  8066. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8067. // Test request without Content-Length header within 10MB limit
  8068. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8069. "Host: " +
  8070. std::string(HOST) + ":" +
  8071. std::to_string(PORT) +
  8072. "\r\n"
  8073. "Connection: close\r\n"
  8074. "\r\n";
  8075. // Add 1MB payload (within 10MB limit)
  8076. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8077. request_without_content_length += medium_payload;
  8078. std::string response;
  8079. bool result = send_request(5, request_without_content_length, &response);
  8080. if (result) {
  8081. // Should get a proper HTTP response for payloads within limit
  8082. if (response.length() > 10) {
  8083. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8084. "10MB limit";
  8085. } else {
  8086. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8087. "Content-Length)";
  8088. }
  8089. } else {
  8090. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8091. }
  8092. }
  8093. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8094. // Test request without Content-Length header exceeding 10MB limit
  8095. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8096. "Host: " +
  8097. std::string(HOST) + ":" +
  8098. std::to_string(PORT) +
  8099. "\r\n"
  8100. "Connection: close\r\n"
  8101. "\r\n";
  8102. // Add 12MB payload (exceeds 10MB limit)
  8103. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8104. request_without_content_length += large_payload;
  8105. std::string response;
  8106. bool result = send_request(10, request_without_content_length, &response);
  8107. if (!result) {
  8108. // Server should close connection due to payload limit
  8109. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8110. "(connection closed)";
  8111. } else {
  8112. // Check for error response
  8113. if (response.length() <= 10) {
  8114. SUCCEED()
  8115. << "Server closed connection for 12MB request exceeding 10MB limit";
  8116. } else {
  8117. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8118. response.find("Payload Too Large") != std::string::npos ||
  8119. response.find("400") != std::string::npos);
  8120. }
  8121. }
  8122. }
  8123. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8124. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8125. // path.
  8126. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8127. Server svr;
  8128. const size_t LIMIT = 64 * 1024; // 64KB
  8129. svr.set_payload_max_length(LIMIT);
  8130. size_t total = 0;
  8131. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8132. const ContentReader &content_reader) {
  8133. content_reader([&](const char * /*data*/, size_t len) {
  8134. total += len;
  8135. return true;
  8136. });
  8137. res.status = 200;
  8138. res.set_content("stream_ok", "text/plain");
  8139. });
  8140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8141. auto se = detail::scope_exit([&] {
  8142. svr.stop();
  8143. thread.join();
  8144. ASSERT_FALSE(svr.is_running());
  8145. });
  8146. svr.wait_until_ready();
  8147. // Prepare 256KB raw data and gzip-compress it
  8148. std::string raw(256 * 1024, 'A');
  8149. std::string gz;
  8150. {
  8151. z_stream zs{};
  8152. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8153. Z_DEFAULT_STRATEGY);
  8154. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8155. zs.avail_in = static_cast<uInt>(raw.size());
  8156. char outbuf[4096];
  8157. int ret;
  8158. do {
  8159. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8160. zs.avail_out = sizeof(outbuf);
  8161. ret = deflate(&zs, Z_FINISH);
  8162. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8163. } while (ret != Z_STREAM_END);
  8164. deflateEnd(&zs);
  8165. }
  8166. Client cli(HOST, PORT);
  8167. cli.set_connection_timeout(std::chrono::seconds(5));
  8168. Headers headers = {{"Content-Encoding", "gzip"}};
  8169. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8170. "application/octet-stream");
  8171. ASSERT_TRUE(res);
  8172. // Server must reject oversized decompressed payloads with 413.
  8173. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8174. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8175. EXPECT_LE(total, LIMIT);
  8176. }
  8177. #endif
  8178. // Regression test for DoS vulnerability: a malicious server sending a response
  8179. // without Content-Length header must not cause unbounded memory consumption on
  8180. // the client side. The client should stop reading after a reasonable limit,
  8181. // similar to the server-side set_payload_max_length protection.
  8182. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8183. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8184. #ifndef _WIN32
  8185. signal(SIGPIPE, SIG_IGN);
  8186. #endif
  8187. auto server_thread = std::thread([] {
  8188. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8189. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8190. default_socket_options(srv);
  8191. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8192. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8193. sockaddr_in addr{};
  8194. addr.sin_family = AF_INET;
  8195. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8196. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8197. int opt = 1;
  8198. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8199. #ifdef _WIN32
  8200. reinterpret_cast<const char *>(&opt),
  8201. #else
  8202. &opt,
  8203. #endif
  8204. sizeof(opt));
  8205. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8206. ::listen(srv, 1);
  8207. sockaddr_in cli_addr{};
  8208. socklen_t cli_len = sizeof(cli_addr);
  8209. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8210. if (cli != INVALID_SOCKET) {
  8211. char buf[4096];
  8212. ::recv(cli, buf, sizeof(buf), 0);
  8213. // Malicious response: no Content-Length, no chunked encoding
  8214. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8215. "Connection: close\r\n"
  8216. "\r\n";
  8217. ::send(cli,
  8218. #ifdef _WIN32
  8219. static_cast<const char *>(response_header.c_str()),
  8220. static_cast<int>(response_header.size()),
  8221. #else
  8222. response_header.c_str(), response_header.size(),
  8223. #endif
  8224. 0);
  8225. // Send 10MB of data
  8226. std::string chunk(64 * 1024, 'A');
  8227. size_t total_sent = 0;
  8228. while (total_sent < MALICIOUS_DATA_SIZE) {
  8229. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8230. auto sent = ::send(cli,
  8231. #ifdef _WIN32
  8232. static_cast<const char *>(chunk.c_str()),
  8233. static_cast<int>(to_send),
  8234. #else
  8235. chunk.c_str(), to_send,
  8236. #endif
  8237. 0);
  8238. if (sent <= 0) break;
  8239. total_sent += static_cast<size_t>(sent);
  8240. }
  8241. detail::close_socket(cli);
  8242. }
  8243. detail::close_socket(srv);
  8244. });
  8245. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8246. size_t total_read = 0;
  8247. {
  8248. Client cli("127.0.0.1", PORT + 2);
  8249. cli.set_read_timeout(5, 0);
  8250. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8251. auto stream = cli.open_stream("GET", "/malicious");
  8252. ASSERT_TRUE(stream.is_valid());
  8253. char buffer[64 * 1024];
  8254. ssize_t n;
  8255. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8256. total_read += static_cast<size_t>(n);
  8257. }
  8258. } // StreamHandle and Client destroyed here, closing the socket
  8259. server_thread.join();
  8260. // With set_payload_max_length, the client must stop reading before consuming
  8261. // all 10MB. The read loop should be cut off at or near the configured limit.
  8262. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8263. << "Client read " << total_read << " bytes, exceeding the configured "
  8264. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8265. }
  8266. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8267. // the entire response body without truncation.
  8268. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8269. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8270. #ifndef _WIN32
  8271. signal(SIGPIPE, SIG_IGN);
  8272. #endif
  8273. auto server_thread = std::thread([] {
  8274. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8275. default_socket_options(srv);
  8276. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8277. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8278. sockaddr_in addr{};
  8279. addr.sin_family = AF_INET;
  8280. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8281. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8282. int opt = 1;
  8283. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8284. #ifdef _WIN32
  8285. reinterpret_cast<const char *>(&opt),
  8286. #else
  8287. &opt,
  8288. #endif
  8289. sizeof(opt));
  8290. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8291. ::listen(srv, 1);
  8292. sockaddr_in cli_addr{};
  8293. socklen_t cli_len = sizeof(cli_addr);
  8294. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8295. if (cli != INVALID_SOCKET) {
  8296. char buf[4096];
  8297. ::recv(cli, buf, sizeof(buf), 0);
  8298. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8299. "Connection: close\r\n"
  8300. "\r\n";
  8301. ::send(cli,
  8302. #ifdef _WIN32
  8303. static_cast<const char *>(response_header.c_str()),
  8304. static_cast<int>(response_header.size()),
  8305. #else
  8306. response_header.c_str(), response_header.size(),
  8307. #endif
  8308. 0);
  8309. std::string chunk(64 * 1024, 'A');
  8310. size_t total_sent = 0;
  8311. while (total_sent < DATA_SIZE) {
  8312. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8313. auto sent = ::send(cli,
  8314. #ifdef _WIN32
  8315. static_cast<const char *>(chunk.c_str()),
  8316. static_cast<int>(to_send),
  8317. #else
  8318. chunk.c_str(), to_send,
  8319. #endif
  8320. 0);
  8321. if (sent <= 0) break;
  8322. total_sent += static_cast<size_t>(sent);
  8323. }
  8324. #ifdef _WIN32
  8325. ::shutdown(cli, SD_SEND);
  8326. #else
  8327. ::shutdown(cli, SHUT_WR);
  8328. #endif
  8329. // Drain until the client closes its end, ensuring all data is delivered
  8330. char drain[1024];
  8331. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8332. detail::close_socket(cli);
  8333. }
  8334. detail::close_socket(srv);
  8335. });
  8336. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8337. size_t total_read = 0;
  8338. {
  8339. Client cli("127.0.0.1", PORT + 2);
  8340. cli.set_read_timeout(5, 0);
  8341. cli.set_payload_max_length(0); // 0 means no limit
  8342. auto stream = cli.open_stream("GET", "/data");
  8343. ASSERT_TRUE(stream.is_valid());
  8344. char buffer[64 * 1024];
  8345. ssize_t n;
  8346. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8347. total_read += static_cast<size_t>(n);
  8348. }
  8349. }
  8350. server_thread.join();
  8351. EXPECT_EQ(total_read, DATA_SIZE)
  8352. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8353. << " bytes without truncation, but only read " << total_read << " bytes.";
  8354. }
  8355. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8356. // enormous Content-Length must not cause the client to pre-allocate a huge
  8357. // response body buffer. The reservation is capped at payload_max_length_, and
  8358. // the read itself fails when the body exceeds the limit.
  8359. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8360. #ifndef _WIN32
  8361. signal(SIGPIPE, SIG_IGN);
  8362. #endif
  8363. auto server_thread = std::thread([] {
  8364. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8365. default_socket_options(srv);
  8366. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8367. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8368. sockaddr_in addr{};
  8369. addr.sin_family = AF_INET;
  8370. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8371. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8372. int opt = 1;
  8373. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8374. #ifdef _WIN32
  8375. reinterpret_cast<const char *>(&opt),
  8376. #else
  8377. &opt,
  8378. #endif
  8379. sizeof(opt));
  8380. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8381. ::listen(srv, 1);
  8382. sockaddr_in cli_addr{};
  8383. socklen_t cli_len = sizeof(cli_addr);
  8384. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8385. if (cli != INVALID_SOCKET) {
  8386. char buf[4096];
  8387. ::recv(cli, buf, sizeof(buf), 0);
  8388. // Malicious response: claim a 20GB body but send only a tiny payload.
  8389. std::string response = "HTTP/1.1 200 OK\r\n"
  8390. "Content-Length: 20000000000\r\n"
  8391. "\r\n"
  8392. "abc";
  8393. ::send(cli,
  8394. #ifdef _WIN32
  8395. static_cast<const char *>(response.c_str()),
  8396. static_cast<int>(response.size()),
  8397. #else
  8398. response.c_str(), response.size(),
  8399. #endif
  8400. 0);
  8401. detail::close_socket(cli);
  8402. }
  8403. detail::close_socket(srv);
  8404. });
  8405. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8406. {
  8407. Client cli("127.0.0.1", PORT + 2);
  8408. cli.set_read_timeout(5, 0);
  8409. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8410. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8411. // (server claims more bytes than payload_max_length permits), but it must
  8412. // not exhaust memory before getting there.
  8413. auto res = cli.Get("/malicious");
  8414. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8415. }
  8416. server_thread.join();
  8417. }
  8418. // Verify that content_receiver bypasses the default payload_max_length,
  8419. // allowing streaming downloads larger than 100MB without requiring an explicit
  8420. // set_payload_max_length call.
  8421. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8422. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8423. #ifndef _WIN32
  8424. signal(SIGPIPE, SIG_IGN);
  8425. #endif
  8426. auto server_thread = std::thread([] {
  8427. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8428. default_socket_options(srv);
  8429. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8430. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8431. sockaddr_in addr{};
  8432. addr.sin_family = AF_INET;
  8433. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8434. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8435. int opt = 1;
  8436. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8437. #ifdef _WIN32
  8438. reinterpret_cast<const char *>(&opt),
  8439. #else
  8440. &opt,
  8441. #endif
  8442. sizeof(opt));
  8443. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8444. ::listen(srv, 1);
  8445. sockaddr_in cli_addr{};
  8446. socklen_t cli_len = sizeof(cli_addr);
  8447. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8448. if (cli != INVALID_SOCKET) {
  8449. char buf[4096];
  8450. ::recv(cli, buf, sizeof(buf), 0);
  8451. // Response with Content-Length larger than default 100MB limit
  8452. auto content_length = std::to_string(DATA_SIZE);
  8453. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8454. "Content-Length: " +
  8455. content_length +
  8456. "\r\n"
  8457. "Connection: close\r\n"
  8458. "\r\n";
  8459. ::send(cli,
  8460. #ifdef _WIN32
  8461. static_cast<const char *>(response_header.c_str()),
  8462. static_cast<int>(response_header.size()),
  8463. #else
  8464. response_header.c_str(), response_header.size(),
  8465. #endif
  8466. 0);
  8467. std::string chunk(64 * 1024, 'A');
  8468. size_t total_sent = 0;
  8469. while (total_sent < DATA_SIZE) {
  8470. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8471. auto sent = ::send(cli,
  8472. #ifdef _WIN32
  8473. static_cast<const char *>(chunk.c_str()),
  8474. static_cast<int>(to_send),
  8475. #else
  8476. chunk.c_str(), to_send,
  8477. #endif
  8478. 0);
  8479. if (sent <= 0) break;
  8480. total_sent += static_cast<size_t>(sent);
  8481. }
  8482. detail::close_socket(cli);
  8483. }
  8484. detail::close_socket(srv);
  8485. });
  8486. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8487. size_t total_received = 0;
  8488. {
  8489. Client cli("127.0.0.1", PORT + 2);
  8490. cli.set_read_timeout(10, 0);
  8491. // Do NOT call set_payload_max_length — use the default 100MB limit
  8492. auto res =
  8493. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8494. total_received += data_length;
  8495. return true;
  8496. });
  8497. ASSERT_TRUE(res);
  8498. EXPECT_EQ(StatusCode::OK_200, res->status);
  8499. }
  8500. server_thread.join();
  8501. EXPECT_EQ(total_received, DATA_SIZE)
  8502. << "With content_receiver, the client should read all " << DATA_SIZE
  8503. << " bytes despite the default 100MB payload_max_length, but only read "
  8504. << total_received << " bytes.";
  8505. }
  8506. // Verify that an explicit set_payload_max_length smaller than the response is
  8507. // enforced even when a content_receiver is used.
  8508. TEST(ClientVulnerabilityTest,
  8509. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8510. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8511. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8512. #ifndef _WIN32
  8513. signal(SIGPIPE, SIG_IGN);
  8514. #endif
  8515. auto server_thread = std::thread([] {
  8516. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8517. default_socket_options(srv);
  8518. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8519. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8520. sockaddr_in addr{};
  8521. addr.sin_family = AF_INET;
  8522. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8523. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8524. int opt = 1;
  8525. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8526. #ifdef _WIN32
  8527. reinterpret_cast<const char *>(&opt),
  8528. #else
  8529. &opt,
  8530. #endif
  8531. sizeof(opt));
  8532. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8533. ::listen(srv, 1);
  8534. sockaddr_in cli_addr{};
  8535. socklen_t cli_len = sizeof(cli_addr);
  8536. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8537. if (cli != INVALID_SOCKET) {
  8538. char buf[4096];
  8539. ::recv(cli, buf, sizeof(buf), 0);
  8540. auto content_length = std::to_string(DATA_SIZE);
  8541. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8542. "Content-Length: " +
  8543. content_length +
  8544. "\r\n"
  8545. "Connection: close\r\n"
  8546. "\r\n";
  8547. ::send(cli,
  8548. #ifdef _WIN32
  8549. static_cast<const char *>(response_header.c_str()),
  8550. static_cast<int>(response_header.size()),
  8551. #else
  8552. response_header.c_str(), response_header.size(),
  8553. #endif
  8554. 0);
  8555. std::string chunk(64 * 1024, 'A');
  8556. size_t total_sent = 0;
  8557. while (total_sent < DATA_SIZE) {
  8558. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8559. auto sent = ::send(cli,
  8560. #ifdef _WIN32
  8561. static_cast<const char *>(chunk.c_str()),
  8562. static_cast<int>(to_send),
  8563. #else
  8564. chunk.c_str(), to_send,
  8565. #endif
  8566. 0);
  8567. if (sent <= 0) break;
  8568. total_sent += static_cast<size_t>(sent);
  8569. }
  8570. detail::close_socket(cli);
  8571. }
  8572. detail::close_socket(srv);
  8573. });
  8574. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8575. size_t total_received = 0;
  8576. {
  8577. Client cli("127.0.0.1", PORT + 2);
  8578. cli.set_read_timeout(10, 0);
  8579. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8580. auto res =
  8581. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8582. total_received += data_length;
  8583. return true;
  8584. });
  8585. // Should fail because 200MB exceeds the explicit 150MB limit
  8586. EXPECT_FALSE(res);
  8587. }
  8588. server_thread.join();
  8589. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8590. << "Client with content_receiver should respect the explicit "
  8591. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8592. << total_received << " bytes.";
  8593. }
  8594. // Verify that an explicit set_payload_max_length larger than the response
  8595. // allows the content_receiver to read all data successfully.
  8596. TEST(ClientVulnerabilityTest,
  8597. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8598. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8599. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8600. #ifndef _WIN32
  8601. signal(SIGPIPE, SIG_IGN);
  8602. #endif
  8603. auto server_thread = std::thread([] {
  8604. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8605. default_socket_options(srv);
  8606. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8607. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8608. sockaddr_in addr{};
  8609. addr.sin_family = AF_INET;
  8610. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8611. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8612. int opt = 1;
  8613. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8614. #ifdef _WIN32
  8615. reinterpret_cast<const char *>(&opt),
  8616. #else
  8617. &opt,
  8618. #endif
  8619. sizeof(opt));
  8620. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8621. ::listen(srv, 1);
  8622. sockaddr_in cli_addr{};
  8623. socklen_t cli_len = sizeof(cli_addr);
  8624. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8625. if (cli != INVALID_SOCKET) {
  8626. char buf[4096];
  8627. ::recv(cli, buf, sizeof(buf), 0);
  8628. auto content_length = std::to_string(DATA_SIZE);
  8629. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8630. "Content-Length: " +
  8631. content_length +
  8632. "\r\n"
  8633. "Connection: close\r\n"
  8634. "\r\n";
  8635. ::send(cli,
  8636. #ifdef _WIN32
  8637. static_cast<const char *>(response_header.c_str()),
  8638. static_cast<int>(response_header.size()),
  8639. #else
  8640. response_header.c_str(), response_header.size(),
  8641. #endif
  8642. 0);
  8643. std::string chunk(64 * 1024, 'A');
  8644. size_t total_sent = 0;
  8645. while (total_sent < DATA_SIZE) {
  8646. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8647. auto sent = ::send(cli,
  8648. #ifdef _WIN32
  8649. static_cast<const char *>(chunk.c_str()),
  8650. static_cast<int>(to_send),
  8651. #else
  8652. chunk.c_str(), to_send,
  8653. #endif
  8654. 0);
  8655. if (sent <= 0) break;
  8656. total_sent += static_cast<size_t>(sent);
  8657. }
  8658. #ifdef _WIN32
  8659. ::shutdown(cli, SD_SEND);
  8660. #else
  8661. ::shutdown(cli, SHUT_WR);
  8662. #endif
  8663. char drain[1024];
  8664. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8665. detail::close_socket(cli);
  8666. }
  8667. detail::close_socket(srv);
  8668. });
  8669. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8670. size_t total_received = 0;
  8671. {
  8672. Client cli("127.0.0.1", PORT + 2);
  8673. cli.set_read_timeout(10, 0);
  8674. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8675. auto res =
  8676. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8677. total_received += data_length;
  8678. return true;
  8679. });
  8680. ASSERT_TRUE(res);
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. }
  8683. server_thread.join();
  8684. EXPECT_EQ(total_received, DATA_SIZE)
  8685. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8686. << " bytes (larger than " << DATA_SIZE
  8687. << " bytes response), content_receiver should read all data, but only "
  8688. "read "
  8689. << total_received << " bytes.";
  8690. }
  8691. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8692. // Regression test for "zip bomb" attack on the client side: a malicious server
  8693. // sends a small gzip-compressed response that decompresses to a huge payload.
  8694. // The client must enforce payload_max_length on the decompressed size.
  8695. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8696. constexpr size_t DECOMPRESSED_SIZE =
  8697. 10 * 1024 * 1024; // 10MB after decompression
  8698. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8699. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8700. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8701. std::string compressed;
  8702. {
  8703. httplib::detail::gzip_compressor compressor;
  8704. bool ok =
  8705. compressor.compress(uncompressed.data(), uncompressed.size(),
  8706. /*last=*/true, [&](const char *buf, size_t len) {
  8707. compressed.append(buf, len);
  8708. return true;
  8709. });
  8710. ASSERT_TRUE(ok);
  8711. }
  8712. // Sanity: compressed data should be much smaller than the decompressed size
  8713. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8714. #ifndef _WIN32
  8715. signal(SIGPIPE, SIG_IGN);
  8716. #endif
  8717. // Set up the listening socket in the main thread so the server is guaranteed
  8718. // to be ready before the client connects (eliminates race condition).
  8719. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8720. default_socket_options(srv);
  8721. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8722. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8723. sockaddr_in addr{};
  8724. addr.sin_family = AF_INET;
  8725. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8726. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8727. int opt = 1;
  8728. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8729. #ifdef _WIN32
  8730. reinterpret_cast<const char *>(&opt),
  8731. #else
  8732. &opt,
  8733. #endif
  8734. sizeof(opt));
  8735. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8736. ASSERT_EQ(0, ::listen(srv, 1));
  8737. auto server_thread = std::thread([&compressed, srv] {
  8738. sockaddr_in cli_addr{};
  8739. socklen_t cli_len = sizeof(cli_addr);
  8740. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8741. if (cli != INVALID_SOCKET) {
  8742. // Read the full HTTP request (until \r\n\r\n)
  8743. char buf[4096];
  8744. size_t total = 0;
  8745. while (total < sizeof(buf)) {
  8746. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8747. if (n <= 0) break;
  8748. total += static_cast<size_t>(n);
  8749. // Check for end of headers
  8750. if (total >= 4) {
  8751. std::string req(buf, total);
  8752. if (req.find("\r\n\r\n") != std::string::npos) break;
  8753. }
  8754. }
  8755. // Malicious response: gzip-compressed body, no Content-Length
  8756. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8757. "Content-Encoding: gzip\r\n"
  8758. "Connection: close\r\n"
  8759. "\r\n";
  8760. ::send(cli,
  8761. #ifdef _WIN32
  8762. static_cast<const char *>(response_header.c_str()),
  8763. static_cast<int>(response_header.size()),
  8764. #else
  8765. response_header.c_str(), response_header.size(),
  8766. #endif
  8767. 0);
  8768. // Send the compressed payload (small on the wire, huge when decompressed)
  8769. size_t total_sent = 0;
  8770. while (total_sent < compressed.size()) {
  8771. auto to_send = std::min(compressed.size() - total_sent,
  8772. static_cast<size_t>(64 * 1024));
  8773. auto sent =
  8774. ::send(cli,
  8775. #ifdef _WIN32
  8776. static_cast<const char *>(compressed.c_str() + total_sent),
  8777. static_cast<int>(to_send),
  8778. #else
  8779. compressed.c_str() + total_sent, to_send,
  8780. #endif
  8781. 0);
  8782. if (sent <= 0) break;
  8783. total_sent += static_cast<size_t>(sent);
  8784. }
  8785. detail::close_socket(cli);
  8786. }
  8787. });
  8788. auto se = detail::scope_exit([&] {
  8789. detail::close_socket(srv);
  8790. server_thread.join();
  8791. });
  8792. size_t total_decompressed = 0;
  8793. {
  8794. Client cli("127.0.0.1", PORT + 3);
  8795. cli.set_read_timeout(5, 0);
  8796. cli.set_decompress(true);
  8797. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8798. auto stream = cli.open_stream("GET", "/zipbomb");
  8799. ASSERT_TRUE(stream.is_valid());
  8800. char buffer[64 * 1024];
  8801. ssize_t n;
  8802. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8803. total_decompressed += static_cast<size_t>(n);
  8804. }
  8805. }
  8806. // The decompressed size must be capped by payload_max_length. Without
  8807. // protection, the client would decompress the full 10MB from a tiny
  8808. // compressed payload, enabling a zip bomb DoS attack.
  8809. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8810. << "Client decompressed " << total_decompressed
  8811. << " bytes from a gzip response. The decompressed size should be "
  8812. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8813. }
  8814. #endif
  8815. TEST(HostAndPortPropertiesTest, NoSSL) {
  8816. httplib::Client cli("www.google.com", 1234);
  8817. ASSERT_EQ("www.google.com", cli.host());
  8818. ASSERT_EQ(1234, cli.port());
  8819. }
  8820. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8821. httplib::Client cli("www.google.com:1234");
  8822. ASSERT_EQ("www.google.com", cli.host());
  8823. ASSERT_EQ(1234, cli.port());
  8824. }
  8825. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8826. // Port number that overflows int — should not crash, client becomes invalid
  8827. httplib::Client cli("http://www.google.com:99999999999999999999");
  8828. ASSERT_FALSE(cli.is_valid());
  8829. }
  8830. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8831. // Port 99999 exceeds valid range (1-65535) — should not crash
  8832. httplib::Client cli("http://www.google.com:99999");
  8833. ASSERT_FALSE(cli.is_valid());
  8834. }
  8835. #ifdef CPPHTTPLIB_SSL_ENABLED
  8836. TEST(HostAndPortPropertiesTest, SSL) {
  8837. httplib::SSLClient cli("www.google.com");
  8838. ASSERT_EQ("www.google.com", cli.host());
  8839. ASSERT_EQ(443, cli.port());
  8840. }
  8841. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8842. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8843. std::string cert;
  8844. read_file(CA_CERT_FILE, cert);
  8845. httplib::SSLClient httplib_client("www.google.com");
  8846. // Load CA store first time
  8847. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8848. // Load CA store second time (update)
  8849. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8850. // Verify client is still valid and can make connections
  8851. httplib_client.enable_server_certificate_verification(true);
  8852. auto res = httplib_client.Get("/");
  8853. ASSERT_TRUE(res);
  8854. // Google may return 200 or 301 depending on various factors
  8855. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8856. res->status == StatusCode::MovedPermanently_301);
  8857. }
  8858. TEST(SSLClientTest, ServerNameIndication_Online) {
  8859. auto host = "httpbingo.org";
  8860. auto path = std::string{"/get"};
  8861. SSLClient cli(host, 443);
  8862. auto res = cli.Get(path);
  8863. ASSERT_TRUE(res);
  8864. ASSERT_EQ(StatusCode::OK_200, res->status);
  8865. }
  8866. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8867. // Use a site that will cause SSL verification failure due to self-signed cert
  8868. SSLClient cli("self-signed.badssl.com", 443);
  8869. cli.enable_server_certificate_verification(true);
  8870. auto res = cli.Get("/");
  8871. ASSERT_TRUE(!res);
  8872. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8873. // Verify backend error is captured for SSLServerVerification
  8874. // This occurs when certificate verification fails
  8875. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8876. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8877. EXPECT_NE(0UL, res.ssl_backend_error());
  8878. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8879. // For OpenSSL, ssl_error is 0 for verification errors
  8880. EXPECT_EQ(0, res.ssl_error());
  8881. #if !defined(_WIN32) || \
  8882. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8883. // On non-Windows or when Windows Schannel is disabled, the error comes
  8884. // from OpenSSL's verification
  8885. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8886. res.ssl_backend_error());
  8887. #endif
  8888. #endif
  8889. }
  8890. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8891. // Use a site where hostname doesn't match the certificate
  8892. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8893. SSLClient cli("wrong.host.badssl.com", 443);
  8894. cli.enable_server_certificate_verification(true);
  8895. cli.enable_server_hostname_verification(true);
  8896. auto res = cli.Get("/");
  8897. ASSERT_TRUE(!res);
  8898. // The error type depends on when hostname verification occurs:
  8899. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8900. // - Mbed TLS: SSLServerVerification (during handshake)
  8901. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8902. res.error() == Error::SSLServerVerification);
  8903. // Verify backend error is captured for hostname verification failure
  8904. EXPECT_NE(0UL, res.ssl_backend_error());
  8905. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8906. // For OpenSSL, ssl_error is 0 for verification errors
  8907. EXPECT_EQ(0, res.ssl_error());
  8908. #if !defined(_WIN32) || \
  8909. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8910. // On non-Windows or when Windows Schannel is disabled, the error comes
  8911. // from OpenSSL's hostname verification
  8912. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8913. res.ssl_backend_error());
  8914. #endif
  8915. #endif
  8916. }
  8917. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8918. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8919. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8920. SSLClient cli("www.google.com", 443);
  8921. cli.enable_server_certificate_verification(true);
  8922. auto res = cli.Get("/");
  8923. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8924. }
  8925. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8926. SSLClient cli("www.google.com", 443);
  8927. cli.enable_server_certificate_verification(true);
  8928. cli.enable_windows_certificate_verification(false);
  8929. auto res = cli.Get("/");
  8930. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8931. }
  8932. #endif
  8933. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8934. Client cli("https://google.com");
  8935. auto res = cli.Get("/");
  8936. ASSERT_TRUE(res);
  8937. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8938. }
  8939. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8940. SSLClient cli("google.com");
  8941. cli.set_ca_cert_path(CA_CERT_FILE);
  8942. auto res = cli.Get("/");
  8943. ASSERT_TRUE(res);
  8944. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8945. }
  8946. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8947. SSLClient cli("google.com");
  8948. cli.enable_server_certificate_verification(true);
  8949. cli.set_ca_cert_path("hello");
  8950. auto res = cli.Get("/");
  8951. ASSERT_TRUE(!res);
  8952. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8953. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8954. // should be set
  8955. EXPECT_EQ(0, res.ssl_error());
  8956. // Verify backend error is captured for SSLLoadingCerts
  8957. // This error occurs when loading CA certificates fails
  8958. EXPECT_NE(0UL, res.ssl_backend_error());
  8959. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8960. // OpenSSL specific error codes:
  8961. // > openssl errstr 0x80000002
  8962. // error:80000002:system library::No such file or directory
  8963. // > openssl errstr 0xA000126
  8964. // error:0A000126:SSL routines::unexpected eof while reading
  8965. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8966. res.ssl_backend_error() == 0xA000126);
  8967. #endif
  8968. }
  8969. TEST(SSLClientTest, ServerCertificateVerification4) {
  8970. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8971. ASSERT_TRUE(svr.is_valid());
  8972. svr.Get("/test", [&](const Request &, Response &res) {
  8973. res.set_content("test", "text/plain");
  8974. svr.stop();
  8975. ASSERT_TRUE(true);
  8976. });
  8977. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8978. auto se = detail::scope_exit([&] {
  8979. t.join();
  8980. ASSERT_FALSE(svr.is_running());
  8981. });
  8982. svr.wait_until_ready();
  8983. SSLClient cli("127.0.0.1", PORT);
  8984. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8985. cli.enable_server_certificate_verification(true);
  8986. cli.set_connection_timeout(30);
  8987. auto res = cli.Get("/test");
  8988. ASSERT_TRUE(res);
  8989. ASSERT_EQ(StatusCode::OK_200, res->status);
  8990. }
  8991. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8992. std::string cert;
  8993. read_file(CA_CERT_FILE, cert);
  8994. SSLClient cli("google.com");
  8995. cli.load_ca_cert_store(cert.data(), cert.size());
  8996. const auto res = cli.Get("/");
  8997. ASSERT_TRUE(res);
  8998. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8999. }
  9000. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9001. // clang-format off
  9002. static constexpr char cert[] =
  9003. "GlobalSign Root CA\n"
  9004. "==================\n"
  9005. "-----BEGIN CERTIFICATE-----\n"
  9006. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9007. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9008. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9009. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9010. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9011. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9012. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9013. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9014. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9015. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9016. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9017. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9018. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9019. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9020. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9021. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9022. "-----END CERTIFICATE-----\n";
  9023. // clang-format on
  9024. SSLClient cli("google.com");
  9025. cli.load_ca_cert_store(cert, sizeof(cert));
  9026. const auto res = cli.Get("/");
  9027. ASSERT_TRUE(res);
  9028. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9029. }
  9030. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9031. SSLClient cli("www.youtube.com");
  9032. cli.set_ca_cert_path(CA_CERT_FILE);
  9033. cli.enable_server_certificate_verification(true);
  9034. cli.set_follow_location(true);
  9035. auto res = cli.Get("/");
  9036. ASSERT_TRUE(res);
  9037. ASSERT_EQ(StatusCode::OK_200, res->status);
  9038. }
  9039. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9040. SSLClient cli("wWw.YouTube.Com");
  9041. cli.set_ca_cert_path(CA_CERT_FILE);
  9042. cli.enable_server_certificate_verification(true);
  9043. cli.enable_server_hostname_verification(true);
  9044. cli.set_follow_location(true);
  9045. auto res = cli.Get("/");
  9046. ASSERT_TRUE(res);
  9047. ASSERT_EQ(StatusCode::OK_200, res->status);
  9048. }
  9049. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9050. SSLClient cli("gOoGlE.COm");
  9051. cli.enable_server_certificate_verification(true);
  9052. cli.enable_server_hostname_verification(true);
  9053. cli.set_follow_location(true);
  9054. auto res = cli.Get("/");
  9055. ASSERT_TRUE(res);
  9056. ASSERT_EQ(StatusCode::OK_200, res->status);
  9057. }
  9058. TEST(SSLClientTest, Issue2004_Online) {
  9059. Client client("https://google.com");
  9060. client.set_follow_location(true);
  9061. auto res = client.Get("/");
  9062. ASSERT_TRUE(res);
  9063. ASSERT_EQ(StatusCode::OK_200, res->status);
  9064. auto body = res->body;
  9065. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9066. }
  9067. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9068. // Create SSLClient with invalid cert/key to make is_valid() return false
  9069. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9070. "nonexistent_key.pem");
  9071. // is_valid() should be false due to cert loading failure
  9072. ASSERT_FALSE(cli.is_valid());
  9073. auto res = cli.Get("/");
  9074. ASSERT_FALSE(res);
  9075. EXPECT_EQ(Error::SSLConnection, res.error());
  9076. }
  9077. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9078. // Test for Issue #2251: SSL error not properly reported when client cert
  9079. // and key paths are swapped or mismatched
  9080. // This simulates the scenario where user accidentally swaps the cert and key
  9081. // files
  9082. // Using client cert file as private key and vice versa (completely wrong)
  9083. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9084. // Should fail validation due to cert/key mismatch
  9085. ASSERT_FALSE(cli.is_valid());
  9086. // Attempt to make a request should fail with proper error
  9087. auto res = cli.Get("/");
  9088. ASSERT_FALSE(res);
  9089. EXPECT_EQ(Error::SSLConnection, res.error());
  9090. // SSL error should be recorded in the Result object (this is the key fix for
  9091. // Issue #2251)
  9092. auto backend_error = res.ssl_backend_error();
  9093. EXPECT_NE(0u, backend_error);
  9094. }
  9095. // Tests cert/key mismatch detection at the TLS context level
  9096. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9097. // Test that using mismatched cert/key causes connection failure.
  9098. // We verify this at the SSLClient level rather than through internal
  9099. // TLS API functions.
  9100. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9101. cli.enable_server_certificate_verification(false);
  9102. cli.set_connection_timeout(2);
  9103. // The mismatch should cause a connection or handshake error
  9104. auto res = cli.Get("/test");
  9105. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9106. // Either way, the request should fail
  9107. EXPECT_FALSE(res);
  9108. }
  9109. #endif
  9110. #if 0
  9111. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9112. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9113. ASSERT_TRUE(cli != nullptr);
  9114. cli->set_address_family(AF_INET6);
  9115. cli->set_interface("en0");
  9116. auto res = cli->Get("/get");
  9117. ASSERT_TRUE(res);
  9118. ASSERT_EQ(StatusCode::OK_200, res->status);
  9119. }
  9120. #endif
  9121. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9122. #ifdef CPPHTTPLIB_SSL_ENABLED
  9123. void ClientCertPresent(
  9124. const std::string &client_cert_file,
  9125. const std::string &client_private_key_file,
  9126. const std::string &client_encrypted_private_key_pass = std::string()) {
  9127. using namespace httplib::tls;
  9128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9129. CLIENT_CA_CERT_DIR);
  9130. ASSERT_TRUE(svr.is_valid());
  9131. svr.Get("/test", [&](const Request &req, Response &res) {
  9132. res.set_content("test", "text/plain");
  9133. auto cert = req.peer_cert();
  9134. ASSERT_TRUE(static_cast<bool>(cert));
  9135. std::string common_name = cert.subject_cn();
  9136. EXPECT_EQ("Common Name", common_name);
  9137. });
  9138. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9139. auto se = detail::scope_exit([&] {
  9140. svr.stop();
  9141. t.join();
  9142. ASSERT_FALSE(svr.is_running());
  9143. });
  9144. svr.wait_until_ready();
  9145. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9146. client_encrypted_private_key_pass);
  9147. cli.enable_server_certificate_verification(false);
  9148. cli.set_connection_timeout(30);
  9149. auto res = cli.Get("/test");
  9150. ASSERT_TRUE(res);
  9151. ASSERT_EQ(StatusCode::OK_200, res->status);
  9152. }
  9153. TEST(SSLClientServerTest, ClientCertPresent) {
  9154. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9155. }
  9156. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9157. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9158. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9159. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9160. }
  9161. // PEM memory-based constructor tests (works with all TLS backends)
  9162. void PemMemoryClientCertPresent(
  9163. const std::string &client_cert_file,
  9164. const std::string &client_private_key_file,
  9165. const std::string &client_encrypted_private_key_pass = std::string()) {
  9166. // Read PEM files into memory
  9167. std::string server_cert_pem, server_key_pem;
  9168. std::string client_ca_pem;
  9169. std::string client_cert_pem, client_key_pem;
  9170. read_file(SERVER_CERT_FILE, server_cert_pem);
  9171. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9172. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9173. read_file(client_cert_file, client_cert_pem);
  9174. read_file(client_private_key_file, client_key_pem);
  9175. // Create server with PEM memory
  9176. SSLServer::PemMemory server_pem = {
  9177. server_cert_pem.c_str(),
  9178. server_cert_pem.size(),
  9179. server_key_pem.c_str(),
  9180. server_key_pem.size(),
  9181. client_ca_pem.c_str(),
  9182. client_ca_pem.size(),
  9183. nullptr // no password for server key
  9184. };
  9185. SSLServer svr(server_pem);
  9186. ASSERT_TRUE(svr.is_valid());
  9187. svr.Get("/test", [&](const Request &, Response &res) {
  9188. res.set_content("test", "text/plain");
  9189. });
  9190. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9191. auto se = detail::scope_exit([&] {
  9192. svr.stop();
  9193. t.join();
  9194. ASSERT_FALSE(svr.is_running());
  9195. });
  9196. svr.wait_until_ready();
  9197. // Create client with PEM memory
  9198. const char *password = client_encrypted_private_key_pass.empty()
  9199. ? nullptr
  9200. : client_encrypted_private_key_pass.c_str();
  9201. SSLClient::PemMemory client_pem = {
  9202. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9203. client_key_pem.size(), password};
  9204. SSLClient cli(HOST, PORT, client_pem);
  9205. cli.enable_server_certificate_verification(false);
  9206. cli.set_connection_timeout(30);
  9207. auto res = cli.Get("/test");
  9208. ASSERT_TRUE(res);
  9209. ASSERT_EQ(StatusCode::OK_200, res->status);
  9210. }
  9211. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9212. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9213. }
  9214. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9215. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9216. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9217. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9218. }
  9219. TEST(SSLClientServerTest, ClientCertMissing) {
  9220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9221. CLIENT_CA_CERT_DIR);
  9222. ASSERT_TRUE(svr.is_valid());
  9223. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9224. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9225. auto se = detail::scope_exit([&] {
  9226. svr.stop();
  9227. t.join();
  9228. ASSERT_FALSE(svr.is_running());
  9229. });
  9230. svr.wait_until_ready();
  9231. SSLClient cli(HOST, PORT);
  9232. cli.set_connection_timeout(30);
  9233. auto res = cli.Get("/test");
  9234. ASSERT_TRUE(!res);
  9235. // When client cert is missing and server requires it, connection fails
  9236. // Error type depends on backend implementation
  9237. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9238. res.error() == Error::SSLConnection);
  9239. // Verify backend error is captured
  9240. // Note: This test may have different error codes depending on the exact
  9241. // verification failure
  9242. EXPECT_NE(0UL, res.ssl_backend_error());
  9243. }
  9244. TEST(SSLClientServerTest, TrustDirOptional) {
  9245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9246. ASSERT_TRUE(svr.is_valid());
  9247. svr.Get("/test", [&](const Request &, Response &res) {
  9248. res.set_content("test", "text/plain");
  9249. });
  9250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9251. auto se = detail::scope_exit([&] {
  9252. svr.stop();
  9253. t.join();
  9254. ASSERT_FALSE(svr.is_running());
  9255. });
  9256. svr.wait_until_ready();
  9257. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9258. cli.enable_server_certificate_verification(false);
  9259. cli.set_connection_timeout(30);
  9260. auto res = cli.Get("/test");
  9261. ASSERT_TRUE(res);
  9262. ASSERT_EQ(StatusCode::OK_200, res->status);
  9263. }
  9264. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9265. class NoListenSSLServer : public SSLServer {
  9266. public:
  9267. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9268. const char *client_ca_cert_file_path,
  9269. const char *client_ca_cert_dir_path = nullptr)
  9270. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9271. client_ca_cert_dir_path),
  9272. stop_(false) {}
  9273. std::atomic_bool stop_;
  9274. private:
  9275. bool process_and_close_socket(socket_t /*sock*/) override {
  9276. // Don't create SSL context
  9277. while (!stop_.load()) {
  9278. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9279. }
  9280. return true;
  9281. }
  9282. };
  9283. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9284. CLIENT_CA_CERT_FILE);
  9285. ASSERT_TRUE(svr.is_valid());
  9286. svr.Get("/test", [&](const Request &, Response &res) {
  9287. res.set_content("test", "text/plain");
  9288. });
  9289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9290. auto se = detail::scope_exit([&] {
  9291. svr.stop_ = true;
  9292. svr.stop();
  9293. t.join();
  9294. ASSERT_FALSE(svr.is_running());
  9295. });
  9296. svr.wait_until_ready();
  9297. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9298. cli.enable_server_certificate_verification(false);
  9299. cli.set_connection_timeout(1);
  9300. auto res = cli.Get("/test");
  9301. ASSERT_TRUE(!res);
  9302. EXPECT_EQ(Error::SSLConnection, res.error());
  9303. // Timeout results in WantRead error code (maps to backend-specific value)
  9304. EXPECT_NE(0, res.ssl_error());
  9305. }
  9306. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9307. // Test SSLServer with client certificate verification using the standard
  9308. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9309. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9310. CLIENT_CA_CERT_DIR);
  9311. ASSERT_TRUE(svr.is_valid());
  9312. svr.Get("/test", [&](const Request &req, Response &res) {
  9313. res.set_content("test", "text/plain");
  9314. auto cert = req.peer_cert();
  9315. ASSERT_TRUE(static_cast<bool>(cert));
  9316. auto common_name = cert.subject_cn();
  9317. EXPECT_EQ("Common Name", common_name);
  9318. });
  9319. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9320. auto se = detail::scope_exit([&] {
  9321. svr.stop();
  9322. t.join();
  9323. ASSERT_FALSE(svr.is_running());
  9324. });
  9325. svr.wait_until_ready();
  9326. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9327. cli.enable_server_certificate_verification(false);
  9328. cli.set_connection_timeout(30);
  9329. auto res = cli.Get("/test");
  9330. ASSERT_TRUE(res);
  9331. ASSERT_EQ(StatusCode::OK_200, res->status);
  9332. }
  9333. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9334. // Verifies that wildcard matching and exact matching work consistently
  9335. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9336. using namespace httplib::tls;
  9337. // We need a running server to test against
  9338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9339. ASSERT_TRUE(svr.is_valid());
  9340. svr.Get("/test", [](const Request &, Response &res) {
  9341. res.set_content("ok", "text/plain");
  9342. });
  9343. thread t([&]() { svr.listen(HOST, PORT); });
  9344. auto se = detail::scope_exit([&] {
  9345. svr.stop();
  9346. t.join();
  9347. });
  9348. svr.wait_until_ready();
  9349. bool verify_callback_called = false;
  9350. bool verify_result_wrong = false;
  9351. SSLClient cli(HOST, PORT);
  9352. cli.enable_server_certificate_verification(true);
  9353. cli.set_ca_cert_path(CA_CERT_FILE);
  9354. cli.set_connection_timeout(5);
  9355. // Note: Test certificate has CN="Common Name", not "localhost"
  9356. bool verify_result_cn = false;
  9357. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9358. verify_callback_called = true;
  9359. if (!ctx.cert) return false;
  9360. // Test 1: "Common Name" should match (our test server cert CN)
  9361. verify_result_cn = ctx.check_hostname("Common Name");
  9362. // Test 2: wrong hostname should not match
  9363. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9364. return true; // Accept for the purpose of this test
  9365. });
  9366. auto res = cli.Get("/test");
  9367. // The request may succeed or fail depending on cert configuration
  9368. // but the callback should have been called
  9369. ASSERT_TRUE(verify_callback_called)
  9370. << "Verify callback should have been called";
  9371. // CN="Common Name" should match our test certificate
  9372. //
  9373. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9374. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9375. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9376. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9377. // <openssl/base.h>, which is included transitively when
  9378. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9379. #if defined(OPENSSL_IS_BORINGSSL)
  9380. EXPECT_FALSE(verify_result_cn)
  9381. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9382. #else
  9383. EXPECT_TRUE(verify_result_cn)
  9384. << "verify_hostname should match 'Common Name' (certificate CN)";
  9385. #endif
  9386. // Wrong hostname should not match
  9387. EXPECT_FALSE(verify_result_wrong)
  9388. << "verify_hostname should not match 'wronghost.example.com'";
  9389. }
  9390. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9391. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9392. // X509_check_ip behavior and must hold for every backend.
  9393. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9394. using namespace httplib::tls;
  9395. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9396. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9397. ASSERT_TRUE(svr.is_valid());
  9398. svr.Get("/test", [](const Request &, Response &res) {
  9399. res.set_content("ok", "text/plain");
  9400. });
  9401. thread t([&]() { svr.listen(HOST, PORT); });
  9402. auto se = detail::scope_exit([&] {
  9403. svr.stop();
  9404. t.join();
  9405. });
  9406. svr.wait_until_ready();
  9407. bool verify_callback_called = false;
  9408. bool ip_matched_via_cn = true;
  9409. SSLClient cli(HOST, PORT);
  9410. cli.enable_server_certificate_verification(true);
  9411. cli.set_ca_cert_path(CA_CERT_FILE);
  9412. cli.set_connection_timeout(5);
  9413. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9414. verify_callback_called = true;
  9415. if (!ctx.cert) return false;
  9416. // The IP appears only in the CN, so it must NOT be accepted.
  9417. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9418. return true; // Accept for the purpose of this test
  9419. });
  9420. cli.Get("/test");
  9421. ASSERT_TRUE(verify_callback_called)
  9422. << "Verify callback should have been called";
  9423. EXPECT_FALSE(ip_matched_via_cn)
  9424. << "An IP host must not be authenticated via the certificate CN";
  9425. }
  9426. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9427. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9428. using namespace httplib::tls;
  9429. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9430. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9431. ASSERT_TRUE(svr.is_valid());
  9432. svr.Get("/test", [](const Request &, Response &res) {
  9433. res.set_content("ok", "text/plain");
  9434. });
  9435. thread t([&]() { svr.listen(HOST, PORT); });
  9436. auto se = detail::scope_exit([&] {
  9437. svr.stop();
  9438. t.join();
  9439. });
  9440. svr.wait_until_ready();
  9441. bool verify_callback_called = false;
  9442. bool san_matched = false;
  9443. bool wrong_ipv6_matched = true;
  9444. bool cn_ipv6_matched = true;
  9445. SSLClient cli(HOST, PORT);
  9446. cli.enable_server_certificate_verification(true);
  9447. cli.set_ca_cert_path(CA_CERT_FILE);
  9448. cli.set_connection_timeout(5);
  9449. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9450. verify_callback_called = true;
  9451. if (!ctx.cert) return false;
  9452. // Matches the IPv6 iPAddress SAN.
  9453. san_matched = ctx.check_hostname("2001:db8::1");
  9454. // A different IPv6 address must not match.
  9455. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9456. // "::1" lives only in the CN, so it must not be accepted.
  9457. cn_ipv6_matched = ctx.check_hostname("::1");
  9458. return true; // Accept for the purpose of this test
  9459. });
  9460. cli.Get("/test");
  9461. ASSERT_TRUE(verify_callback_called)
  9462. << "Verify callback should have been called";
  9463. EXPECT_TRUE(san_matched)
  9464. << "verify_hostname should match an IPv6 iPAddress SAN";
  9465. EXPECT_FALSE(wrong_ipv6_matched)
  9466. << "verify_hostname should not match a non-matching IPv6 address";
  9467. EXPECT_FALSE(cn_ipv6_matched)
  9468. << "An IPv6 host must not be authenticated via the certificate CN";
  9469. }
  9470. #endif
  9471. // mbedTLS-specific callback constructor test
  9472. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9473. #ifdef CPPHTTPLIB_SSL_ENABLED
  9474. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9476. ASSERT_TRUE(svr.is_valid());
  9477. // Set up a handler to verify client certificate is present
  9478. bool client_cert_verified = false;
  9479. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9480. // Verify that client certificate was provided
  9481. client_cert_verified = true;
  9482. res.set_content("success", "text/plain");
  9483. });
  9484. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9485. auto se = detail::scope_exit([&] {
  9486. svr.stop();
  9487. t.join();
  9488. ASSERT_FALSE(svr.is_running());
  9489. });
  9490. svr.wait_until_ready();
  9491. // Client with certificate
  9492. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9493. cli.enable_server_certificate_verification(false);
  9494. cli.set_connection_timeout(30);
  9495. auto res = cli.Get("/test");
  9496. ASSERT_TRUE(res);
  9497. ASSERT_EQ(StatusCode::OK_200, res->status);
  9498. ASSERT_TRUE(client_cert_verified);
  9499. EXPECT_EQ("success", res->body);
  9500. }
  9501. #endif
  9502. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9503. // backends
  9504. #ifdef CPPHTTPLIB_SSL_ENABLED
  9505. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9506. using namespace httplib::tls;
  9507. // Test that when client CA cert file is provided,
  9508. // the server properly requests and validates client certificates
  9509. // Create a server with client authentication
  9510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9511. ASSERT_TRUE(svr.is_valid());
  9512. bool handler_called = false;
  9513. svr.Get("/test", [&](const Request &req, Response &res) {
  9514. handler_called = true;
  9515. // Verify that a client certificate was provided
  9516. auto cert = req.peer_cert();
  9517. ASSERT_TRUE(static_cast<bool>(cert));
  9518. // Get the issuer name
  9519. std::string issuer_str = cert.issuer_name();
  9520. ASSERT_FALSE(issuer_str.empty());
  9521. // The client certificate should be issued by our test CA
  9522. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9523. res.set_content("authenticated", "text/plain");
  9524. });
  9525. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9526. auto se = detail::scope_exit([&] {
  9527. svr.stop();
  9528. t.join();
  9529. ASSERT_FALSE(svr.is_running());
  9530. });
  9531. svr.wait_until_ready();
  9532. // Connect with a client certificate issued by the CA
  9533. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9534. cli.enable_server_certificate_verification(false);
  9535. cli.set_connection_timeout(30);
  9536. auto res = cli.Get("/test");
  9537. ASSERT_TRUE(res);
  9538. ASSERT_EQ(StatusCode::OK_200, res->status);
  9539. ASSERT_TRUE(handler_called);
  9540. EXPECT_EQ("authenticated", res->body);
  9541. }
  9542. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9543. using namespace httplib::tls;
  9544. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9545. ASSERT_TRUE(svr.is_valid());
  9546. svr.Get("/test", [](const Request &, Response &res) {
  9547. res.set_content("ok", "text/plain");
  9548. });
  9549. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9550. auto se = detail::scope_exit([&] {
  9551. svr.stop();
  9552. t.join();
  9553. });
  9554. svr.wait_until_ready();
  9555. SSLClient cli(HOST, PORT);
  9556. cli.enable_server_certificate_verification(false);
  9557. cli.set_connection_timeout(30);
  9558. bool cert_checked = false;
  9559. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9560. if (ctx.cert) {
  9561. auto sans = ctx.sans();
  9562. // Test certificate may or may not have SANs - just verify the API
  9563. // works If SANs exist, verify the types are valid
  9564. for (const auto &san : sans) {
  9565. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9566. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9567. san.type == SanType::OTHER);
  9568. EXPECT_FALSE(san.value.empty());
  9569. }
  9570. cert_checked = true;
  9571. }
  9572. return true;
  9573. });
  9574. auto res = cli.Get("/test");
  9575. ASSERT_TRUE(res);
  9576. EXPECT_TRUE(cert_checked);
  9577. }
  9578. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9579. using namespace httplib::tls;
  9580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9581. ASSERT_TRUE(svr.is_valid());
  9582. svr.Get("/test", [](const Request &, Response &res) {
  9583. res.set_content("ok", "text/plain");
  9584. });
  9585. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9586. auto se = detail::scope_exit([&] {
  9587. svr.stop();
  9588. t.join();
  9589. });
  9590. svr.wait_until_ready();
  9591. SSLClient cli(HOST, PORT);
  9592. cli.enable_server_certificate_verification(false);
  9593. cli.set_connection_timeout(30);
  9594. bool validity_checked = false;
  9595. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9596. if (ctx.cert) {
  9597. time_t not_before = 0, not_after = 0;
  9598. bool result = ctx.validity(not_before, not_after);
  9599. EXPECT_TRUE(result);
  9600. // Verify that not_before < now < not_after for a valid cert
  9601. time_t now = time(nullptr);
  9602. EXPECT_LT(not_before, now);
  9603. EXPECT_GT(not_after, now);
  9604. validity_checked = true;
  9605. }
  9606. return true;
  9607. });
  9608. auto res = cli.Get("/test");
  9609. ASSERT_TRUE(res);
  9610. EXPECT_TRUE(validity_checked);
  9611. }
  9612. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9613. using namespace httplib::tls;
  9614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9615. ASSERT_TRUE(svr.is_valid());
  9616. svr.Get("/test", [](const Request &, Response &res) {
  9617. res.set_content("ok", "text/plain");
  9618. });
  9619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9620. auto se = detail::scope_exit([&] {
  9621. svr.stop();
  9622. t.join();
  9623. });
  9624. svr.wait_until_ready();
  9625. SSLClient cli(HOST, PORT);
  9626. cli.enable_server_certificate_verification(false);
  9627. cli.set_connection_timeout(30);
  9628. bool serial_checked = false;
  9629. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9630. if (ctx.cert) {
  9631. std::string serial = ctx.serial();
  9632. EXPECT_FALSE(serial.empty());
  9633. // Serial should be a hex string
  9634. for (char c : serial) {
  9635. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9636. (c >= 'a' && c <= 'f'));
  9637. }
  9638. serial_checked = true;
  9639. }
  9640. return true;
  9641. });
  9642. auto res = cli.Get("/test");
  9643. ASSERT_TRUE(res);
  9644. EXPECT_TRUE(serial_checked);
  9645. }
  9646. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9647. // Test 1: Valid CA file - no error should be recorded
  9648. {
  9649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9650. CLIENT_CA_CERT_FILE);
  9651. ASSERT_TRUE(svr.is_valid());
  9652. // With valid setup, last_ssl_error should be 0
  9653. EXPECT_EQ(0, svr.ssl_last_error());
  9654. }
  9655. // Test 2: Invalid CA file content
  9656. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9657. {
  9658. // Create a temporary file with completely invalid content
  9659. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9660. {
  9661. std::ofstream ofs(temp_invalid_ca);
  9662. ofs << "This is not a certificate file at all\n";
  9663. ofs << "Just plain text content\n";
  9664. }
  9665. // Create server with invalid CA file
  9666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9667. // Clean up temporary file
  9668. std::remove(temp_invalid_ca);
  9669. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9670. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9671. // Note: SSL_CTX_load_verify_locations typically fails first,
  9672. // but our error handling code path is still exercised
  9673. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9674. }
  9675. }
  9676. TEST(VerifyCallbackTest, VerifyContextFields) {
  9677. using namespace httplib::tls;
  9678. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9679. ASSERT_TRUE(svr.is_valid());
  9680. svr.Get("/test", [](const Request &, Response &res) {
  9681. res.set_content("ok", "text/plain");
  9682. });
  9683. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9684. auto se = detail::scope_exit([&] {
  9685. svr.stop();
  9686. t.join();
  9687. });
  9688. svr.wait_until_ready();
  9689. SSLClient cli(HOST, PORT);
  9690. cli.enable_server_certificate_verification(false);
  9691. cli.set_connection_timeout(30);
  9692. int callback_count = 0;
  9693. bool saw_leaf_cert = false;
  9694. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9695. if (ctx.cert) {
  9696. callback_count++;
  9697. // We should see at least one certificate (the leaf)
  9698. std::string cn = ctx.subject_cn();
  9699. if (!cn.empty()) { saw_leaf_cert = true; }
  9700. // Verify context fields are populated
  9701. EXPECT_NE(ctx.session, nullptr);
  9702. EXPECT_GE(ctx.depth, 0);
  9703. }
  9704. return true;
  9705. });
  9706. auto res = cli.Get("/test");
  9707. ASSERT_TRUE(res);
  9708. EXPECT_GT(callback_count, 0);
  9709. EXPECT_TRUE(saw_leaf_cert);
  9710. }
  9711. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9712. using httplib::tls::TlsError;
  9713. // Test that verify_error_to_string returns empty for success
  9714. std::string success_str = TlsError::verify_error_to_string(0);
  9715. EXPECT_TRUE(success_str.empty());
  9716. // Test that verify_error_to_string returns non-empty for error codes
  9717. // Using a common error code (certificate expired)
  9718. std::string error_str =
  9719. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9720. EXPECT_FALSE(error_str.empty());
  9721. }
  9722. TEST(SessionVerifierTest, CertificateAccepted) {
  9723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9724. ASSERT_TRUE(svr.is_valid());
  9725. svr.Get("/test", [](const Request &, Response &res) {
  9726. res.set_content("ok", "text/plain");
  9727. });
  9728. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9729. auto se = detail::scope_exit([&] {
  9730. svr.stop();
  9731. t.join();
  9732. });
  9733. svr.wait_until_ready();
  9734. SSLClient cli(HOST, PORT);
  9735. cli.enable_server_certificate_verification(false);
  9736. cli.set_connection_timeout(30);
  9737. bool callback_called = false;
  9738. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9739. EXPECT_NE(session, nullptr);
  9740. callback_called = true;
  9741. return SSLVerifierResponse::CertificateAccepted;
  9742. });
  9743. auto res = cli.Get("/test");
  9744. ASSERT_TRUE(res);
  9745. EXPECT_EQ(200, res->status);
  9746. EXPECT_TRUE(callback_called);
  9747. }
  9748. TEST(SessionVerifierTest, CertificateRejected) {
  9749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9750. ASSERT_TRUE(svr.is_valid());
  9751. svr.Get("/test", [](const Request &, Response &res) {
  9752. res.set_content("ok", "text/plain");
  9753. });
  9754. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9755. auto se = detail::scope_exit([&] {
  9756. svr.stop();
  9757. t.join();
  9758. });
  9759. svr.wait_until_ready();
  9760. SSLClient cli(HOST, PORT);
  9761. cli.enable_server_certificate_verification(false);
  9762. cli.set_connection_timeout(30);
  9763. bool callback_called = false;
  9764. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9765. EXPECT_NE(session, nullptr);
  9766. callback_called = true;
  9767. return SSLVerifierResponse::CertificateRejected;
  9768. });
  9769. auto res = cli.Get("/test");
  9770. EXPECT_FALSE(res);
  9771. EXPECT_TRUE(callback_called);
  9772. }
  9773. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9774. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9775. ASSERT_TRUE(svr.is_valid());
  9776. svr.Get("/test", [](const Request &, Response &res) {
  9777. res.set_content("ok", "text/plain");
  9778. });
  9779. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9780. auto se = detail::scope_exit([&] {
  9781. svr.stop();
  9782. t.join();
  9783. });
  9784. svr.wait_until_ready();
  9785. // NoDecisionMade with verification disabled should succeed (no default check)
  9786. SSLClient cli(HOST, PORT);
  9787. cli.enable_server_certificate_verification(false);
  9788. cli.set_connection_timeout(30);
  9789. bool callback_called = false;
  9790. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9791. EXPECT_NE(session, nullptr);
  9792. callback_called = true;
  9793. return SSLVerifierResponse::NoDecisionMade;
  9794. });
  9795. auto res = cli.Get("/test");
  9796. ASSERT_TRUE(res);
  9797. EXPECT_EQ(200, res->status);
  9798. EXPECT_TRUE(callback_called);
  9799. }
  9800. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9802. ASSERT_TRUE(svr.is_valid());
  9803. svr.Get("/test", [](const Request &, Response &res) {
  9804. res.set_content("ok", "text/plain");
  9805. });
  9806. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9807. auto se = detail::scope_exit([&] {
  9808. svr.stop();
  9809. t.join();
  9810. });
  9811. svr.wait_until_ready();
  9812. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9813. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9814. // so we only check that the request fails, not whether the callback was
  9815. // called.
  9816. SSLClient cli(HOST, PORT);
  9817. cli.enable_server_certificate_verification(true);
  9818. cli.set_connection_timeout(30);
  9819. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9820. EXPECT_NE(session, nullptr);
  9821. return SSLVerifierResponse::NoDecisionMade;
  9822. });
  9823. auto res = cli.Get("/test");
  9824. EXPECT_FALSE(res);
  9825. }
  9826. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9827. // Test SSL server using PemMemory constructor with client CA certificates
  9828. // Read PEM files
  9829. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9830. read_file(SERVER_CERT_FILE, server_cert_pem);
  9831. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9832. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9833. // Create SSLServer with PemMemory constructor including client CA
  9834. SSLServer::PemMemory server_pem = {
  9835. server_cert_pem.c_str(),
  9836. server_cert_pem.size(),
  9837. server_key_pem.c_str(),
  9838. server_key_pem.size(),
  9839. client_ca_pem.c_str(),
  9840. client_ca_pem.size(),
  9841. nullptr // no password for server key
  9842. };
  9843. SSLServer svr(server_pem);
  9844. ASSERT_TRUE(svr.is_valid());
  9845. // No SSL error should be recorded for valid setup
  9846. EXPECT_EQ(0, svr.ssl_last_error());
  9847. // Set up server endpoints
  9848. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9849. res.set_content("ok", "text/plain");
  9850. });
  9851. // Start server in a thread
  9852. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9853. svr.wait_until_ready();
  9854. // Connect with client certificate (using constructor with paths)
  9855. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9856. cli.enable_server_certificate_verification(false);
  9857. auto res = cli.Get("/test-pem-ca");
  9858. ASSERT_TRUE(res);
  9859. EXPECT_EQ(200, res->status);
  9860. EXPECT_EQ("ok", res->body);
  9861. svr.stop();
  9862. server_thread.join();
  9863. }
  9864. #endif
  9865. #ifdef _WIN32
  9866. TEST(CleanupTest, WSACleanup) {
  9867. int ret = WSACleanup();
  9868. ASSERT_EQ(0, ret);
  9869. }
  9870. #endif
  9871. #ifndef CPPHTTPLIB_SSL_ENABLED
  9872. TEST(NoSSLSupport, SimpleInterface) {
  9873. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9874. }
  9875. #endif
  9876. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9877. TEST(InvalidScheme, SimpleInterface) {
  9878. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9879. }
  9880. #endif
  9881. TEST(NoScheme, SimpleInterface) {
  9882. Client cli("yahoo.com:80");
  9883. ASSERT_TRUE(cli.is_valid());
  9884. }
  9885. TEST(SendAPI, SimpleInterface_Online) {
  9886. Client cli("http://yahoo.com");
  9887. Request req;
  9888. req.method = "GET";
  9889. req.path = "/";
  9890. auto res = cli.send(req);
  9891. ASSERT_TRUE(res);
  9892. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9893. }
  9894. TEST(SendAPI, WithParamsInRequest) {
  9895. Server svr;
  9896. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9897. EXPECT_TRUE(req.has_param("test"));
  9898. EXPECT_EQ("test_value", req.get_param_value("test"));
  9899. });
  9900. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9901. auto se = detail::scope_exit([&] {
  9902. svr.stop();
  9903. t.join();
  9904. ASSERT_FALSE(svr.is_running());
  9905. });
  9906. svr.wait_until_ready();
  9907. Client cli(HOST, PORT);
  9908. {
  9909. Request req;
  9910. req.method = "GET";
  9911. req.path = "/";
  9912. req.params.emplace("test", "test_value");
  9913. auto res = cli.send(req);
  9914. ASSERT_TRUE(res);
  9915. }
  9916. {
  9917. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9918. ASSERT_TRUE(res);
  9919. }
  9920. }
  9921. TEST(ClientImplMethods, GetSocketTest) {
  9922. httplib::Server svr;
  9923. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9924. res.status = StatusCode::OK_200;
  9925. });
  9926. auto port = svr.bind_to_any_port("127.0.0.1");
  9927. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9928. auto se = detail::scope_exit([&] {
  9929. svr.stop();
  9930. thread.join();
  9931. ASSERT_FALSE(svr.is_running());
  9932. });
  9933. svr.wait_until_ready();
  9934. {
  9935. httplib::Client cli("127.0.0.1", port);
  9936. cli.set_keep_alive(true);
  9937. // Use the behavior of cpp-httplib of opening the connection
  9938. // only when the first request happens. If that changes,
  9939. // this test would be obsolete.
  9940. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9941. // This also implicitly tests the server. But other tests would fail much
  9942. // earlier than this one to be considered.
  9943. auto res = cli.Get("/");
  9944. ASSERT_TRUE(res);
  9945. EXPECT_EQ(StatusCode::OK_200, res->status);
  9946. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9947. }
  9948. }
  9949. #ifdef CPPHTTPLIB_SSL_ENABLED
  9950. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9951. Client cli("http://yahoo.com");
  9952. auto res = cli.Get("/");
  9953. ASSERT_TRUE(res);
  9954. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9955. cli.set_follow_location(true);
  9956. res = cli.Get("/");
  9957. ASSERT_TRUE(res);
  9958. EXPECT_EQ(StatusCode::OK_200, res->status);
  9959. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9960. }
  9961. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9962. Client cli("https://yahoo.com");
  9963. auto res = cli.Get("/");
  9964. ASSERT_TRUE(res);
  9965. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9966. cli.set_follow_location(true);
  9967. res = cli.Get("/");
  9968. ASSERT_TRUE(res);
  9969. EXPECT_EQ(StatusCode::OK_200, res->status);
  9970. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9971. }
  9972. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9973. Client cli("https://yahoo.com");
  9974. auto res = cli.Get("/");
  9975. ASSERT_TRUE(res);
  9976. ASSERT_FALSE(!res);
  9977. ASSERT_TRUE(res);
  9978. ASSERT_FALSE(res == nullptr);
  9979. ASSERT_TRUE(res != nullptr);
  9980. EXPECT_EQ(Error::Success, res.error());
  9981. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9982. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9983. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9984. cli.set_follow_location(true);
  9985. res = cli.Get("/");
  9986. ASSERT_TRUE(res);
  9987. EXPECT_EQ(Error::Success, res.error());
  9988. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9989. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9990. EXPECT_EQ(StatusCode::OK_200, res->status);
  9991. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9992. }
  9993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9994. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9995. Client cli("https://cdnjs.cloudflare.com");
  9996. auto res =
  9997. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9998. ASSERT_TRUE(res);
  9999. EXPECT_EQ(StatusCode::OK_200, res->status);
  10000. EXPECT_EQ(287630U, res->body.size());
  10001. EXPECT_EQ("application/javascript; charset=utf-8",
  10002. res->get_header_value("Content-Type"));
  10003. }
  10004. #endif
  10005. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10006. #undef REDIR_HOST // Silence compiler warning
  10007. #define REDIR_HOST "https://httpbingo.org"
  10008. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10009. Client cli(REDIR_HOST);
  10010. cli.set_follow_location(true);
  10011. auto res =
  10012. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10013. ASSERT_TRUE(res);
  10014. EXPECT_EQ(StatusCode::OK_200, res->status);
  10015. }
  10016. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10017. Client cli(REDIR_HOST);
  10018. cli.set_follow_location(true);
  10019. Params params;
  10020. params.emplace("url", "http://example.com");
  10021. params.emplace("status_code", "302");
  10022. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10023. ASSERT_TRUE(res);
  10024. EXPECT_EQ(StatusCode::OK_200, res->status);
  10025. }
  10026. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10027. Client cli(REDIR_HOST);
  10028. cli.set_follow_location(true);
  10029. Params params;
  10030. params.emplace("url", "http://example.com");
  10031. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10032. ASSERT_TRUE(res);
  10033. EXPECT_EQ(StatusCode::OK_200, res->status);
  10034. }
  10035. TEST(HttpToHttpsRedirectTest, CertFile) {
  10036. auto ssl_port = PORT + 1;
  10037. Server svr;
  10038. ASSERT_TRUE(svr.is_valid());
  10039. svr.Get("/index", [&](const Request &, Response &res) {
  10040. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10041. "/index");
  10042. svr.stop();
  10043. });
  10044. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10045. ASSERT_TRUE(ssl_svr.is_valid());
  10046. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10047. res.set_content("test", "text/plain");
  10048. ssl_svr.stop();
  10049. });
  10050. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10051. thread t2 =
  10052. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10053. auto se = detail::scope_exit([&] {
  10054. t2.join();
  10055. t.join();
  10056. ASSERT_FALSE(svr.is_running());
  10057. });
  10058. svr.wait_until_ready();
  10059. ssl_svr.wait_until_ready();
  10060. Client cli("127.0.0.1", PORT);
  10061. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10062. cli.enable_server_certificate_verification(true);
  10063. cli.set_follow_location(true);
  10064. cli.set_connection_timeout(30);
  10065. auto res = cli.Get("/index");
  10066. ASSERT_TRUE(res);
  10067. ASSERT_EQ(StatusCode::OK_200, res->status);
  10068. }
  10069. TEST(SSLClientRedirectTest, CertFile) {
  10070. auto ssl_port = PORT + 1;
  10071. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10072. ASSERT_TRUE(ssl_svr1.is_valid());
  10073. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10074. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10075. "/index");
  10076. ssl_svr1.stop();
  10077. });
  10078. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10079. ASSERT_TRUE(ssl_svr2.is_valid());
  10080. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10081. res.set_content("test", "text/plain");
  10082. ssl_svr2.stop();
  10083. });
  10084. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10085. thread t2 =
  10086. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10087. auto se = detail::scope_exit([&] {
  10088. t2.join();
  10089. t.join();
  10090. ASSERT_FALSE(ssl_svr1.is_running());
  10091. });
  10092. ssl_svr1.wait_until_ready();
  10093. ssl_svr2.wait_until_ready();
  10094. SSLClient cli("127.0.0.1", PORT);
  10095. std::string cert;
  10096. read_file(SERVER_CERT2_FILE, cert);
  10097. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10098. cli.enable_server_certificate_verification(true);
  10099. cli.set_follow_location(true);
  10100. cli.set_connection_timeout(30);
  10101. auto res = cli.Get("/index");
  10102. ASSERT_TRUE(res);
  10103. ASSERT_EQ(StatusCode::OK_200, res->status);
  10104. }
  10105. #endif
  10106. #ifdef CPPHTTPLIB_SSL_ENABLED
  10107. // Test that set_ca_cert_store() skips system certs (consistent with
  10108. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10109. // should be trusted - system certs should NOT be loaded.
  10110. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10111. // Load a specific cert that is NOT a system CA cert
  10112. std::string cert;
  10113. read_file(SERVER_CERT2_FILE, cert);
  10114. SSLClient cli("google.com");
  10115. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10116. cli.enable_server_certificate_verification(true);
  10117. // This should FAIL because:
  10118. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10119. // 2. System certs should NOT be loaded when custom store is set
  10120. // If system certs WERE loaded, this would succeed
  10121. auto res = cli.Get("/");
  10122. ASSERT_FALSE(res);
  10123. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10124. }
  10125. // Same as above, but through the native store handle path. Regression test:
  10126. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10127. // merged system certs into the user-provided store.
  10128. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10129. std::string cert;
  10130. read_file(SERVER_CERT2_FILE, cert);
  10131. SSLClient cli("google.com");
  10132. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10133. cli.enable_server_certificate_verification(true);
  10134. auto res = cli.Get("/");
  10135. ASSERT_FALSE(res);
  10136. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10137. }
  10138. // A custom store set via the native handle must still verify a server whose
  10139. // cert it does contain.
  10140. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10141. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10142. ASSERT_TRUE(svr.is_valid());
  10143. svr.Get("/test", [&](const Request &, Response &res) {
  10144. res.set_content("test", "text/plain");
  10145. });
  10146. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10147. auto se = detail::scope_exit([&] {
  10148. svr.stop();
  10149. t.join();
  10150. ASSERT_FALSE(svr.is_running());
  10151. });
  10152. svr.wait_until_ready();
  10153. SSLClient cli("127.0.0.1", PORT);
  10154. std::string cert;
  10155. read_file(SERVER_CERT2_FILE, cert);
  10156. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10157. cli.enable_server_certificate_verification(true);
  10158. cli.set_connection_timeout(30);
  10159. auto res = cli.Get("/test");
  10160. ASSERT_TRUE(res);
  10161. ASSERT_EQ(StatusCode::OK_200, res->status);
  10162. }
  10163. // CA certs loaded through the universal Client must be transferred to the
  10164. // client created internally for following an HTTPS redirect. Regression test:
  10165. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10166. // the CA data for redirect transfer.
  10167. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10168. auto ssl_port = PORT + 1;
  10169. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10170. ASSERT_TRUE(ssl_svr1.is_valid());
  10171. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10172. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10173. "/index");
  10174. });
  10175. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10176. ASSERT_TRUE(ssl_svr2.is_valid());
  10177. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10178. res.set_content("test", "text/plain");
  10179. });
  10180. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10181. thread t2 =
  10182. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10183. auto se = detail::scope_exit([&] {
  10184. ssl_svr2.stop();
  10185. ssl_svr1.stop();
  10186. t2.join();
  10187. t.join();
  10188. ASSERT_FALSE(ssl_svr1.is_running());
  10189. });
  10190. ssl_svr1.wait_until_ready();
  10191. ssl_svr2.wait_until_ready();
  10192. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10193. std::string cert;
  10194. read_file(SERVER_CERT2_FILE, cert);
  10195. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10196. cli.enable_server_certificate_verification(true);
  10197. cli.set_follow_location(true);
  10198. cli.set_connection_timeout(30);
  10199. auto res = cli.Get("/index");
  10200. ASSERT_TRUE(res);
  10201. ASSERT_EQ(StatusCode::OK_200, res->status);
  10202. }
  10203. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10204. // so a host signed by a system CA verifies even though a custom CA is set
  10205. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10206. std::string cert;
  10207. read_file(SERVER_CERT2_FILE, cert);
  10208. SSLClient cli("google.com");
  10209. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10210. cli.enable_system_ca(true);
  10211. cli.enable_server_certificate_verification(true);
  10212. auto res = cli.Get("/");
  10213. ASSERT_TRUE(res);
  10214. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10215. }
  10216. // The custom CA remains effective when combined with the system CA
  10217. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10218. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10219. ASSERT_TRUE(svr.is_valid());
  10220. svr.Get("/test", [&](const Request &, Response &res) {
  10221. res.set_content("test", "text/plain");
  10222. });
  10223. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. t.join();
  10227. ASSERT_FALSE(svr.is_running());
  10228. });
  10229. svr.wait_until_ready();
  10230. SSLClient cli("127.0.0.1", PORT);
  10231. std::string cert;
  10232. read_file(SERVER_CERT2_FILE, cert);
  10233. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10234. cli.enable_system_ca(true);
  10235. cli.enable_server_certificate_verification(true);
  10236. cli.set_connection_timeout(30);
  10237. auto res = cli.Get("/test");
  10238. ASSERT_TRUE(res);
  10239. ASSERT_EQ(StatusCode::OK_200, res->status);
  10240. }
  10241. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10242. // skip chain verification entirely (only the certificate identity was
  10243. // checked), so a server presenting an untrusted certificate with a matching
  10244. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10245. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10246. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10247. ASSERT_TRUE(svr.is_valid());
  10248. svr.Get("/test", [&](const Request &, Response &res) {
  10249. res.set_content("test", "text/plain");
  10250. });
  10251. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10252. auto se = detail::scope_exit([&] {
  10253. svr.stop();
  10254. t.join();
  10255. ASSERT_FALSE(svr.is_running());
  10256. });
  10257. svr.wait_until_ready();
  10258. SSLClient cli("127.0.0.1", PORT);
  10259. std::string cert;
  10260. // A trusted CA that did not sign the server certificate. The server cert
  10261. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10262. // this connection.
  10263. read_file(CLIENT_CA_CERT_FILE, cert);
  10264. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10265. cli.enable_server_certificate_verification(true);
  10266. cli.set_connection_timeout(30);
  10267. auto res = cli.Get("/test");
  10268. ASSERT_FALSE(res);
  10269. }
  10270. // enable_system_ca(false) prevents system CA loading entirely
  10271. TEST(SSLClientTest, DisableSystemCa_Online) {
  10272. SSLClient cli("google.com");
  10273. cli.enable_system_ca(false);
  10274. cli.enable_server_certificate_verification(true);
  10275. auto res = cli.Get("/");
  10276. ASSERT_FALSE(res);
  10277. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10278. // itself when the CA chain is empty
  10279. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10280. res.error() == Error::SSLConnection);
  10281. }
  10282. // The universal Client forwards enable_system_ca()
  10283. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10284. std::string cert;
  10285. read_file(SERVER_CERT2_FILE, cert);
  10286. Client cli("https://google.com");
  10287. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10288. cli.enable_system_ca(true);
  10289. cli.enable_server_certificate_verification(true);
  10290. auto res = cli.Get("/");
  10291. ASSERT_TRUE(res);
  10292. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10293. }
  10294. // The system CA policy must carry over to the client created internally for
  10295. // following a cross-host HTTPS redirect
  10296. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10297. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10298. ASSERT_TRUE(svr.is_valid());
  10299. svr.Get("/index", [&](const Request &, Response &res) {
  10300. res.set_redirect("https://www.google.com/");
  10301. });
  10302. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10303. auto se = detail::scope_exit([&] {
  10304. svr.stop();
  10305. t.join();
  10306. ASSERT_FALSE(svr.is_running());
  10307. });
  10308. svr.wait_until_ready();
  10309. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10310. std::string cert;
  10311. read_file(SERVER_CERT2_FILE, cert);
  10312. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10313. cli.enable_system_ca(true);
  10314. cli.enable_server_certificate_verification(true);
  10315. cli.set_follow_location(true);
  10316. cli.set_connection_timeout(30);
  10317. // Receiving any response proves the redirect client completed the TLS
  10318. // handshake with a system-CA-signed host
  10319. auto res = cli.Get("/index");
  10320. ASSERT_TRUE(res);
  10321. }
  10322. TEST(MultipartFormDataTest, LargeData) {
  10323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10324. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10325. const ContentReader &content_reader) {
  10326. if (req.is_multipart_form_data()) {
  10327. std::vector<FormData> items;
  10328. content_reader(
  10329. [&](const FormData &file) {
  10330. items.push_back(file);
  10331. return true;
  10332. },
  10333. [&](const char *data, size_t data_length) {
  10334. items.back().content.append(data, data_length);
  10335. return true;
  10336. });
  10337. EXPECT_TRUE(std::string(items[0].name) == "document");
  10338. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10339. EXPECT_TRUE(items[0].filename == "2MB_data");
  10340. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10341. EXPECT_TRUE(items[1].name == "hello");
  10342. EXPECT_TRUE(items[1].content == "world");
  10343. EXPECT_TRUE(items[1].filename == "");
  10344. EXPECT_TRUE(items[1].content_type == "");
  10345. } else {
  10346. std::string body;
  10347. content_reader([&](const char *data, size_t data_length) {
  10348. body.append(data, data_length);
  10349. return true;
  10350. });
  10351. }
  10352. });
  10353. auto port = svr.bind_to_any_port(HOST);
  10354. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10355. auto se = detail::scope_exit([&] {
  10356. svr.stop();
  10357. t.join();
  10358. ASSERT_FALSE(svr.is_running());
  10359. });
  10360. svr.wait_until_ready();
  10361. {
  10362. std::string data(1024 * 1024 * 2, '.');
  10363. std::stringstream buffer;
  10364. buffer << data;
  10365. SSLClient cli(HOST, port);
  10366. cli.enable_server_certificate_verification(false);
  10367. UploadFormDataItems items{
  10368. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10369. {"hello", "world", "", ""},
  10370. };
  10371. auto res = cli.Post("/post", items);
  10372. ASSERT_TRUE(res);
  10373. ASSERT_EQ(StatusCode::OK_200, res->status);
  10374. }
  10375. }
  10376. TEST(MultipartFormDataTest, DataProviderItems) {
  10377. std::random_device seed_gen;
  10378. std::mt19937 random(seed_gen());
  10379. std::string rand1;
  10380. rand1.resize(1000);
  10381. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10382. std::string rand2;
  10383. rand2.resize(3000);
  10384. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10386. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10387. const ContentReader &content_reader) {
  10388. ASSERT_FALSE(req.is_multipart_form_data());
  10389. std::string body;
  10390. content_reader([&](const char *data, size_t data_length) {
  10391. body.append(data, data_length);
  10392. return true;
  10393. });
  10394. EXPECT_EQ(body, "");
  10395. });
  10396. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10397. const ContentReader &content_reader) {
  10398. ASSERT_TRUE(req.is_multipart_form_data());
  10399. std::vector<FormData> items;
  10400. content_reader(
  10401. [&](const FormData &file) {
  10402. items.push_back(file);
  10403. return true;
  10404. },
  10405. [&](const char *data, size_t data_length) {
  10406. items.back().content.append(data, data_length);
  10407. return true;
  10408. });
  10409. ASSERT_TRUE(items.size() == 2);
  10410. EXPECT_EQ(std::string(items[0].name), "name1");
  10411. EXPECT_EQ(items[0].content, "Testing123");
  10412. EXPECT_EQ(items[0].filename, "filename1");
  10413. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10414. EXPECT_EQ(items[1].name, "name2");
  10415. EXPECT_EQ(items[1].content, "Testing456");
  10416. EXPECT_EQ(items[1].filename, "");
  10417. EXPECT_EQ(items[1].content_type, "");
  10418. });
  10419. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10420. const ContentReader &content_reader) {
  10421. ASSERT_TRUE(req.is_multipart_form_data());
  10422. std::vector<FormData> items;
  10423. content_reader(
  10424. [&](const FormData &file) {
  10425. items.push_back(file);
  10426. return true;
  10427. },
  10428. [&](const char *data, size_t data_length) {
  10429. items.back().content.append(data, data_length);
  10430. return true;
  10431. });
  10432. ASSERT_TRUE(items.size() == 2);
  10433. EXPECT_EQ(items[0].name, "name3");
  10434. EXPECT_EQ(items[0].content, rand1);
  10435. EXPECT_EQ(items[0].filename, "filename3");
  10436. EXPECT_EQ(items[0].content_type, "");
  10437. EXPECT_EQ(items[1].name, "name4");
  10438. EXPECT_EQ(items[1].content, rand2);
  10439. EXPECT_EQ(items[1].filename, "filename4");
  10440. EXPECT_EQ(items[1].content_type, "");
  10441. });
  10442. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10443. const ContentReader &content_reader) {
  10444. ASSERT_TRUE(req.is_multipart_form_data());
  10445. std::vector<FormData> items;
  10446. content_reader(
  10447. [&](const FormData &file) {
  10448. items.push_back(file);
  10449. return true;
  10450. },
  10451. [&](const char *data, size_t data_length) {
  10452. items.back().content.append(data, data_length);
  10453. return true;
  10454. });
  10455. ASSERT_TRUE(items.size() == 4);
  10456. EXPECT_EQ(std::string(items[0].name), "name1");
  10457. EXPECT_EQ(items[0].content, "Testing123");
  10458. EXPECT_EQ(items[0].filename, "filename1");
  10459. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10460. EXPECT_EQ(items[1].name, "name2");
  10461. EXPECT_EQ(items[1].content, "Testing456");
  10462. EXPECT_EQ(items[1].filename, "");
  10463. EXPECT_EQ(items[1].content_type, "");
  10464. EXPECT_EQ(items[2].name, "name3");
  10465. EXPECT_EQ(items[2].content, rand1);
  10466. EXPECT_EQ(items[2].filename, "filename3");
  10467. EXPECT_EQ(items[2].content_type, "");
  10468. EXPECT_EQ(items[3].name, "name4");
  10469. EXPECT_EQ(items[3].content, rand2);
  10470. EXPECT_EQ(items[3].filename, "filename4");
  10471. EXPECT_EQ(items[3].content_type, "");
  10472. });
  10473. auto port = svr.bind_to_any_port("localhost");
  10474. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10475. auto se = detail::scope_exit([&] {
  10476. svr.stop();
  10477. t.join();
  10478. ASSERT_FALSE(svr.is_running());
  10479. });
  10480. svr.wait_until_ready();
  10481. {
  10482. SSLClient cli("localhost", port);
  10483. cli.enable_server_certificate_verification(false);
  10484. UploadFormDataItems items{
  10485. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10486. {"name2", "Testing456", "", ""}, // not a file
  10487. };
  10488. {
  10489. auto res = cli.Post("/post-none", {}, {}, {});
  10490. ASSERT_TRUE(res);
  10491. ASSERT_EQ(StatusCode::OK_200, res->status);
  10492. }
  10493. FormDataProviderItems providers;
  10494. {
  10495. auto res =
  10496. cli.Post("/post-items", {}, items, providers); // empty providers
  10497. ASSERT_TRUE(res);
  10498. ASSERT_EQ(StatusCode::OK_200, res->status);
  10499. }
  10500. providers.push_back({"name3",
  10501. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10502. // test the offset is given correctly at each step
  10503. if (!offset)
  10504. sink.os.write(rand1.data(), 30);
  10505. else if (offset == 30)
  10506. sink.os.write(rand1.data() + 30, 300);
  10507. else if (offset == 330)
  10508. sink.os.write(rand1.data() + 330, 670);
  10509. else if (offset == rand1.size())
  10510. sink.done();
  10511. return true;
  10512. },
  10513. "filename3",
  10514. {}});
  10515. providers.push_back({"name4",
  10516. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10517. // test the offset is given correctly at each step
  10518. if (!offset)
  10519. sink.os.write(rand2.data(), 2000);
  10520. else if (offset == 2000)
  10521. sink.os.write(rand2.data() + 2000, 1);
  10522. else if (offset == 2001)
  10523. sink.os.write(rand2.data() + 2001, 999);
  10524. else if (offset == rand2.size())
  10525. sink.done();
  10526. return true;
  10527. },
  10528. "filename4",
  10529. {}});
  10530. {
  10531. auto res = cli.Post("/post-providers", {}, {}, providers);
  10532. ASSERT_TRUE(res);
  10533. ASSERT_EQ(StatusCode::OK_200, res->status);
  10534. }
  10535. {
  10536. auto res = cli.Post("/post-both", {}, items, providers);
  10537. ASSERT_TRUE(res);
  10538. ASSERT_EQ(StatusCode::OK_200, res->status);
  10539. }
  10540. }
  10541. }
  10542. TEST(MultipartFormDataTest, BadHeader) {
  10543. Server svr;
  10544. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10545. res.set_content("ok", "text/plain");
  10546. });
  10547. thread t = thread([&] { svr.listen(HOST, PORT); });
  10548. auto se = detail::scope_exit([&] {
  10549. svr.stop();
  10550. t.join();
  10551. ASSERT_FALSE(svr.is_running());
  10552. });
  10553. svr.wait_until_ready();
  10554. const std::string body =
  10555. "This is the preamble. It is to be ignored, though it\r\n"
  10556. "is a handy place for composition agents to include an\r\n"
  10557. "explanatory note to non-MIME conformant readers.\r\n"
  10558. "\r\n"
  10559. "\r\n"
  10560. "--simple boundary\r\n"
  10561. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10562. ": BAD...\r\n"
  10563. "\r\n"
  10564. "value1\r\n"
  10565. "--simple boundary\r\n"
  10566. "Content-Disposition: form-data; name=\"field2\"; "
  10567. "filename=\"example.txt\"\r\n"
  10568. "\r\n"
  10569. "value2\r\n"
  10570. "--simple boundary--\r\n"
  10571. "This is the epilogue. It is also to be ignored.\r\n";
  10572. std::string content_type =
  10573. R"(multipart/form-data; boundary="simple boundary")";
  10574. Client cli(HOST, PORT);
  10575. auto res = cli.Post("/post", body, content_type.c_str());
  10576. ASSERT_TRUE(res);
  10577. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10578. }
  10579. TEST(MultipartFormDataTest, WithPreamble) {
  10580. Server svr;
  10581. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10582. res.set_content("ok", "text/plain");
  10583. });
  10584. thread t = thread([&] { svr.listen(HOST, PORT); });
  10585. auto se = detail::scope_exit([&] {
  10586. svr.stop();
  10587. t.join();
  10588. ASSERT_FALSE(svr.is_running());
  10589. });
  10590. svr.wait_until_ready();
  10591. const std::string body =
  10592. "This is the preamble. It is to be ignored, though it\r\n"
  10593. "is a handy place for composition agents to include an\r\n"
  10594. "explanatory note to non-MIME conformant readers.\r\n"
  10595. "\r\n"
  10596. "\r\n"
  10597. "--simple boundary\r\n"
  10598. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10599. "\r\n"
  10600. "value1\r\n"
  10601. "--simple boundary\r\n"
  10602. "Content-Disposition: form-data; name=\"field2\"; "
  10603. "filename=\"example.txt\"\r\n"
  10604. "\r\n"
  10605. "value2\r\n"
  10606. "--simple boundary--\r\n"
  10607. "This is the epilogue. It is also to be ignored.\r\n";
  10608. std::string content_type =
  10609. R"(multipart/form-data; boundary="simple boundary")";
  10610. Client cli(HOST, PORT);
  10611. auto res = cli.Post("/post", body, content_type.c_str());
  10612. ASSERT_TRUE(res);
  10613. EXPECT_EQ(StatusCode::OK_200, res->status);
  10614. }
  10615. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10617. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10618. const ContentReader &content_reader) {
  10619. if (req.is_multipart_form_data()) {
  10620. std::vector<FormData> items;
  10621. content_reader(
  10622. [&](const FormData &file) {
  10623. items.push_back(file);
  10624. return true;
  10625. },
  10626. [&](const char *data, size_t data_length) {
  10627. items.back().content.append(data, data_length);
  10628. return true;
  10629. });
  10630. EXPECT_TRUE(std::string(items[0].name) == "document");
  10631. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10632. EXPECT_TRUE(items[0].filename == "2MB_data");
  10633. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10634. EXPECT_TRUE(items[1].name == "hello");
  10635. EXPECT_TRUE(items[1].content == "world");
  10636. EXPECT_TRUE(items[1].filename == "");
  10637. EXPECT_TRUE(items[1].content_type == "");
  10638. } else {
  10639. std::string body;
  10640. content_reader([&](const char *data, size_t data_length) {
  10641. body.append(data, data_length);
  10642. return true;
  10643. });
  10644. }
  10645. });
  10646. auto port = svr.bind_to_any_port("localhost");
  10647. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. t.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.wait_until_ready();
  10654. {
  10655. std::string data(1024 * 1024 * 2, '.');
  10656. std::stringstream buffer;
  10657. buffer << data;
  10658. SSLClient cli("localhost", port);
  10659. cli.enable_server_certificate_verification(false);
  10660. UploadFormDataItems items{
  10661. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10662. {"hello", "world", "", ""},
  10663. };
  10664. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10665. ASSERT_TRUE(res);
  10666. ASSERT_EQ(StatusCode::OK_200, res->status);
  10667. }
  10668. }
  10669. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10670. std::string data(1024 * 1024 * 2, '&');
  10671. std::stringstream buffer;
  10672. buffer << data;
  10673. Client cli("https://localhost:8080");
  10674. UploadFormDataItems items{
  10675. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10676. {"hello", "world", "", ""},
  10677. };
  10678. for (const char &c : " \t\r\n") {
  10679. auto res =
  10680. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10681. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10682. ASSERT_FALSE(res);
  10683. }
  10684. }
  10685. TEST(MultipartFormDataTest, PutFormData) {
  10686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10687. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10688. const ContentReader &content_reader) {
  10689. if (req.is_multipart_form_data()) {
  10690. std::vector<FormData> items;
  10691. content_reader(
  10692. [&](const FormData &file) {
  10693. items.push_back(file);
  10694. return true;
  10695. },
  10696. [&](const char *data, size_t data_length) {
  10697. items.back().content.append(data, data_length);
  10698. return true;
  10699. });
  10700. EXPECT_TRUE(std::string(items[0].name) == "document");
  10701. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10702. EXPECT_TRUE(items[0].filename == "2MB_data");
  10703. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10704. EXPECT_TRUE(items[1].name == "hello");
  10705. EXPECT_TRUE(items[1].content == "world");
  10706. EXPECT_TRUE(items[1].filename == "");
  10707. EXPECT_TRUE(items[1].content_type == "");
  10708. } else {
  10709. std::string body;
  10710. content_reader([&](const char *data, size_t data_length) {
  10711. body.append(data, data_length);
  10712. return true;
  10713. });
  10714. }
  10715. });
  10716. auto port = svr.bind_to_any_port("localhost");
  10717. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10718. auto se = detail::scope_exit([&] {
  10719. svr.stop();
  10720. t.join();
  10721. ASSERT_FALSE(svr.is_running());
  10722. });
  10723. svr.wait_until_ready();
  10724. {
  10725. std::string data(1024 * 1024 * 2, '&');
  10726. std::stringstream buffer;
  10727. buffer << data;
  10728. SSLClient cli("localhost", port);
  10729. cli.enable_server_certificate_verification(false);
  10730. UploadFormDataItems items{
  10731. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10732. {"hello", "world", "", ""},
  10733. };
  10734. auto res = cli.Put("/put", items);
  10735. ASSERT_TRUE(res);
  10736. ASSERT_EQ(StatusCode::OK_200, res->status);
  10737. }
  10738. }
  10739. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10741. svr.Put("/put_customboundary",
  10742. [&](const Request &req, const Response & /*res*/,
  10743. const ContentReader &content_reader) {
  10744. if (req.is_multipart_form_data()) {
  10745. std::vector<FormData> items;
  10746. content_reader(
  10747. [&](const FormData &file) {
  10748. items.push_back(file);
  10749. return true;
  10750. },
  10751. [&](const char *data, size_t data_length) {
  10752. items.back().content.append(data, data_length);
  10753. return true;
  10754. });
  10755. EXPECT_TRUE(std::string(items[0].name) == "document");
  10756. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10757. EXPECT_TRUE(items[0].filename == "2MB_data");
  10758. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10759. EXPECT_TRUE(items[1].name == "hello");
  10760. EXPECT_TRUE(items[1].content == "world");
  10761. EXPECT_TRUE(items[1].filename == "");
  10762. EXPECT_TRUE(items[1].content_type == "");
  10763. } else {
  10764. std::string body;
  10765. content_reader([&](const char *data, size_t data_length) {
  10766. body.append(data, data_length);
  10767. return true;
  10768. });
  10769. }
  10770. });
  10771. auto port = svr.bind_to_any_port("localhost");
  10772. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10773. auto se = detail::scope_exit([&] {
  10774. svr.stop();
  10775. t.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. svr.wait_until_ready();
  10779. {
  10780. std::string data(1024 * 1024 * 2, '&');
  10781. std::stringstream buffer;
  10782. buffer << data;
  10783. SSLClient cli("localhost", port);
  10784. cli.enable_server_certificate_verification(false);
  10785. UploadFormDataItems items{
  10786. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10787. {"hello", "world", "", ""},
  10788. };
  10789. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10790. ASSERT_TRUE(res);
  10791. ASSERT_EQ(StatusCode::OK_200, res->status);
  10792. }
  10793. }
  10794. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10795. std::string data(1024 * 1024 * 2, '&');
  10796. std::stringstream buffer;
  10797. buffer << data;
  10798. Client cli("https://localhost:8080");
  10799. cli.enable_server_certificate_verification(false);
  10800. UploadFormDataItems items{
  10801. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10802. {"hello", "world", "", ""},
  10803. };
  10804. for (const char &c : " \t\r\n") {
  10805. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10806. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10807. ASSERT_FALSE(res);
  10808. }
  10809. }
  10810. TEST(MultipartFormDataTest, AlternateFilename) {
  10811. auto handled = false;
  10812. Server svr;
  10813. svr.Post("/test", [&](const Request &req, Response &res) {
  10814. ASSERT_EQ(2u, req.form.files.size());
  10815. ASSERT_EQ(1u, req.form.fields.size());
  10816. // Test files
  10817. const auto &file1 = req.form.get_file("file1");
  10818. ASSERT_EQ("file1", file1.name);
  10819. ASSERT_EQ("A.txt", file1.filename);
  10820. ASSERT_EQ("text/plain", file1.content_type);
  10821. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10822. const auto &file2 = req.form.get_file("file2");
  10823. ASSERT_EQ("file2", file2.name);
  10824. ASSERT_EQ("a.html", file2.filename);
  10825. ASSERT_EQ("text/html", file2.content_type);
  10826. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10827. file2.content);
  10828. // Test text field
  10829. const auto &text = req.form.get_field("text");
  10830. ASSERT_EQ("text default", text);
  10831. res.set_content("ok", "text/plain");
  10832. handled = true;
  10833. });
  10834. thread t = thread([&] { svr.listen(HOST, PORT); });
  10835. auto se = detail::scope_exit([&] {
  10836. svr.stop();
  10837. t.join();
  10838. ASSERT_FALSE(svr.is_running());
  10839. ASSERT_TRUE(handled);
  10840. });
  10841. svr.wait_until_ready();
  10842. auto req = "POST /test HTTP/1.1\r\n"
  10843. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10844. "Content-Length: 399\r\n"
  10845. "\r\n"
  10846. "----------\r\n"
  10847. "Content-Disposition: form-data; name=\"text\"\r\n"
  10848. "\r\n"
  10849. "text default\r\n"
  10850. "----------\r\n"
  10851. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10852. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10853. "Content-Type: text/plain\r\n"
  10854. "\r\n"
  10855. "Content of a.txt.\r\n"
  10856. "\r\n"
  10857. "----------\r\n"
  10858. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10859. "\"a.html\"\r\n"
  10860. "Content-Type: text/html\r\n"
  10861. "\r\n"
  10862. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10863. "\r\n"
  10864. "------------\r\n";
  10865. ASSERT_TRUE(send_request(1, req));
  10866. }
  10867. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10868. auto handled = false;
  10869. Server svr;
  10870. svr.Post("/test", [&](const Request &req, Response &res) {
  10871. // Case-insensitive "utf-8''" prefix with a long value
  10872. const auto &file = req.form.get_file("file1");
  10873. ASSERT_EQ("file1", file.name);
  10874. // 8000 chars exercises both the Content-Disposition parser and the
  10875. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10876. // Prior to the fix, std::regex_match on this header would cause O(N)
  10877. // stack recursion in libstdc++, leading to SIGSEGV.
  10878. std::string expected_filename(8000, 'A');
  10879. ASSERT_EQ(expected_filename, file.filename);
  10880. res.set_content("ok", "text/plain");
  10881. handled = true;
  10882. });
  10883. thread t = thread([&] { svr.listen(HOST, PORT); });
  10884. auto se = detail::scope_exit([&] {
  10885. svr.stop();
  10886. t.join();
  10887. ASSERT_FALSE(svr.is_running());
  10888. ASSERT_TRUE(handled);
  10889. });
  10890. svr.wait_until_ready();
  10891. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10892. // Regression test for GHSA-qq6v-r583-3h69
  10893. std::string long_filename(8000, 'A');
  10894. std::string body = "----------\r\n"
  10895. "Content-Disposition: form-data; name=\"file1\"; "
  10896. "filename*=\"Utf-8''" +
  10897. long_filename +
  10898. "\"\r\n"
  10899. "\r\n"
  10900. "hello\r\n"
  10901. "------------\r\n";
  10902. auto req = "POST /test HTTP/1.1\r\n"
  10903. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10904. "Content-Length: " +
  10905. std::to_string(body.size()) + "\r\n\r\n" + body;
  10906. ASSERT_TRUE(send_request(1, req));
  10907. }
  10908. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10909. auto handled = false;
  10910. Server svr;
  10911. svr.Post("/test", [&](const Request &req, Response &) {
  10912. ASSERT_EQ(2u, req.form.fields.size());
  10913. const auto &text1 = req.form.get_field("text1");
  10914. ASSERT_EQ("text1", text1);
  10915. const auto &text2 = req.form.get_field("text2");
  10916. ASSERT_EQ("text2", text2);
  10917. handled = true;
  10918. });
  10919. thread t = thread([&] { svr.listen(HOST, PORT); });
  10920. auto se = detail::scope_exit([&] {
  10921. svr.stop();
  10922. t.join();
  10923. ASSERT_FALSE(svr.is_running());
  10924. ASSERT_TRUE(handled);
  10925. });
  10926. svr.wait_until_ready();
  10927. auto req = "POST /test HTTP/1.1\r\n"
  10928. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10929. "Content-Length: 146\r\n"
  10930. "\r\n----------\r\n"
  10931. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10932. "\r\n"
  10933. "text1"
  10934. "\r\n----------\r\n"
  10935. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10936. "\r\n"
  10937. "text2"
  10938. "\r\n------------";
  10939. std::string response;
  10940. ASSERT_TRUE(send_request(1, req, &response));
  10941. ASSERT_EQ("200", response.substr(9, 3));
  10942. }
  10943. TEST(MultipartFormDataTest, ContentLength) {
  10944. auto handled = false;
  10945. Server svr;
  10946. svr.Post("/test", [&](const Request &req, Response &) {
  10947. ASSERT_EQ(2u, req.form.fields.size());
  10948. const auto &text1 = req.form.get_field("text1");
  10949. ASSERT_EQ("text1", text1);
  10950. const auto &text2 = req.form.get_field("text2");
  10951. ASSERT_EQ("text2", text2);
  10952. handled = true;
  10953. });
  10954. thread t = thread([&] { svr.listen(HOST, PORT); });
  10955. auto se = detail::scope_exit([&] {
  10956. svr.stop();
  10957. t.join();
  10958. ASSERT_FALSE(svr.is_running());
  10959. ASSERT_TRUE(handled);
  10960. });
  10961. svr.wait_until_ready();
  10962. auto req = "POST /test HTTP/1.1\r\n"
  10963. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10964. "Content-Length: 167\r\n"
  10965. "\r\n----------\r\n"
  10966. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10967. "Content-Length: 5\r\n"
  10968. "\r\n"
  10969. "text1"
  10970. "\r\n----------\r\n"
  10971. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10972. "\r\n"
  10973. "text2"
  10974. "\r\n------------\r\n";
  10975. std::string response;
  10976. ASSERT_TRUE(send_request(1, req, &response));
  10977. ASSERT_EQ("200", response.substr(9, 3));
  10978. }
  10979. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10980. auto handled = false;
  10981. Server svr;
  10982. svr.Post("/test", [&](const Request &req, Response &) {
  10983. ASSERT_EQ(2u, req.form.fields.size());
  10984. const auto &text1 = req.form.get_field("text1");
  10985. ASSERT_EQ("text1", text1);
  10986. // TODO: Add header access for text fields if needed
  10987. const auto &text2 = req.form.get_field("text2");
  10988. ASSERT_EQ("text2", text2);
  10989. // TODO: Header access for text fields needs to be implemented
  10990. // auto &headers = it->second.headers;
  10991. // ASSERT_EQ(3U, headers.size());
  10992. // auto custom_header = headers.find("x-whatever");
  10993. // ASSERT_TRUE(custom_header != headers.end());
  10994. // ASSERT_NE("customvalue", custom_header->second);
  10995. // ASSERT_EQ("CustomValue", custom_header->second);
  10996. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10997. handled = true;
  10998. });
  10999. thread t = thread([&] { svr.listen(HOST, PORT); });
  11000. auto se = detail::scope_exit([&] {
  11001. svr.stop();
  11002. t.join();
  11003. ASSERT_FALSE(svr.is_running());
  11004. ASSERT_TRUE(handled);
  11005. });
  11006. svr.wait_until_ready();
  11007. auto req = "POST /test HTTP/1.1\r\n"
  11008. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11009. "Content-Length: 232\r\n"
  11010. "\r\n----------\r\n"
  11011. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11012. "Content-Length: 5\r\n"
  11013. "X-Test: 1\r\n"
  11014. "\r\n"
  11015. "text1"
  11016. "\r\n----------\r\n"
  11017. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11018. "Content-Type: text/plain\r\n"
  11019. "X-Whatever: CustomValue\r\n"
  11020. "\r\n"
  11021. "text2"
  11022. "\r\n------------\r\n"
  11023. "That should be disregarded. Not even read";
  11024. std::string response;
  11025. ASSERT_TRUE(send_request(1, req, &response));
  11026. ASSERT_EQ("200", response.substr(9, 3));
  11027. }
  11028. TEST(MultipartFormDataTest, LargeHeader) {
  11029. auto handled = false;
  11030. Server svr;
  11031. svr.Post("/test", [&](const Request &req, Response &) {
  11032. ASSERT_EQ(1u, req.form.fields.size());
  11033. const auto &text = req.form.get_field("name1");
  11034. ASSERT_EQ("text1", text);
  11035. handled = true;
  11036. });
  11037. thread t = thread([&] { svr.listen(HOST, PORT); });
  11038. auto se = detail::scope_exit([&] {
  11039. svr.stop();
  11040. t.join();
  11041. ASSERT_FALSE(svr.is_running());
  11042. ASSERT_TRUE(handled);
  11043. });
  11044. svr.wait_until_ready();
  11045. auto boundary = std::string("cpp-httplib-multipart-data");
  11046. std::string content = "--" + boundary +
  11047. "\r\n"
  11048. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11049. "\r\n"
  11050. "text1\r\n"
  11051. "--" +
  11052. boundary + "--\r\n";
  11053. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11054. "Content-Type: multipart/form-data;boundary=" +
  11055. boundary +
  11056. "\r\n"
  11057. "Content-Length: " +
  11058. std::to_string(content.size()) +
  11059. "\r\n"
  11060. "Dummy-Header: ";
  11061. std::string header_suffix = "\r\n"
  11062. "\r\n";
  11063. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11064. size_t header_dummy_size =
  11065. read_buff_size -
  11066. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11067. auto header_dummy = std::string(header_dummy_size, '@');
  11068. auto req = header_prefix + header_dummy + header_suffix + content;
  11069. std::string response;
  11070. ASSERT_TRUE(send_request(1, req, &response));
  11071. ASSERT_EQ("200", response.substr(9, 3));
  11072. }
  11073. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11074. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11075. // (not chunked Transfer-Encoding) after the streaming refactor.
  11076. auto handled = false;
  11077. Server svr;
  11078. svr.Post("/upload", [&](const Request &req, Response &res) {
  11079. auto cl_it = req.headers.find("Content-Length");
  11080. EXPECT_TRUE(cl_it != req.headers.end());
  11081. auto te_it = req.headers.find("Transfer-Encoding");
  11082. EXPECT_TRUE(te_it == req.headers.end());
  11083. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11084. res.set_content("ok", "text/plain");
  11085. handled = true;
  11086. });
  11087. auto port = svr.bind_to_any_port(HOST);
  11088. auto t = thread([&] { svr.listen_after_bind(); });
  11089. auto se = detail::scope_exit([&] {
  11090. svr.stop();
  11091. t.join();
  11092. ASSERT_FALSE(svr.is_running());
  11093. ASSERT_TRUE(handled);
  11094. });
  11095. svr.wait_until_ready();
  11096. UploadFormDataItems items = {
  11097. {"field1", "hello", "", "text/plain"},
  11098. {"file1", "world", "test.txt", "application/octet-stream"},
  11099. };
  11100. Client cli(HOST, port);
  11101. auto res = cli.Post("/upload", {}, items);
  11102. ASSERT_TRUE(res);
  11103. EXPECT_EQ(StatusCode::OK_200, res->status);
  11104. }
  11105. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11106. // Verify that make_multipart_content_provider coalesces many small segments
  11107. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11108. constexpr size_t kItemCount = 1000;
  11109. UploadFormDataItems items;
  11110. items.reserve(kItemCount);
  11111. for (size_t i = 0; i < kItemCount; i++) {
  11112. items.push_back(
  11113. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11114. }
  11115. const std::string boundary = "----test-boundary";
  11116. auto content_length = detail::get_multipart_content_length(items, boundary);
  11117. auto provider = detail::make_multipart_content_provider(items, boundary);
  11118. // Drive the provider the same way write_content_with_progress does
  11119. size_t write_count = 0;
  11120. size_t total_bytes = 0;
  11121. DataSink sink;
  11122. size_t offset = 0;
  11123. sink.write = [&](const char *d, size_t l) -> bool {
  11124. (void)d;
  11125. write_count++;
  11126. total_bytes += l;
  11127. offset += l;
  11128. return true;
  11129. };
  11130. sink.is_writable = []() -> bool { return true; };
  11131. while (offset < content_length) {
  11132. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11133. }
  11134. EXPECT_EQ(content_length, total_bytes);
  11135. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11136. // With buffering into 64KB blocks, write_count should be much smaller.
  11137. auto segment_count = 3 * kItemCount + 1;
  11138. EXPECT_LT(write_count, segment_count / 10);
  11139. }
  11140. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11141. // Integration test: send many UploadFormDataItems and verify the server
  11142. // receives all of them correctly (#2410).
  11143. constexpr size_t kItemCount = 500;
  11144. auto handled = false;
  11145. Server svr;
  11146. svr.Post("/upload", [&](const Request &req, Response &res) {
  11147. EXPECT_EQ(kItemCount, req.form.fields.size());
  11148. for (size_t i = 0; i < kItemCount; i++) {
  11149. auto key = "field" + std::to_string(i);
  11150. auto val = "value" + std::to_string(i);
  11151. auto it = req.form.fields.find(key);
  11152. if (it != req.form.fields.end()) {
  11153. EXPECT_EQ(val, it->second.content);
  11154. } else {
  11155. ADD_FAILURE() << "Missing field: " << key;
  11156. }
  11157. }
  11158. res.set_content("ok", "text/plain");
  11159. handled = true;
  11160. });
  11161. auto port = svr.bind_to_any_port(HOST);
  11162. auto t = thread([&] { svr.listen_after_bind(); });
  11163. auto se = detail::scope_exit([&] {
  11164. svr.stop();
  11165. t.join();
  11166. ASSERT_FALSE(svr.is_running());
  11167. ASSERT_TRUE(handled);
  11168. });
  11169. svr.wait_until_ready();
  11170. UploadFormDataItems items;
  11171. items.reserve(kItemCount);
  11172. for (size_t i = 0; i < kItemCount; i++) {
  11173. items.push_back(
  11174. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11175. }
  11176. Client cli(HOST, port);
  11177. auto res = cli.Post("/upload", items);
  11178. ASSERT_TRUE(res);
  11179. EXPECT_EQ(StatusCode::OK_200, res->status);
  11180. }
  11181. TEST(MultipartFormDataTest, MakeFileProvider) {
  11182. // Verify make_file_provider sends a file's contents correctly.
  11183. const std::string file_content(4096, 'Z');
  11184. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11185. {
  11186. std::ofstream ofs(tmp_path, std::ios::binary);
  11187. ofs.write(file_content.data(),
  11188. static_cast<std::streamsize>(file_content.size()));
  11189. }
  11190. auto handled = false;
  11191. Server svr;
  11192. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11193. const ContentReader &content_reader) {
  11194. ASSERT_TRUE(req.is_multipart_form_data());
  11195. std::vector<FormData> items;
  11196. content_reader(
  11197. [&](const FormData &file) {
  11198. items.push_back(file);
  11199. return true;
  11200. },
  11201. [&](const char *data, size_t data_length) {
  11202. items.back().content.append(data, data_length);
  11203. return true;
  11204. });
  11205. ASSERT_EQ(1u, items.size());
  11206. EXPECT_EQ("myfile", items[0].name);
  11207. EXPECT_EQ("data.bin", items[0].filename);
  11208. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11209. EXPECT_EQ(file_content, items[0].content);
  11210. handled = true;
  11211. });
  11212. auto port = svr.bind_to_any_port(HOST);
  11213. auto t = thread([&] { svr.listen_after_bind(); });
  11214. auto se = detail::scope_exit([&] {
  11215. svr.stop();
  11216. t.join();
  11217. ASSERT_FALSE(svr.is_running());
  11218. ASSERT_TRUE(handled);
  11219. std::remove(tmp_path.c_str());
  11220. });
  11221. svr.wait_until_ready();
  11222. FormDataProviderItems providers;
  11223. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11224. "application/octet-stream"));
  11225. Client cli(HOST, port);
  11226. auto res = cli.Post("/upload", {}, {}, providers);
  11227. ASSERT_TRUE(res);
  11228. EXPECT_EQ(StatusCode::OK_200, res->status);
  11229. }
  11230. TEST(MakeFileBodyTest, Basic) {
  11231. const std::string file_content(4096, 'Z');
  11232. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11233. {
  11234. std::ofstream ofs(tmp_path, std::ios::binary);
  11235. ofs.write(file_content.data(),
  11236. static_cast<std::streamsize>(file_content.size()));
  11237. }
  11238. auto handled = false;
  11239. Server svr;
  11240. svr.Post("/upload", [&](const Request &req, Response &res) {
  11241. EXPECT_EQ(file_content, req.body);
  11242. handled = true;
  11243. res.status = StatusCode::OK_200;
  11244. });
  11245. auto port = svr.bind_to_any_port(HOST);
  11246. auto t = thread([&] { svr.listen_after_bind(); });
  11247. auto se = detail::scope_exit([&] {
  11248. svr.stop();
  11249. t.join();
  11250. ASSERT_FALSE(svr.is_running());
  11251. ASSERT_TRUE(handled);
  11252. std::remove(tmp_path.c_str());
  11253. });
  11254. svr.wait_until_ready();
  11255. auto fb = make_file_body(tmp_path);
  11256. ASSERT_GT(fb.first, 0u);
  11257. Client cli(HOST, port);
  11258. auto res =
  11259. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11260. ASSERT_TRUE(res);
  11261. EXPECT_EQ(StatusCode::OK_200, res->status);
  11262. }
  11263. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11264. static constexpr unsigned int number_of_tasks{1000000};
  11265. std::atomic_uint count{0};
  11266. std::unique_ptr<TaskQueue> task_queue{
  11267. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11268. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11269. auto queued = task_queue->enqueue(
  11270. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11271. EXPECT_TRUE(queued);
  11272. }
  11273. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11274. task_queue->shutdown();
  11275. #else
  11276. EXPECT_NO_THROW(task_queue->shutdown());
  11277. #endif
  11278. EXPECT_EQ(number_of_tasks, count.load());
  11279. }
  11280. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11281. static constexpr unsigned int number_of_tasks{1000000};
  11282. static constexpr unsigned int qlimit{2};
  11283. unsigned int queued_count{0};
  11284. std::atomic_uint count{0};
  11285. std::unique_ptr<TaskQueue> task_queue{
  11286. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11287. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11288. if (task_queue->enqueue(
  11289. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11290. queued_count++;
  11291. }
  11292. }
  11293. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11294. task_queue->shutdown();
  11295. #else
  11296. EXPECT_NO_THROW(task_queue->shutdown());
  11297. #endif
  11298. EXPECT_EQ(queued_count, count.load());
  11299. EXPECT_TRUE(queued_count <= number_of_tasks);
  11300. EXPECT_TRUE(queued_count >= qlimit);
  11301. }
  11302. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11303. // Use a short idle timeout so a dynamic thread spawns, times out and
  11304. // exits during the test, and the pool keeps working afterwards.
  11305. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11306. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11307. /*idle_timeout_sec=*/1}};
  11308. std::atomic_uint count{0};
  11309. std::condition_variable cv;
  11310. std::mutex mtx;
  11311. bool release = false;
  11312. // Block the base thread so the second task spawns a dynamic thread.
  11313. EXPECT_TRUE(task_queue->enqueue([&] {
  11314. std::unique_lock<std::mutex> lock(mtx);
  11315. while (!release) {
  11316. cv.wait(lock);
  11317. }
  11318. count++;
  11319. }));
  11320. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11321. // Let the dynamic thread finish its task and exceed the idle timeout.
  11322. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11323. {
  11324. std::unique_lock<std::mutex> lock(mtx);
  11325. release = true;
  11326. }
  11327. cv.notify_all();
  11328. // The pool must still accept and run tasks after the dynamic thread exited.
  11329. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11330. task_queue->shutdown();
  11331. EXPECT_EQ(3u, count.load());
  11332. }
  11333. TEST(TaskQueueTest, MaxQueuedRequests) {
  11334. static constexpr unsigned int qlimit{3};
  11335. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11336. std::condition_variable sem_cv;
  11337. std::mutex sem_mtx;
  11338. int credits = 0;
  11339. bool queued;
  11340. /* Fill up the queue with tasks that will block until we give them credits to
  11341. * complete. */
  11342. for (unsigned int n = 0; n <= qlimit;) {
  11343. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11344. std::unique_lock<std::mutex> lock(sem_mtx);
  11345. while (credits <= 0) {
  11346. sem_cv.wait(lock);
  11347. }
  11348. /* Consume the credit and signal the test code if they are all gone. */
  11349. if (--credits == 0) { sem_cv.notify_one(); }
  11350. });
  11351. if (n < qlimit) {
  11352. /* The first qlimit enqueues must succeed. */
  11353. EXPECT_TRUE(queued);
  11354. } else {
  11355. /* The last one will succeed only when the worker thread
  11356. * starts and dequeues the first blocking task. Although
  11357. * not necessary for the correctness of this test, we sleep for
  11358. * a short while to avoid busy waiting. */
  11359. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11360. }
  11361. if (queued) { n++; }
  11362. }
  11363. /* Further enqueues must fail since the queue is full. */
  11364. for (auto i = 0; i < 4; i++) {
  11365. queued = task_queue->enqueue([] {});
  11366. EXPECT_FALSE(queued);
  11367. }
  11368. /* Give the credits to allow the previous tasks to complete. */
  11369. {
  11370. std::unique_lock<std::mutex> lock(sem_mtx);
  11371. credits += qlimit + 1;
  11372. }
  11373. sem_cv.notify_all();
  11374. /* Wait for all the credits to be consumed. */
  11375. {
  11376. std::unique_lock<std::mutex> lock(sem_mtx);
  11377. while (credits > 0) {
  11378. sem_cv.wait(lock);
  11379. }
  11380. }
  11381. /* Check that we are able again to enqueue at least qlimit tasks. */
  11382. for (unsigned int i = 0; i < qlimit; i++) {
  11383. queued = task_queue->enqueue([] {});
  11384. EXPECT_TRUE(queued);
  11385. }
  11386. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11387. task_queue->shutdown();
  11388. #else
  11389. EXPECT_NO_THROW(task_queue->shutdown());
  11390. #endif
  11391. }
  11392. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11393. Server svr;
  11394. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11395. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11396. });
  11397. svr.Get("/hello", [](const Request &req, Response &res) {
  11398. res.set_content(req.get_param_value("key"), "text/plain");
  11399. });
  11400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11401. auto se = detail::scope_exit([&] {
  11402. svr.stop();
  11403. thread.join();
  11404. ASSERT_FALSE(svr.is_running());
  11405. });
  11406. svr.wait_until_ready();
  11407. {
  11408. Client cli(HOST, PORT);
  11409. cli.set_follow_location(true);
  11410. auto res = cli.Get("/");
  11411. ASSERT_TRUE(res);
  11412. EXPECT_EQ(StatusCode::OK_200, res->status);
  11413. EXPECT_EQ("val&key2=val2", res->body);
  11414. }
  11415. }
  11416. #endif
  11417. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11418. Server svr;
  11419. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11420. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11421. });
  11422. svr.Get("/hello", [](const Request &req, Response &res) {
  11423. res.set_content(req.get_param_value("key"), "text/plain");
  11424. });
  11425. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11426. auto se = detail::scope_exit([&] {
  11427. svr.stop();
  11428. thread.join();
  11429. ASSERT_FALSE(svr.is_running());
  11430. });
  11431. svr.wait_until_ready();
  11432. {
  11433. Client cli(HOST, PORT);
  11434. cli.set_follow_location(true);
  11435. auto res = cli.Get("/");
  11436. ASSERT_TRUE(res);
  11437. EXPECT_EQ(StatusCode::OK_200, res->status);
  11438. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11439. }
  11440. }
  11441. TEST(RedirectTest, RedirectWithPlusInPath) {
  11442. Server svr;
  11443. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11444. res.set_redirect("/a+b");
  11445. });
  11446. // Route pattern uses regex; escape + as \\+
  11447. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11448. res.set_content(req.path, "text/plain");
  11449. });
  11450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11451. auto se = detail::scope_exit([&] {
  11452. svr.stop();
  11453. thread.join();
  11454. ASSERT_FALSE(svr.is_running());
  11455. });
  11456. svr.wait_until_ready();
  11457. {
  11458. Client cli(HOST, PORT);
  11459. cli.set_follow_location(true);
  11460. auto res = cli.Get("/");
  11461. ASSERT_TRUE(res);
  11462. EXPECT_EQ(StatusCode::OK_200, res->status);
  11463. EXPECT_EQ("/a+b", res->body);
  11464. }
  11465. }
  11466. #ifdef CPPHTTPLIB_SSL_ENABLED
  11467. TEST(RedirectTest, Issue2185_Online) {
  11468. SSLClient client("github.com");
  11469. client.set_follow_location(true);
  11470. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11471. "Coollab-Windows.zip");
  11472. ASSERT_TRUE(res);
  11473. EXPECT_EQ(StatusCode::OK_200, res->status);
  11474. EXPECT_EQ(9920427U, res->body.size());
  11475. }
  11476. #endif
  11477. TEST(VulnerabilityTest, CRLFInjection) {
  11478. Server svr;
  11479. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11480. res.set_content("Hello 1", "text/plain");
  11481. });
  11482. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11483. res.set_content("Hello 2", "text/plain");
  11484. });
  11485. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11486. res.set_content("Hello 3", "text/plain");
  11487. });
  11488. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11489. res.set_content("Hello 4", "text/plain");
  11490. });
  11491. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11492. for (const auto &x : req.headers) {
  11493. auto key = x.first;
  11494. EXPECT_STRNE("evil", key.c_str());
  11495. }
  11496. });
  11497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11498. auto se = detail::scope_exit([&] {
  11499. svr.stop();
  11500. thread.join();
  11501. ASSERT_FALSE(svr.is_running());
  11502. });
  11503. svr.wait_until_ready();
  11504. {
  11505. Client cli(HOST, PORT);
  11506. cli.Post("/test1", "A=B",
  11507. "application/x-www-form-urlencoded\r\nevil: hello1");
  11508. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11509. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11510. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11511. }
  11512. }
  11513. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11514. auto server_thread = std::thread([] {
  11515. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11516. default_socket_options(srv);
  11517. sockaddr_in addr{};
  11518. addr.sin_family = AF_INET;
  11519. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11520. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11521. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11522. ::listen(srv, 1);
  11523. sockaddr_in cli_addr{};
  11524. socklen_t cli_len = sizeof(cli_addr);
  11525. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11526. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11527. std::string buf_all;
  11528. char buf[2048];
  11529. ssize_t n;
  11530. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11531. buf_all.append(buf, static_cast<size_t>(n));
  11532. size_t pos;
  11533. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11534. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11535. auto e = request_block.find("\r\n");
  11536. if (e != std::string::npos) {
  11537. auto request_line = request_block.substr(0, e);
  11538. std::string msg =
  11539. "CRLF injection detected in request line: '" + request_line + "'";
  11540. EXPECT_FALSE(true) << msg;
  11541. }
  11542. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11543. ::send(cli,
  11544. #ifdef _WIN32
  11545. static_cast<const char *>(resp.c_str()),
  11546. static_cast<int>(resp.size()),
  11547. #else
  11548. resp.c_str(), resp.size(),
  11549. #endif
  11550. 0);
  11551. buf_all.erase(0, pos + 4);
  11552. }
  11553. }
  11554. detail::close_socket(cli);
  11555. detail::close_socket(srv);
  11556. });
  11557. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11558. auto cli = Client("127.0.0.1", PORT + 1);
  11559. auto headers = Headers{
  11560. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11561. {"Connection", "keep-alive"}};
  11562. auto res = cli.Get("/hi", headers);
  11563. EXPECT_FALSE(res);
  11564. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11565. server_thread.join();
  11566. }
  11567. TEST(PathParamsTest, StaticMatch) {
  11568. const auto pattern = "/users/all";
  11569. detail::PathParamsMatcher matcher(pattern);
  11570. Request request;
  11571. request.path = "/users/all";
  11572. ASSERT_TRUE(matcher.match(request));
  11573. std::unordered_map<std::string, std::string> expected_params = {};
  11574. EXPECT_EQ(request.path_params, expected_params);
  11575. }
  11576. TEST(PathParamsTest, StaticMismatch) {
  11577. const auto pattern = "/users/all";
  11578. detail::PathParamsMatcher matcher(pattern);
  11579. Request request;
  11580. request.path = "/users/1";
  11581. ASSERT_FALSE(matcher.match(request));
  11582. }
  11583. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11584. const auto pattern = "/users/:id/subscriptions";
  11585. detail::PathParamsMatcher matcher(pattern);
  11586. Request request;
  11587. request.path = "/users/42/subscriptions";
  11588. ASSERT_TRUE(matcher.match(request));
  11589. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11590. EXPECT_EQ(request.path_params, expected_params);
  11591. }
  11592. TEST(PathParamsTest, SingleParamInTheEnd) {
  11593. const auto pattern = "/users/:id";
  11594. detail::PathParamsMatcher matcher(pattern);
  11595. Request request;
  11596. request.path = "/users/24";
  11597. ASSERT_TRUE(matcher.match(request));
  11598. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11599. EXPECT_EQ(request.path_params, expected_params);
  11600. }
  11601. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11602. const auto pattern = "/users/:id/";
  11603. detail::PathParamsMatcher matcher(pattern);
  11604. Request request;
  11605. request.path = "/users/42/";
  11606. ASSERT_TRUE(matcher.match(request));
  11607. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11608. EXPECT_EQ(request.path_params, expected_params);
  11609. }
  11610. TEST(PathParamsTest, EmptyParam) {
  11611. const auto pattern = "/users/:id/";
  11612. detail::PathParamsMatcher matcher(pattern);
  11613. Request request;
  11614. request.path = "/users//";
  11615. ASSERT_TRUE(matcher.match(request));
  11616. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11617. EXPECT_EQ(request.path_params, expected_params);
  11618. }
  11619. TEST(PathParamsTest, FragmentMismatch) {
  11620. const auto pattern = "/users/:id/";
  11621. detail::PathParamsMatcher matcher(pattern);
  11622. Request request;
  11623. request.path = "/admins/24/";
  11624. ASSERT_FALSE(matcher.match(request));
  11625. }
  11626. TEST(PathParamsTest, ExtraFragments) {
  11627. const auto pattern = "/users/:id";
  11628. detail::PathParamsMatcher matcher(pattern);
  11629. Request request;
  11630. request.path = "/users/42/subscriptions";
  11631. ASSERT_FALSE(matcher.match(request));
  11632. }
  11633. TEST(PathParamsTest, MissingTrailingParam) {
  11634. const auto pattern = "/users/:id";
  11635. detail::PathParamsMatcher matcher(pattern);
  11636. Request request;
  11637. request.path = "/users";
  11638. ASSERT_FALSE(matcher.match(request));
  11639. }
  11640. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11641. const auto pattern = "/users/:id/subscriptions";
  11642. detail::PathParamsMatcher matcher(pattern);
  11643. Request request;
  11644. request.path = "/users/subscriptions";
  11645. ASSERT_FALSE(matcher.match(request));
  11646. }
  11647. TEST(PathParamsTest, MultipleParams) {
  11648. const auto pattern = "/users/:userid/subscriptions/:subid";
  11649. detail::PathParamsMatcher matcher(pattern);
  11650. Request request;
  11651. request.path = "/users/42/subscriptions/2";
  11652. ASSERT_TRUE(matcher.match(request));
  11653. std::unordered_map<std::string, std::string> expected_params = {
  11654. {"userid", "42"}, {"subid", "2"}};
  11655. EXPECT_EQ(request.path_params, expected_params);
  11656. }
  11657. TEST(PathParamsTest, SequenceOfParams) {
  11658. const auto pattern = "/values/:x/:y/:z";
  11659. detail::PathParamsMatcher matcher(pattern);
  11660. Request request;
  11661. request.path = "/values/1/2/3";
  11662. ASSERT_TRUE(matcher.match(request));
  11663. std::unordered_map<std::string, std::string> expected_params = {
  11664. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11665. EXPECT_EQ(request.path_params, expected_params);
  11666. }
  11667. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11668. const auto pattern = "/prefix:suffix";
  11669. detail::PathParamsMatcher matcher(pattern);
  11670. Request request;
  11671. request.path = "/prefix:suffix";
  11672. ASSERT_TRUE(matcher.match(request));
  11673. const std::unordered_map<std::string, std::string> expected_params = {};
  11674. EXPECT_EQ(request.path_params, expected_params);
  11675. }
  11676. TEST(ParseUrlTest, VariousPatterns) {
  11677. {
  11678. detail::UrlComponents uc;
  11679. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11680. EXPECT_EQ("http", uc.scheme);
  11681. EXPECT_EQ("example.com", uc.host);
  11682. EXPECT_EQ("8080", uc.port);
  11683. EXPECT_EQ("/path", uc.path);
  11684. EXPECT_EQ("?q=1", uc.query);
  11685. }
  11686. {
  11687. detail::UrlComponents uc;
  11688. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11689. EXPECT_EQ("https", uc.scheme);
  11690. EXPECT_EQ("example.com", uc.host);
  11691. EXPECT_TRUE(uc.port.empty());
  11692. EXPECT_EQ("/path", uc.path);
  11693. }
  11694. {
  11695. detail::UrlComponents uc;
  11696. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11697. EXPECT_EQ("::1", uc.host);
  11698. EXPECT_EQ("8080", uc.port);
  11699. EXPECT_EQ("/path", uc.path);
  11700. }
  11701. {
  11702. detail::UrlComponents uc;
  11703. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11704. }
  11705. {
  11706. detail::UrlComponents uc;
  11707. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11708. EXPECT_TRUE(uc.scheme.empty());
  11709. EXPECT_EQ("example.com", uc.host);
  11710. EXPECT_EQ("/path", uc.path);
  11711. EXPECT_EQ("?q=1", uc.query);
  11712. }
  11713. {
  11714. detail::UrlComponents uc;
  11715. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11716. EXPECT_TRUE(uc.host.empty());
  11717. EXPECT_EQ("/path", uc.path);
  11718. EXPECT_EQ("?q=1", uc.query);
  11719. }
  11720. {
  11721. detail::UrlComponents uc;
  11722. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11723. EXPECT_EQ("example.com", uc.host);
  11724. EXPECT_EQ("8080", uc.port);
  11725. }
  11726. {
  11727. // Unix socket path — must not be parsed as host
  11728. detail::UrlComponents uc;
  11729. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11730. EXPECT_TRUE(uc.host.empty());
  11731. }
  11732. {
  11733. detail::UrlComponents uc;
  11734. ASSERT_TRUE(detail::parse_url("", uc));
  11735. EXPECT_TRUE(uc.host.empty());
  11736. EXPECT_TRUE(uc.path.empty());
  11737. }
  11738. {
  11739. detail::UrlComponents uc;
  11740. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11741. }
  11742. {
  11743. detail::UrlComponents uc;
  11744. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11745. }
  11746. {
  11747. // Accepted by parse_url; callers restrict to http/https
  11748. detail::UrlComponents uc;
  11749. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11750. EXPECT_EQ("ftp", uc.scheme);
  11751. }
  11752. {
  11753. detail::UrlComponents uc;
  11754. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11755. }
  11756. {
  11757. detail::UrlComponents uc;
  11758. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11759. }
  11760. }
  11761. TEST(ParseUrlTest, FragmentHandling) {
  11762. {
  11763. detail::UrlComponents uc;
  11764. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11765. EXPECT_EQ("/path", uc.path);
  11766. EXPECT_TRUE(uc.query.empty());
  11767. }
  11768. {
  11769. detail::UrlComponents uc;
  11770. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11771. EXPECT_TRUE(uc.path.empty());
  11772. EXPECT_TRUE(uc.query.empty());
  11773. }
  11774. }
  11775. TEST(ParseUrlTest, UserinfoHandling) {
  11776. // Userinfo with @ but no colon — host includes @
  11777. detail::UrlComponents uc;
  11778. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11779. EXPECT_EQ("user@host.com", uc.host);
  11780. EXPECT_EQ("/path", uc.path);
  11781. }
  11782. TEST(ParseUrlTest, IPv6EdgeCases) {
  11783. {
  11784. detail::UrlComponents uc;
  11785. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11786. EXPECT_TRUE(uc.scheme.empty());
  11787. EXPECT_EQ("::1", uc.host);
  11788. EXPECT_EQ("8080", uc.port);
  11789. }
  11790. {
  11791. // Zone ID '%25' is not in [a-fA-F0-9:]
  11792. detail::UrlComponents uc;
  11793. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11794. }
  11795. }
  11796. TEST(ParseUrlTest, SchemeEdgeCases) {
  11797. {
  11798. detail::UrlComponents uc;
  11799. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11800. }
  11801. {
  11802. detail::UrlComponents uc;
  11803. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11804. }
  11805. {
  11806. detail::UrlComponents uc;
  11807. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11808. }
  11809. }
  11810. TEST(ParseUrlTest, PortEdgeCases) {
  11811. {
  11812. detail::UrlComponents uc;
  11813. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11814. EXPECT_TRUE(uc.port.empty());
  11815. EXPECT_EQ("/path", uc.path);
  11816. }
  11817. {
  11818. // parse_url accepts any port string; validation is done by parse_port
  11819. detail::UrlComponents uc;
  11820. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11821. EXPECT_EQ("abc", uc.port);
  11822. }
  11823. }
  11824. TEST(ParseUrlTest, WebSocketPatterns) {
  11825. {
  11826. detail::UrlComponents uc;
  11827. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11828. EXPECT_EQ("ws", uc.scheme);
  11829. EXPECT_EQ("echo.example.com", uc.host);
  11830. EXPECT_EQ("8080", uc.port);
  11831. EXPECT_EQ("/ws", uc.path);
  11832. }
  11833. {
  11834. detail::UrlComponents uc;
  11835. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11836. EXPECT_EQ("wss", uc.scheme);
  11837. EXPECT_EQ("echo.example.com", uc.host);
  11838. EXPECT_TRUE(uc.port.empty());
  11839. EXPECT_EQ("/ws", uc.path);
  11840. }
  11841. }
  11842. TEST(ParseUrlTest, QueryOnly) {
  11843. detail::UrlComponents uc;
  11844. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11845. EXPECT_TRUE(uc.host.empty());
  11846. EXPECT_TRUE(uc.path.empty());
  11847. EXPECT_EQ("?q=1&r=2", uc.query);
  11848. }
  11849. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11850. detail::UrlComponents uc;
  11851. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11852. EXPECT_TRUE(uc.scheme.empty());
  11853. EXPECT_EQ("example.com", uc.host);
  11854. EXPECT_EQ("443", uc.port);
  11855. EXPECT_EQ("/path", uc.path);
  11856. }
  11857. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11858. // If ipv6 regex working, regex match codepath is taken.
  11859. // else port will default to 80 in Client impl
  11860. int clientImplMagicPort = 80;
  11861. int port = 4321;
  11862. // above ports must be different to avoid false negative
  11863. EXPECT_NE(clientImplMagicPort, port);
  11864. std::string ipV6TestURL = "http://[ff06::c3]";
  11865. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11866. CLIENT_PRIVATE_KEY_FILE);
  11867. EXPECT_EQ(cli.port(), port);
  11868. }
  11869. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11870. auto file_path = "./www/dir/index.html";
  11871. auto dir_path = "./www/dir";
  11872. detail::FileStat stat_file(file_path);
  11873. EXPECT_TRUE(stat_file.is_file());
  11874. EXPECT_FALSE(stat_file.is_dir());
  11875. detail::FileStat stat_dir(dir_path);
  11876. EXPECT_FALSE(stat_dir.is_file());
  11877. EXPECT_TRUE(stat_dir.is_dir());
  11878. }
  11879. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11880. // IPv4 with default HTTP port (80)
  11881. EXPECT_EQ("example.com",
  11882. detail::make_host_and_port_string("example.com", 80, false));
  11883. // IPv4 with default HTTPS port (443)
  11884. EXPECT_EQ("example.com",
  11885. detail::make_host_and_port_string("example.com", 443, true));
  11886. // IPv4 with non-default HTTP port
  11887. EXPECT_EQ("example.com:8080",
  11888. detail::make_host_and_port_string("example.com", 8080, false));
  11889. // IPv4 with non-default HTTPS port
  11890. EXPECT_EQ("example.com:8443",
  11891. detail::make_host_and_port_string("example.com", 8443, true));
  11892. // IPv6 with default HTTP port (80)
  11893. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11894. // IPv6 with default HTTPS port (443)
  11895. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11896. // IPv6 with non-default HTTP port
  11897. EXPECT_EQ("[::1]:8080",
  11898. detail::make_host_and_port_string("::1", 8080, false));
  11899. // IPv6 with non-default HTTPS port
  11900. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11901. // IPv6 full address with default port
  11902. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11903. detail::make_host_and_port_string(
  11904. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11905. // IPv6 full address with non-default port
  11906. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11907. detail::make_host_and_port_string(
  11908. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11909. // IPv6 localhost with non-default port
  11910. EXPECT_EQ("[::1]:3000",
  11911. detail::make_host_and_port_string("::1", 3000, false));
  11912. // IPv6 with zone ID (link-local address) with default port
  11913. EXPECT_EQ("[fe80::1%eth0]",
  11914. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11915. // IPv6 with zone ID (link-local address) with non-default port
  11916. EXPECT_EQ("[fe80::1%eth0]:8080",
  11917. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11918. // Edge case: Port 443 with is_ssl=false (should add port)
  11919. EXPECT_EQ("example.com:443",
  11920. detail::make_host_and_port_string("example.com", 443, false));
  11921. // Edge case: Port 80 with is_ssl=true (should add port)
  11922. EXPECT_EQ("example.com:80",
  11923. detail::make_host_and_port_string("example.com", 80, true));
  11924. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11925. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11926. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11927. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11928. // Security fix: Already bracketed IPv6 should not get double brackets
  11929. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11930. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11931. EXPECT_EQ("[::1]:8080",
  11932. detail::make_host_and_port_string("[::1]", 8080, false));
  11933. EXPECT_EQ("[2001:db8::1]:8080",
  11934. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11935. EXPECT_EQ("[fe80::1%eth0]",
  11936. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11937. EXPECT_EQ("[fe80::1%eth0]:8080",
  11938. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11939. // Edge case: Empty host (should return as-is)
  11940. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11941. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11942. // This is a known limitation but shouldn't crash
  11943. EXPECT_EQ("[host:name]",
  11944. detail::make_host_and_port_string("host:name", 80, false));
  11945. // Port number edge cases (no validation, but should not crash)
  11946. EXPECT_EQ("example.com:0",
  11947. detail::make_host_and_port_string("example.com", 0, false));
  11948. EXPECT_EQ("example.com:-1",
  11949. detail::make_host_and_port_string("example.com", -1, false));
  11950. EXPECT_EQ("example.com:65535",
  11951. detail::make_host_and_port_string("example.com", 65535, false));
  11952. EXPECT_EQ("example.com:65536",
  11953. detail::make_host_and_port_string("example.com", 65536, false));
  11954. }
  11955. #ifdef CPPHTTPLIB_SSL_ENABLED
  11956. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11957. httplib::SSLClient cli("roblox.com", 443);
  11958. cli.set_follow_location(true);
  11959. auto res = cli.Get("/");
  11960. ASSERT_TRUE(res);
  11961. EXPECT_EQ(StatusCode::OK_200, res->status);
  11962. }
  11963. #endif
  11964. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11965. Server svr;
  11966. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11967. EXPECT_EQ(res.status, 400);
  11968. });
  11969. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11970. auto se = detail::scope_exit([&] {
  11971. svr.stop();
  11972. thread.join();
  11973. ASSERT_FALSE(svr.is_running());
  11974. });
  11975. svr.wait_until_ready();
  11976. Client cli(HOST, PORT);
  11977. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11978. }
  11979. TEST(InvalidHeaderCharsTest, is_field_name) {
  11980. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11981. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11982. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11983. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11984. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11985. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11986. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11987. EXPECT_FALSE(detail::fields::is_field_name(""));
  11988. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11989. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11990. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11991. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11992. }
  11993. TEST(InvalidHeaderCharsTest, is_field_value) {
  11994. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11995. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11996. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11997. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11998. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11999. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12000. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12001. EXPECT_TRUE(detail::fields::is_field_value(""));
  12002. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12003. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12004. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12005. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12006. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12007. }
  12008. TEST(InvalidHeaderCharsTest, OnServer) {
  12009. Server svr;
  12010. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12011. std::string header = "Not Set";
  12012. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12013. res.set_header(header, "value");
  12014. res.set_content("Page Content Page Content", "text/plain");
  12015. });
  12016. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12017. std::string header = "Not Set";
  12018. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12019. res.set_header("X-Test", header);
  12020. res.set_content("Page Content Page Content", "text/plain");
  12021. });
  12022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12023. auto se = detail::scope_exit([&] {
  12024. svr.stop();
  12025. thread.join();
  12026. ASSERT_FALSE(svr.is_running());
  12027. });
  12028. svr.wait_until_ready();
  12029. Client cli(HOST, PORT);
  12030. {
  12031. auto res = cli.Get(
  12032. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12033. ASSERT_TRUE(res);
  12034. EXPECT_EQ("Page Content Page Content", res->body);
  12035. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12036. }
  12037. {
  12038. auto res = cli.Get(
  12039. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12040. ASSERT_TRUE(res);
  12041. EXPECT_EQ("Page Content Page Content", res->body);
  12042. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12043. }
  12044. }
  12045. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12046. auto handled = false;
  12047. Server svr;
  12048. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12049. thread t = thread([&] { svr.listen(HOST, PORT); });
  12050. auto se = detail::scope_exit([&] {
  12051. svr.stop();
  12052. t.join();
  12053. ASSERT_FALSE(svr.is_running());
  12054. ASSERT_FALSE(handled);
  12055. });
  12056. svr.wait_until_ready();
  12057. auto req = "POST /test HTTP/1.1\r\n"
  12058. "Content-Length: x\r\n"
  12059. "\r\n";
  12060. std::string response;
  12061. ASSERT_TRUE(send_request(1, req, &response));
  12062. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12063. response.substr(0, response.find("\r\n")));
  12064. }
  12065. #ifndef _WIN32
  12066. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12067. static constexpr char reject[] = "Unauthorized";
  12068. static constexpr char accept[] = "Upload accepted";
  12069. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12070. Server svr;
  12071. svr.set_expect_100_continue_handler(
  12072. [](const Request & /*req*/, Response &res) {
  12073. res.status = StatusCode::Unauthorized_401;
  12074. res.set_content(reject, "text/plain");
  12075. return res.status;
  12076. });
  12077. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12078. res.set_content(accept, "text/plain");
  12079. });
  12080. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12081. auto se = detail::scope_exit([&] {
  12082. svr.stop();
  12083. thread.join();
  12084. ASSERT_FALSE(svr.is_running());
  12085. });
  12086. svr.wait_until_ready();
  12087. {
  12088. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12089. curl_easy_init(), &curl_easy_cleanup};
  12090. ASSERT_NE(curl, nullptr);
  12091. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12092. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12093. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12094. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12095. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12096. &curl_slist_free_all};
  12097. ASSERT_NE(list, nullptr);
  12098. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12099. struct read_data {
  12100. size_t read_size;
  12101. size_t total_size;
  12102. } data = {0, total_size};
  12103. using read_callback_t =
  12104. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12105. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12106. void *userdata) -> size_t {
  12107. read_data *d = (read_data *)userdata;
  12108. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12109. std::fill_n(ptr, size * nmemb, 'A');
  12110. d->read_size += size * nmemb;
  12111. return size * nmemb;
  12112. };
  12113. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12114. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12115. std::vector<char> buffer;
  12116. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12117. using write_callback_t =
  12118. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12119. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12120. void *userdata) -> size_t {
  12121. std::vector<char> *buf = (std::vector<char> *)userdata;
  12122. buf->reserve(buf->size() + size * nmemb + 1);
  12123. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12124. return size * nmemb;
  12125. };
  12126. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12127. {
  12128. const auto res = curl_easy_perform(curl.get());
  12129. ASSERT_EQ(res, CURLE_OK);
  12130. }
  12131. {
  12132. auto response_code = long{};
  12133. const auto res =
  12134. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12135. ASSERT_EQ(res, CURLE_OK);
  12136. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12137. }
  12138. {
  12139. auto dl = curl_off_t{};
  12140. const auto res =
  12141. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12142. ASSERT_EQ(res, CURLE_OK);
  12143. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12144. }
  12145. {
  12146. buffer.push_back('\0');
  12147. ASSERT_STRCASEEQ(buffer.data(), reject);
  12148. }
  12149. }
  12150. }
  12151. #endif
  12152. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12153. // Regression test for #2458.
  12154. //
  12155. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12156. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12157. // ticket can make the client socket spuriously readable during the
  12158. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12159. // the client withholds the body and then blocks reading a response that never
  12160. // comes, failing with `Failed to read connection`.
  12161. //
  12162. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12163. // within the timeout. This raw OpenSSL server deliberately never sends
  12164. // `100 Continue`; the client must still deliver the body and receive 200.
  12165. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12166. signal(SIGPIPE, SIG_IGN);
  12167. const auto port = PORT + 4;
  12168. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12169. ASSERT_NE(srv, INVALID_SOCKET);
  12170. int opt = 1;
  12171. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12172. sockaddr_in addr{};
  12173. addr.sin_family = AF_INET;
  12174. addr.sin_port = htons(static_cast<uint16_t>(port));
  12175. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12176. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12177. ASSERT_EQ(0, ::listen(srv, 1));
  12178. std::atomic<size_t> server_body_bytes{0};
  12179. auto server_thread = std::thread([&] {
  12180. sockaddr_in cli_addr{};
  12181. socklen_t cli_len = sizeof(cli_addr);
  12182. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12183. if (cli == INVALID_SOCKET) { return; }
  12184. // Bound the lifetime of the server side so a buggy client (which never
  12185. // sends the body) cannot make this thread block forever on join.
  12186. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12187. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12188. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12189. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12190. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12191. SSL *ssl = SSL_new(ctx);
  12192. SSL_set_fd(ssl, static_cast<int>(cli));
  12193. if (SSL_accept(ssl) > 0) {
  12194. // Read the request headers. Reading here also flushes the TLS 1.3
  12195. // session tickets to the client. Deliberately do NOT send
  12196. // `100 Continue`.
  12197. std::string buf;
  12198. char tmp[1024];
  12199. while (buf.find("\r\n\r\n") == std::string::npos) {
  12200. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12201. if (n <= 0) { break; }
  12202. buf.append(tmp, static_cast<size_t>(n));
  12203. }
  12204. // A correct client sends the body now; count what arrives.
  12205. auto pos = buf.find("\r\n\r\n");
  12206. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12207. while (body < 4096) {
  12208. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12209. if (n <= 0) { break; }
  12210. body += static_cast<size_t>(n);
  12211. }
  12212. server_body_bytes = body;
  12213. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12214. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12215. SSL_shutdown(ssl);
  12216. }
  12217. SSL_free(ssl);
  12218. detail::close_socket(cli);
  12219. SSL_CTX_free(ctx);
  12220. });
  12221. auto se = detail::scope_exit([&] {
  12222. server_thread.join();
  12223. detail::close_socket(srv);
  12224. });
  12225. SSLClient cli("127.0.0.1", port);
  12226. cli.enable_server_certificate_verification(false);
  12227. cli.set_connection_timeout(5, 0);
  12228. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12229. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12230. std::string body(4096, 'A');
  12231. auto res = cli.Put("/api/test", body, "application/json");
  12232. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12233. EXPECT_EQ(StatusCode::OK_200, res->status);
  12234. EXPECT_EQ(body.size(), server_body_bytes.load());
  12235. }
  12236. #endif
  12237. template <typename S, typename C>
  12238. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12239. svr.Get("/stream", [&](const Request &, Response &res) {
  12240. auto data = new std::string("01234567890123456789");
  12241. res.set_content_provider(
  12242. data->size(), "text/plain",
  12243. [&, data](size_t offset, size_t length, DataSink &sink) {
  12244. const size_t DATA_CHUNK_SIZE = 4;
  12245. const auto &d = *data;
  12246. std::this_thread::sleep_for(std::chrono::seconds(1));
  12247. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12248. return true;
  12249. },
  12250. [data](bool success) {
  12251. EXPECT_FALSE(success);
  12252. delete data;
  12253. });
  12254. });
  12255. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12256. auto i = new size_t(0);
  12257. res.set_content_provider(
  12258. "text/plain",
  12259. [i](size_t, DataSink &sink) {
  12260. if (*i < 5) {
  12261. std::this_thread::sleep_for(std::chrono::seconds(1));
  12262. sink.write("abcd", 4);
  12263. (*i)++;
  12264. } else {
  12265. sink.done();
  12266. }
  12267. return true;
  12268. },
  12269. [i](bool success) {
  12270. EXPECT_FALSE(success);
  12271. delete i;
  12272. });
  12273. });
  12274. svr.Get("/chunked", [&](const Request &, Response &res) {
  12275. auto i = new size_t(0);
  12276. res.set_chunked_content_provider(
  12277. "text/plain",
  12278. [i](size_t, DataSink &sink) {
  12279. if (*i < 5) {
  12280. std::this_thread::sleep_for(std::chrono::seconds(1));
  12281. sink.os << "abcd";
  12282. (*i)++;
  12283. } else {
  12284. sink.done();
  12285. }
  12286. return true;
  12287. },
  12288. [i](bool success) {
  12289. EXPECT_FALSE(success);
  12290. delete i;
  12291. });
  12292. });
  12293. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12294. auto se = detail::scope_exit([&] {
  12295. svr.stop();
  12296. listen_thread.join();
  12297. ASSERT_FALSE(svr.is_running());
  12298. });
  12299. svr.wait_until_ready();
  12300. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12301. {
  12302. auto start = std::chrono::steady_clock::now();
  12303. auto res = cli.Get("/stream");
  12304. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12305. std::chrono::steady_clock::now() - start)
  12306. .count();
  12307. ASSERT_FALSE(res);
  12308. EXPECT_EQ(Error::Read, res.error());
  12309. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12310. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12311. }
  12312. {
  12313. auto start = std::chrono::steady_clock::now();
  12314. auto res = cli.Get("/stream_without_length");
  12315. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12316. std::chrono::steady_clock::now() - start)
  12317. .count();
  12318. ASSERT_FALSE(res);
  12319. EXPECT_EQ(Error::Read, res.error());
  12320. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12321. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12322. }
  12323. {
  12324. auto start = std::chrono::steady_clock::now();
  12325. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12326. EXPECT_EQ("abcd", string(data, data_length));
  12327. return true;
  12328. });
  12329. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12330. std::chrono::steady_clock::now() - start)
  12331. .count();
  12332. ASSERT_FALSE(res);
  12333. EXPECT_EQ(Error::Read, res.error());
  12334. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12335. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12336. }
  12337. }
  12338. TEST(MaxTimeoutTest, ContentStream) {
  12339. time_t timeout = 2000;
  12340. time_t threshold = 200;
  12341. Server svr;
  12342. Client cli("localhost", PORT);
  12343. max_timeout_test(svr, cli, timeout, threshold);
  12344. }
  12345. #ifdef CPPHTTPLIB_SSL_ENABLED
  12346. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12347. time_t timeout = 2000;
  12348. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12350. SSLClient cli("localhost", PORT);
  12351. cli.enable_server_certificate_verification(false);
  12352. max_timeout_test(svr, cli, timeout, threshold);
  12353. }
  12354. #endif
  12355. class EventDispatcher {
  12356. public:
  12357. EventDispatcher() {}
  12358. bool wait_event(DataSink *sink) {
  12359. unique_lock<mutex> lk(m_);
  12360. int id = id_;
  12361. // Wait with timeout to prevent hanging if client disconnects
  12362. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12363. [&] { return cid_ == id; })) {
  12364. return false; // Timeout occurred
  12365. }
  12366. sink->write(message_.data(), message_.size());
  12367. return true;
  12368. }
  12369. void send_event(const string &message) {
  12370. lock_guard<mutex> lk(m_);
  12371. cid_ = id_++;
  12372. message_ = message;
  12373. cv_.notify_all();
  12374. }
  12375. private:
  12376. mutex m_;
  12377. condition_variable cv_;
  12378. atomic_int id_{0};
  12379. atomic_int cid_{-1};
  12380. string message_;
  12381. };
  12382. TEST(ClientInThreadTest, Issue2068) {
  12383. EventDispatcher ed;
  12384. Server svr;
  12385. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12386. res.set_chunked_content_provider("text/event-stream",
  12387. [&](size_t /*offset*/, DataSink &sink) {
  12388. return ed.wait_event(&sink);
  12389. });
  12390. });
  12391. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12392. svr.wait_until_ready();
  12393. thread event_thread([&] {
  12394. int id = 0;
  12395. while (svr.is_running()) {
  12396. this_thread::sleep_for(chrono::milliseconds(500));
  12397. std::stringstream ss;
  12398. ss << "data: " << id << "\n\n";
  12399. ed.send_event(ss.str());
  12400. id++;
  12401. }
  12402. });
  12403. auto se = detail::scope_exit([&] {
  12404. svr.stop();
  12405. listen_thread.join();
  12406. event_thread.join();
  12407. ASSERT_FALSE(svr.is_running());
  12408. });
  12409. {
  12410. auto client = detail::make_unique<Client>(HOST, PORT);
  12411. client->set_read_timeout(std::chrono::minutes(10));
  12412. std::atomic<bool> stop{false};
  12413. std::thread t([&] {
  12414. client->Get("/event1",
  12415. [&](const char *, size_t) -> bool { return !stop; });
  12416. });
  12417. std::this_thread::sleep_for(std::chrono::seconds(2));
  12418. stop = true;
  12419. client->stop();
  12420. t.join();
  12421. // Reset client after thread has finished
  12422. client.reset();
  12423. }
  12424. }
  12425. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12426. auto handled = false;
  12427. Server svr;
  12428. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12429. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12430. auto se = detail::scope_exit([&] {
  12431. svr.stop();
  12432. t.join();
  12433. ASSERT_FALSE(svr.is_running());
  12434. ASSERT_FALSE(handled);
  12435. });
  12436. svr.wait_until_ready();
  12437. // Two Content-Length headers with different values — must be rejected
  12438. auto req = "POST /test HTTP/1.1\r\n"
  12439. "Content-Length: 5\r\n"
  12440. "Content-Length: 10\r\n"
  12441. "\r\n"
  12442. "hello";
  12443. std::string response;
  12444. ASSERT_TRUE(send_request(1, req, &response));
  12445. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12446. response.substr(0, response.find("\r\n")));
  12447. }
  12448. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12449. auto handled = false;
  12450. Server svr;
  12451. svr.Post("/test", [&](const Request &, Response &res) {
  12452. handled = true;
  12453. res.set_content("ok", "text/plain");
  12454. });
  12455. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12456. auto se = detail::scope_exit([&] {
  12457. svr.stop();
  12458. t.join();
  12459. ASSERT_FALSE(svr.is_running());
  12460. ASSERT_TRUE(handled);
  12461. });
  12462. svr.wait_until_ready();
  12463. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12464. auto req = "POST /test HTTP/1.1\r\n"
  12465. "Content-Length: 5\r\n"
  12466. "Content-Length: 5\r\n"
  12467. "\r\n"
  12468. "hello";
  12469. std::string response;
  12470. ASSERT_TRUE(send_request(1, req, &response));
  12471. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12472. }
  12473. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12474. Server svr;
  12475. svr.Get("/", [](const Request &req, Response &res) {
  12476. EXPECT_EQ(2U, req.trailers.size());
  12477. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12478. // Denied
  12479. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12480. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12481. // Accepted
  12482. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12483. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12484. EXPECT_TRUE(req.has_trailer("X-World"));
  12485. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12486. res.set_content("ok", "text/plain");
  12487. });
  12488. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12489. auto se = detail::scope_exit([&] {
  12490. svr.stop();
  12491. t.join();
  12492. ASSERT_FALSE(svr.is_running());
  12493. });
  12494. svr.wait_until_ready();
  12495. const std::string req = "GET / HTTP/1.1\r\n"
  12496. "Transfer-Encoding: chunked\r\n"
  12497. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12498. "\r\n"
  12499. "0\r\n"
  12500. "Content-Length: 10\r\n"
  12501. "Host: internal.local\r\n"
  12502. "Content-Type: malicious/content\r\n"
  12503. "Cookie: any\r\n"
  12504. "Set-Cookie: any\r\n"
  12505. "X-Forwarded-For: attacker.com\r\n"
  12506. "X-Real-Ip: 1.1.1.1\r\n"
  12507. "X-Hello: hello\r\n"
  12508. "X-World: world\r\n"
  12509. "\r\n";
  12510. std::string res;
  12511. ASSERT_TRUE(send_request(1, req, &res));
  12512. }
  12513. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12514. Server svr;
  12515. std::string observed_remote_addr;
  12516. std::string observed_xff;
  12517. svr.Get("/ip", [&](const Request &req, Response &res) {
  12518. observed_remote_addr = req.remote_addr;
  12519. observed_xff = req.get_header_value("X-Forwarded-For");
  12520. res.set_content("ok", "text/plain");
  12521. });
  12522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12523. auto se = detail::scope_exit([&] {
  12524. svr.stop();
  12525. t.join();
  12526. ASSERT_FALSE(svr.is_running());
  12527. });
  12528. svr.wait_until_ready();
  12529. Client cli(HOST, PORT);
  12530. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  12531. ASSERT_TRUE(res);
  12532. EXPECT_EQ(StatusCode::OK_200, res->status);
  12533. EXPECT_EQ(observed_xff, "203.0.113.66");
  12534. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12535. observed_remote_addr == "127.0.0.1");
  12536. }
  12537. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12538. Server svr;
  12539. svr.set_trusted_proxies({"203.0.113.66"});
  12540. std::string observed_remote_addr;
  12541. std::string observed_xff;
  12542. svr.Get("/ip", [&](const Request &req, Response &res) {
  12543. observed_remote_addr = req.remote_addr;
  12544. observed_xff = req.get_header_value("X-Forwarded-For");
  12545. res.set_content("ok", "text/plain");
  12546. });
  12547. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12548. auto se = detail::scope_exit([&] {
  12549. svr.stop();
  12550. t.join();
  12551. ASSERT_FALSE(svr.is_running());
  12552. });
  12553. svr.wait_until_ready();
  12554. Client cli(HOST, PORT);
  12555. auto res = cli.Get("/ip");
  12556. ASSERT_TRUE(res);
  12557. EXPECT_EQ(StatusCode::OK_200, res->status);
  12558. EXPECT_EQ(observed_xff, "");
  12559. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12560. observed_remote_addr == "127.0.0.1");
  12561. }
  12562. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12563. Server svr;
  12564. svr.set_trusted_proxies({"203.0.113.66"});
  12565. std::string observed_remote_addr;
  12566. std::string observed_xff;
  12567. svr.Get("/ip", [&](const Request &req, Response &res) {
  12568. observed_remote_addr = req.remote_addr;
  12569. observed_xff = req.get_header_value("X-Forwarded-For");
  12570. res.set_content("ok", "text/plain");
  12571. });
  12572. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12573. auto se = detail::scope_exit([&] {
  12574. svr.stop();
  12575. t.join();
  12576. ASSERT_FALSE(svr.is_running());
  12577. });
  12578. svr.wait_until_ready();
  12579. Client cli(HOST, PORT);
  12580. auto res =
  12581. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12582. ASSERT_TRUE(res);
  12583. EXPECT_EQ(StatusCode::OK_200, res->status);
  12584. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12585. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12586. }
  12587. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12588. Server svr;
  12589. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12590. std::string observed_remote_addr;
  12591. std::string observed_xff;
  12592. svr.Get("/ip", [&](const Request &req, Response &res) {
  12593. observed_remote_addr = req.remote_addr;
  12594. observed_xff = req.get_header_value("X-Forwarded-For");
  12595. res.set_content("ok", "text/plain");
  12596. });
  12597. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12598. auto se = detail::scope_exit([&] {
  12599. svr.stop();
  12600. t.join();
  12601. ASSERT_FALSE(svr.is_running());
  12602. });
  12603. svr.wait_until_ready();
  12604. Client cli(HOST, PORT);
  12605. auto res = cli.Get(
  12606. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12607. ASSERT_TRUE(res);
  12608. EXPECT_EQ(StatusCode::OK_200, res->status);
  12609. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12610. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12611. }
  12612. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12613. Server svr;
  12614. svr.set_trusted_proxies({"192.0.2.45"});
  12615. std::string observed_remote_addr;
  12616. std::string observed_xff;
  12617. svr.Get("/ip", [&](const Request &req, Response &res) {
  12618. observed_remote_addr = req.remote_addr;
  12619. observed_xff = req.get_header_value("X-Forwarded-For");
  12620. res.set_content("ok", "text/plain");
  12621. });
  12622. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12623. auto se = detail::scope_exit([&] {
  12624. svr.stop();
  12625. t.join();
  12626. ASSERT_FALSE(svr.is_running());
  12627. });
  12628. svr.wait_until_ready();
  12629. Client cli(HOST, PORT);
  12630. auto res =
  12631. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12632. ASSERT_TRUE(res);
  12633. EXPECT_EQ(StatusCode::OK_200, res->status);
  12634. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12635. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12636. }
  12637. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12638. Server svr;
  12639. svr.set_trusted_proxies({"192.0.2.45"});
  12640. std::string observed_remote_addr;
  12641. std::string observed_xff;
  12642. svr.Get("/ip", [&](const Request &req, Response &res) {
  12643. observed_remote_addr = req.remote_addr;
  12644. observed_xff = req.get_header_value("X-Forwarded-For");
  12645. res.set_content("ok", "text/plain");
  12646. });
  12647. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12648. auto se = detail::scope_exit([&] {
  12649. svr.stop();
  12650. t.join();
  12651. ASSERT_FALSE(svr.is_running());
  12652. });
  12653. svr.wait_until_ready();
  12654. Client cli(HOST, PORT);
  12655. auto res = cli.Get(
  12656. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12657. ASSERT_TRUE(res);
  12658. EXPECT_EQ(StatusCode::OK_200, res->status);
  12659. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12660. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12661. }
  12662. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12663. Server svr;
  12664. svr.set_trusted_proxies({"192.0.2.45"});
  12665. std::string observed_remote_addr;
  12666. std::string observed_xff;
  12667. svr.Get("/ip", [&](const Request &req, Response &res) {
  12668. observed_remote_addr = req.remote_addr;
  12669. observed_xff = req.get_header_value("X-Forwarded-For");
  12670. res.set_content("ok", "text/plain");
  12671. });
  12672. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12673. auto se = detail::scope_exit([&] {
  12674. svr.stop();
  12675. t.join();
  12676. ASSERT_FALSE(svr.is_running());
  12677. });
  12678. svr.wait_until_ready();
  12679. std::string raw_req =
  12680. "GET /ip HTTP/1.1\r\n"
  12681. "Host: localhost\r\n"
  12682. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12683. "Connection: close\r\n"
  12684. "\r\n";
  12685. std::string out;
  12686. ASSERT_TRUE(send_request(5, raw_req, &out));
  12687. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12688. // Header parser trims surrounding whitespace of the header value
  12689. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12690. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12691. }
  12692. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12693. // crash the server (it used to call front() on an empty vector inside
  12694. // get_client_ip). The connection-level remote address must be retained instead.
  12695. static void run_malformed_xff_test(const std::string &xff_value) {
  12696. Server svr;
  12697. svr.set_trusted_proxies({"192.0.2.45"});
  12698. std::string observed_remote_addr;
  12699. svr.Get("/ip", [&](const Request &req, Response &res) {
  12700. observed_remote_addr = req.remote_addr;
  12701. res.set_content("ok", "text/plain");
  12702. });
  12703. int port = 0;
  12704. thread t = thread([&]() {
  12705. port = svr.bind_to_any_port(HOST);
  12706. svr.listen_after_bind();
  12707. });
  12708. auto se = detail::scope_exit([&] {
  12709. svr.stop();
  12710. t.join();
  12711. ASSERT_FALSE(svr.is_running());
  12712. });
  12713. svr.wait_until_ready();
  12714. Client cli(HOST, port);
  12715. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12716. ASSERT_TRUE(res);
  12717. EXPECT_EQ(StatusCode::OK_200, res->status);
  12718. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12719. observed_remote_addr == "127.0.0.1");
  12720. }
  12721. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12722. run_malformed_xff_test("");
  12723. }
  12724. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12725. run_malformed_xff_test(",");
  12726. }
  12727. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12728. run_malformed_xff_test(", , ,");
  12729. }
  12730. #ifndef _WIN32
  12731. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12732. Server svr;
  12733. svr.Post("/post", [&](const Request &req, Response &res) {
  12734. res.set_content(req.body, "text/plain");
  12735. });
  12736. svr.Put("/put", [&](const Request &req, Response &res) {
  12737. res.set_content(req.body, "text/plain");
  12738. });
  12739. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12740. res.set_content(req.body, "text/plain");
  12741. });
  12742. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12743. res.set_content(req.body, "text/plain");
  12744. });
  12745. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12746. auto se = detail::scope_exit([&] {
  12747. svr.stop();
  12748. t.join();
  12749. ASSERT_FALSE(svr.is_running());
  12750. });
  12751. svr.wait_until_ready();
  12752. std::string resp;
  12753. // POST without Content-Length
  12754. ASSERT_TRUE(send_request(5,
  12755. "POST /post HTTP/1.1\r\n"
  12756. "Host: localhost\r\n"
  12757. "Connection: close\r\n"
  12758. "\r\n",
  12759. &resp));
  12760. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12761. // PUT without Content-Length
  12762. resp.clear();
  12763. ASSERT_TRUE(send_request(5,
  12764. "PUT /put HTTP/1.1\r\n"
  12765. "Host: localhost\r\n"
  12766. "Connection: close\r\n"
  12767. "\r\n",
  12768. &resp));
  12769. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12770. // PATCH without Content-Length
  12771. resp.clear();
  12772. ASSERT_TRUE(send_request(5,
  12773. "PATCH /patch HTTP/1.1\r\n"
  12774. "Host: localhost\r\n"
  12775. "Connection: close\r\n"
  12776. "\r\n",
  12777. &resp));
  12778. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12779. // DELETE without Content-Length
  12780. resp.clear();
  12781. ASSERT_TRUE(send_request(5,
  12782. "DELETE /delete HTTP/1.1\r\n"
  12783. "Host: localhost\r\n"
  12784. "Connection: close\r\n"
  12785. "\r\n",
  12786. &resp));
  12787. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12788. }
  12789. #endif
  12790. //==============================================================================
  12791. // open_stream() Tests
  12792. //==============================================================================
  12793. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12794. std::string result;
  12795. char buf[8192];
  12796. ssize_t n;
  12797. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12798. result.append(buf, static_cast<size_t>(n));
  12799. }
  12800. return result;
  12801. }
  12802. // Mock stream for unit tests
  12803. class MockStream : public Stream {
  12804. public:
  12805. std::string data;
  12806. size_t pos = 0;
  12807. ssize_t error_after = -1; // -1 = no error
  12808. explicit MockStream(const std::string &d, ssize_t err = -1)
  12809. : data(d), error_after(err) {}
  12810. bool is_readable() const override { return true; }
  12811. bool wait_readable() const override { return true; }
  12812. bool wait_writable() const override { return true; }
  12813. ssize_t read(char *ptr, size_t size) override {
  12814. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12815. if (pos >= data.size()) return 0;
  12816. size_t limit =
  12817. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12818. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12819. std::memcpy(ptr, data.data() + pos, to_read);
  12820. pos += to_read;
  12821. return static_cast<ssize_t>(to_read);
  12822. }
  12823. ssize_t write(const char *, size_t) override { return -1; }
  12824. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12825. ip = "127.0.0.1";
  12826. port = 0;
  12827. }
  12828. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12829. ip = "127.0.0.1";
  12830. port = 0;
  12831. }
  12832. socket_t socket() const override { return INVALID_SOCKET; }
  12833. time_t duration() const override { return 0; }
  12834. };
  12835. TEST(StreamHandleTest, Basic) {
  12836. ClientImpl::StreamHandle handle;
  12837. EXPECT_FALSE(handle.is_valid());
  12838. handle.response = detail::make_unique<Response>();
  12839. handle.error = Error::Connection;
  12840. EXPECT_FALSE(handle.is_valid());
  12841. handle.error = Error::Success;
  12842. EXPECT_TRUE(handle.is_valid());
  12843. }
  12844. TEST(BodyReaderTest, Basic) {
  12845. MockStream stream("Hello, World!");
  12846. detail::BodyReader reader;
  12847. reader.stream = &stream;
  12848. reader.content_length = 13;
  12849. char buf[32];
  12850. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12851. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12852. EXPECT_TRUE(reader.eof);
  12853. }
  12854. TEST(BodyReaderTest, NoStream) {
  12855. detail::BodyReader reader;
  12856. char buf[32];
  12857. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12858. EXPECT_EQ(Error::Connection, reader.last_error);
  12859. }
  12860. TEST(BodyReaderTest, Error) {
  12861. MockStream stream("Hello, World!", 5);
  12862. detail::BodyReader reader;
  12863. reader.stream = &stream;
  12864. reader.content_length = 13;
  12865. char buf[32];
  12866. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12867. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12868. EXPECT_EQ(Error::Read, reader.last_error);
  12869. }
  12870. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12871. // Mock-based StreamHandle tests relying on private internals are removed.
  12872. class OpenStreamTest : public ::testing::Test {
  12873. protected:
  12874. void SetUp() override {
  12875. svr_.Get("/hello", [](const Request &, Response &res) {
  12876. res.set_content("Hello World!", "text/plain");
  12877. });
  12878. svr_.Get("/large", [](const Request &, Response &res) {
  12879. res.set_content(std::string(10000, 'X'), "text/plain");
  12880. });
  12881. svr_.Get("/chunked", [](const Request &, Response &res) {
  12882. res.set_chunked_content_provider("text/plain",
  12883. [](size_t offset, DataSink &sink) {
  12884. if (offset < 15) {
  12885. sink.write("chunk", 5);
  12886. return true;
  12887. }
  12888. sink.done();
  12889. return true;
  12890. });
  12891. });
  12892. svr_.Get("/compressible", [](const Request &, Response &res) {
  12893. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12894. DataSink &sink) {
  12895. if (offset < 100 * 1024) {
  12896. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12897. sink.write(chunk.data(), chunk.size());
  12898. return true;
  12899. }
  12900. sink.done();
  12901. return true;
  12902. });
  12903. });
  12904. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12905. [](const Request & /*req*/, Response &res) {
  12906. auto i = new int(0);
  12907. res.set_header("Trailer", "Content-Length, X-Allowed");
  12908. res.set_chunked_content_provider(
  12909. "text/plain",
  12910. [i](size_t /*offset*/, DataSink &sink) {
  12911. switch (*i) {
  12912. case 0: sink.os << "123"; break;
  12913. case 1: sink.os << "456"; break;
  12914. case 2: sink.os << "789"; break;
  12915. case 3: {
  12916. sink.done_with_trailer(
  12917. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12918. } break;
  12919. }
  12920. (*i)++;
  12921. return true;
  12922. },
  12923. [i](bool success) {
  12924. EXPECT_TRUE(success);
  12925. delete i;
  12926. });
  12927. });
  12928. // Echo headers endpoint for header-related tests
  12929. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12930. std::string body;
  12931. for (const auto &h : req.headers) {
  12932. body.append(h.first);
  12933. body.push_back(':');
  12934. body.append(h.second);
  12935. body.push_back('\n');
  12936. }
  12937. res.set_content(body, "text/plain");
  12938. });
  12939. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12940. std::string body;
  12941. for (const auto &h : req.headers) {
  12942. body.append(h.first);
  12943. body.push_back(':');
  12944. body.append(h.second);
  12945. body.push_back('\n');
  12946. }
  12947. res.set_content(body, "text/plain");
  12948. });
  12949. port_ = svr_.bind_to_any_port("127.0.0.1");
  12950. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12951. svr_.wait_until_ready();
  12952. }
  12953. void TearDown() override {
  12954. svr_.stop();
  12955. if (thread_.joinable()) thread_.join();
  12956. }
  12957. Server svr_;
  12958. std::thread thread_;
  12959. int port_ = 0;
  12960. };
  12961. TEST_F(OpenStreamTest, Basic) {
  12962. Client cli("127.0.0.1", port_);
  12963. auto handle = cli.open_stream("GET", "/hello");
  12964. EXPECT_TRUE(handle.is_valid());
  12965. EXPECT_EQ("Hello World!", read_all(handle));
  12966. }
  12967. TEST_F(OpenStreamTest, SmallBuffer) {
  12968. Client cli("127.0.0.1", port_);
  12969. auto handle = cli.open_stream("GET", "/hello");
  12970. std::string result;
  12971. char buf[4];
  12972. ssize_t n;
  12973. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12974. result.append(buf, static_cast<size_t>(n));
  12975. EXPECT_EQ("Hello World!", result);
  12976. }
  12977. TEST_F(OpenStreamTest, DefaultHeaders) {
  12978. Client cli("127.0.0.1", port_);
  12979. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12980. {
  12981. auto handle = cli.open_stream("GET", "/echo-headers");
  12982. ASSERT_TRUE(handle.is_valid());
  12983. auto body = read_all(handle);
  12984. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12985. std::string::npos);
  12986. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12987. std::string::npos);
  12988. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12989. }
  12990. // open_stream POST with body and no explicit content_type should NOT add
  12991. // text/plain Content-Type (behavior differs from non-streaming path), but
  12992. // should include Content-Length
  12993. {
  12994. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12995. ASSERT_TRUE(handle.is_valid());
  12996. auto body = read_all(handle);
  12997. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12998. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12999. }
  13000. // open_stream POST with explicit Content-Type should preserve it
  13001. {
  13002. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13003. {{"Content-Type", "application/custom"}},
  13004. "{}", "application/custom");
  13005. ASSERT_TRUE(handle.is_valid());
  13006. auto body = read_all(handle);
  13007. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13008. }
  13009. // User-specified User-Agent must not be overwritten for stream API
  13010. {
  13011. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13012. {{"User-Agent", "MyAgent/1.2"}});
  13013. ASSERT_TRUE(handle.is_valid());
  13014. auto body = read_all(handle);
  13015. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13016. }
  13017. }
  13018. TEST_F(OpenStreamTest, Large) {
  13019. Client cli("127.0.0.1", port_);
  13020. auto handle = cli.open_stream("GET", "/large");
  13021. EXPECT_EQ(10000u, read_all(handle).size());
  13022. }
  13023. TEST_F(OpenStreamTest, ConnectionError) {
  13024. Client cli("127.0.0.1", 9999);
  13025. auto handle = cli.open_stream("GET", "/hello");
  13026. EXPECT_FALSE(handle.is_valid());
  13027. }
  13028. TEST_F(OpenStreamTest, Chunked) {
  13029. Client cli("127.0.0.1", port_);
  13030. auto handle = cli.open_stream("GET", "/chunked");
  13031. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13032. "Transfer-Encoding") == "chunked");
  13033. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13034. }
  13035. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13036. Client cli("127.0.0.1", port_);
  13037. auto handle =
  13038. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13039. ASSERT_TRUE(handle.is_valid());
  13040. // Consume body to allow trailers to be received/parsed
  13041. auto body = read_all(handle);
  13042. // Explicitly parse trailers (ensure trailers are available for assertion)
  13043. handle.parse_trailers_if_needed();
  13044. EXPECT_EQ(std::string("123456789"), body);
  13045. // The response should include a Trailer header declaring both names
  13046. ASSERT_TRUE(handle.response);
  13047. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13048. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13049. handle.response->get_header_value("Trailer"));
  13050. // Prohibited trailer must not be present
  13051. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13052. // Allowed trailer should be present
  13053. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13054. EXPECT_EQ(std::string("yes"),
  13055. handle.response->get_trailer_value("X-Allowed"));
  13056. // Verify trailers are NOT present as regular headers
  13057. EXPECT_EQ(std::string(""),
  13058. handle.response->get_header_value("Content-Length"));
  13059. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13060. }
  13061. static std::thread serve_single_response(std::promise<int> &port_promise,
  13062. const std::string &response) {
  13063. return std::thread([&port_promise, response] {
  13064. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13065. default_socket_options(srv);
  13066. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13067. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13068. sockaddr_in addr{};
  13069. addr.sin_family = AF_INET;
  13070. addr.sin_port = htons(0); // Let OS assign a free port
  13071. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13072. int opt = 1;
  13073. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13074. #ifdef _WIN32
  13075. reinterpret_cast<const char *>(&opt),
  13076. #else
  13077. &opt,
  13078. #endif
  13079. sizeof(opt));
  13080. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13081. ::listen(srv, 1) != 0) {
  13082. port_promise.set_value(-1);
  13083. detail::close_socket(srv);
  13084. return;
  13085. }
  13086. socklen_t addr_len = sizeof(addr);
  13087. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13088. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13089. sockaddr_in cli_addr{};
  13090. socklen_t cli_len = sizeof(cli_addr);
  13091. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13092. if (cli != INVALID_SOCKET) {
  13093. // Read the complete HTTP request (until the blank line that terminates
  13094. // headers) before sending the response. If the server closes the socket
  13095. // while the client's request data is still unread in the kernel receive
  13096. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13097. // connection on both sides: it discards the client's receive buffer
  13098. // (which already holds our response) and causes any in-progress write on
  13099. // the client to fail with ECONNRESET. Reading all request data first
  13100. // ensures close() emits a graceful FIN.
  13101. {
  13102. char rbuf[256];
  13103. std::string req;
  13104. while (req.find("\r\n\r\n") == std::string::npos) {
  13105. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13106. if (n <= 0) { break; }
  13107. req.append(rbuf, static_cast<size_t>(n));
  13108. }
  13109. }
  13110. ::send(cli,
  13111. #ifdef _WIN32
  13112. static_cast<const char *>(response.c_str()),
  13113. static_cast<int>(response.size()),
  13114. #else
  13115. response.c_str(), response.size(),
  13116. #endif
  13117. 0);
  13118. detail::close_socket(cli);
  13119. }
  13120. detail::close_socket(srv);
  13121. });
  13122. }
  13123. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13124. #ifndef _WIN32
  13125. signal(SIGPIPE, SIG_IGN);
  13126. #endif
  13127. std::promise<int> port_promise;
  13128. auto port_future = port_promise.get_future();
  13129. auto server_thread =
  13130. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13131. "Content-Type: text/plain\r\n"
  13132. "Content-Length: not-a-number\r\n"
  13133. "Connection: close\r\n"
  13134. "\r\n"
  13135. "hello");
  13136. auto port = port_future.get();
  13137. ASSERT_GT(port, 0);
  13138. Client cli("127.0.0.1", port);
  13139. auto handle = cli.open_stream("GET", "/");
  13140. EXPECT_FALSE(handle.is_valid());
  13141. server_thread.join();
  13142. }
  13143. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13144. #ifndef _WIN32
  13145. signal(SIGPIPE, SIG_IGN);
  13146. #endif
  13147. std::promise<int> port_promise;
  13148. auto port_future = port_promise.get_future();
  13149. auto server_thread = serve_single_response(
  13150. port_promise, "HTTP/1.1 200 OK\r\n"
  13151. "Content-Type: text/plain\r\n"
  13152. "Content-Length: 99999999999999999999999999\r\n"
  13153. "Connection: close\r\n"
  13154. "\r\n"
  13155. "hello");
  13156. auto port = port_future.get();
  13157. ASSERT_GT(port, 0);
  13158. // Before the fix, std::stoull would throw std::out_of_range here and
  13159. // crash the process. After the fix, strtoull silently clamps to
  13160. // ULLONG_MAX so the stream opens without crashing. The important thing
  13161. // is that the process does NOT terminate.
  13162. Client cli("127.0.0.1", port);
  13163. auto handle = cli.open_stream("GET", "/");
  13164. EXPECT_TRUE(handle.is_valid());
  13165. server_thread.join();
  13166. }
  13167. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13168. TEST_F(OpenStreamTest, Gzip) {
  13169. Client cli("127.0.0.1", port_);
  13170. auto handle = cli.open_stream("GET", "/compressible", {},
  13171. {{"Accept-Encoding", "gzip"}});
  13172. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13173. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13174. }
  13175. #endif
  13176. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13177. TEST_F(OpenStreamTest, Brotli) {
  13178. Client cli("127.0.0.1", port_);
  13179. auto handle =
  13180. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13181. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13182. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13183. }
  13184. #endif
  13185. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13186. TEST_F(OpenStreamTest, Zstd) {
  13187. Client cli("127.0.0.1", port_);
  13188. auto handle = cli.open_stream("GET", "/compressible", {},
  13189. {{"Accept-Encoding", "zstd"}});
  13190. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13191. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13192. }
  13193. #endif
  13194. #ifdef CPPHTTPLIB_SSL_ENABLED
  13195. class SSLOpenStreamTest : public ::testing::Test {
  13196. protected:
  13197. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13198. void SetUp() override {
  13199. svr_.Get("/hello", [](const Request &, Response &res) {
  13200. res.set_content("Hello SSL World!", "text/plain");
  13201. });
  13202. svr_.Get("/chunked", [](const Request &, Response &res) {
  13203. res.set_chunked_content_provider("text/plain",
  13204. [](size_t offset, DataSink &sink) {
  13205. if (offset < 15) {
  13206. sink.write("chunk", 5);
  13207. return true;
  13208. }
  13209. sink.done();
  13210. return true;
  13211. });
  13212. });
  13213. svr_.Post("/echo", [](const Request &req, Response &res) {
  13214. res.set_content(req.body, req.get_header_value("Content-Type"));
  13215. });
  13216. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13217. std::string body = req.body;
  13218. res.set_chunked_content_provider(
  13219. "text/plain", [body](size_t offset, DataSink &sink) {
  13220. if (offset < body.size()) {
  13221. sink.write(body.data() + offset, body.size() - offset);
  13222. }
  13223. sink.done();
  13224. return true;
  13225. });
  13226. });
  13227. port_ = svr_.bind_to_any_port("127.0.0.1");
  13228. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13229. svr_.wait_until_ready();
  13230. }
  13231. void TearDown() override {
  13232. svr_.stop();
  13233. if (thread_.joinable()) thread_.join();
  13234. }
  13235. SSLServer svr_;
  13236. std::thread thread_;
  13237. int port_ = 0;
  13238. };
  13239. TEST_F(SSLOpenStreamTest, Basic) {
  13240. SSLClient cli("127.0.0.1", port_);
  13241. cli.enable_server_certificate_verification(false);
  13242. auto handle = cli.open_stream("GET", "/hello");
  13243. ASSERT_TRUE(handle.is_valid());
  13244. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13245. }
  13246. TEST_F(SSLOpenStreamTest, Chunked) {
  13247. SSLClient cli("127.0.0.1", port_);
  13248. cli.enable_server_certificate_verification(false);
  13249. auto handle = cli.open_stream("GET", "/chunked");
  13250. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13251. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13252. "Transfer-Encoding") == "chunked");
  13253. auto body = read_all(handle);
  13254. EXPECT_EQ("chunkchunkchunk", body);
  13255. }
  13256. TEST_F(SSLOpenStreamTest, Post) {
  13257. SSLClient cli("127.0.0.1", port_);
  13258. cli.enable_server_certificate_verification(false);
  13259. auto handle =
  13260. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13261. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13262. EXPECT_EQ(200, handle.response->status);
  13263. auto body = read_all(handle);
  13264. EXPECT_EQ("Hello SSL POST", body);
  13265. }
  13266. TEST_F(SSLOpenStreamTest, PostChunked) {
  13267. SSLClient cli("127.0.0.1", port_);
  13268. cli.enable_server_certificate_verification(false);
  13269. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13270. "Chunked SSL Data", "text/plain");
  13271. ASSERT_TRUE(handle.is_valid());
  13272. EXPECT_EQ(200, handle.response->status);
  13273. auto body = read_all(handle);
  13274. EXPECT_EQ("Chunked SSL Data", body);
  13275. }
  13276. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13277. // Content-Length is terminated by the server closing the connection. When the
  13278. // SSL peer sends a close_notify after the body, the client must treat it as a
  13279. // clean EOF and return a successful response rather than an error.
  13280. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13282. ASSERT_TRUE(svr.is_valid());
  13283. svr.set_keep_alive_max_count(1);
  13284. const std::string expected_body = "Hello from connection-close response!";
  13285. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13286. res.set_content_provider("text/plain",
  13287. [&](size_t offset, DataSink &sink) -> bool {
  13288. if (offset < expected_body.size()) {
  13289. sink.write(expected_body.data() + offset,
  13290. expected_body.size() - offset);
  13291. }
  13292. sink.done();
  13293. return true;
  13294. });
  13295. });
  13296. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13297. auto se = detail::scope_exit([&] {
  13298. svr.stop();
  13299. listen_thread.join();
  13300. ASSERT_FALSE(svr.is_running());
  13301. });
  13302. svr.wait_until_ready();
  13303. SSLClient cli(HOST, PORT);
  13304. cli.enable_server_certificate_verification(false);
  13305. auto res = cli.Get("/no-content-length");
  13306. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13307. EXPECT_EQ(StatusCode::OK_200, res->status);
  13308. EXPECT_EQ(expected_body, res->body);
  13309. }
  13310. #endif // CPPHTTPLIB_SSL_ENABLED
  13311. //==============================================================================
  13312. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13313. // results for various scenarios.
  13314. //==============================================================================
  13315. TEST(ParityTest, GetVsOpenStream) {
  13316. Server svr;
  13317. const std::string path = "/parity";
  13318. const std::string content = "Parity test content: hello world";
  13319. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13320. res.set_content(content, "text/plain");
  13321. });
  13322. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13323. auto se = detail::scope_exit([&] {
  13324. svr.stop();
  13325. t.join();
  13326. ASSERT_FALSE(svr.is_running());
  13327. });
  13328. svr.wait_until_ready();
  13329. Client cli(HOST, PORT);
  13330. // Non-stream path
  13331. auto r1 = cli.Get(path);
  13332. ASSERT_TRUE(r1);
  13333. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13334. // Stream path
  13335. auto h = cli.open_stream("GET", path);
  13336. ASSERT_TRUE(h.is_valid());
  13337. EXPECT_EQ(r1->body, read_all(h));
  13338. }
  13339. // Helper to compress data with provided compressor type T
  13340. template <typename Compressor>
  13341. static std::string compress_payload_for_parity(const std::string &in) {
  13342. std::string out;
  13343. Compressor compressor;
  13344. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13345. [&](const char *data, size_t n) {
  13346. out.append(data, n);
  13347. return true;
  13348. });
  13349. EXPECT_TRUE(ok);
  13350. return out;
  13351. }
  13352. // Helper function for compression parity tests
  13353. template <typename Compressor>
  13354. static void test_compression_parity(const std::string &original,
  13355. const std::string &path,
  13356. const std::string &encoding) {
  13357. const std::string compressed =
  13358. compress_payload_for_parity<Compressor>(original);
  13359. Server svr;
  13360. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13361. res.set_content(compressed, "application/octet-stream");
  13362. res.set_header("Content-Encoding", encoding);
  13363. });
  13364. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13365. auto se = detail::scope_exit([&] {
  13366. svr.stop();
  13367. t.join();
  13368. ASSERT_FALSE(svr.is_running());
  13369. });
  13370. svr.wait_until_ready();
  13371. Client cli(HOST, PORT);
  13372. // Non-streaming
  13373. {
  13374. auto res = cli.Get(path);
  13375. ASSERT_TRUE(res);
  13376. EXPECT_EQ(StatusCode::OK_200, res->status);
  13377. EXPECT_EQ(original, res->body);
  13378. }
  13379. // Streaming
  13380. {
  13381. auto h = cli.open_stream("GET", path);
  13382. ASSERT_TRUE(h.is_valid());
  13383. EXPECT_EQ(original, read_all(h));
  13384. }
  13385. }
  13386. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13387. TEST(ParityTest, Gzip) {
  13388. test_compression_parity<detail::gzip_compressor>(
  13389. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13390. }
  13391. #endif
  13392. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13393. TEST(ParityTest, Brotli) {
  13394. test_compression_parity<detail::brotli_compressor>(
  13395. "Hello, brotli parity test payload", "/parity-br", "br");
  13396. }
  13397. #endif
  13398. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13399. TEST(ParityTest, Zstd) {
  13400. test_compression_parity<detail::zstd_compressor>(
  13401. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13402. }
  13403. #endif
  13404. //==============================================================================
  13405. // New Stream API Tests
  13406. //==============================================================================
  13407. inline std::string read_body(httplib::stream::Result &result) {
  13408. std::string body;
  13409. while (result.next()) {
  13410. body.append(result.data(), result.size());
  13411. }
  13412. return body;
  13413. }
  13414. TEST(ClientConnectionTest, Basic) {
  13415. httplib::ClientConnection conn;
  13416. EXPECT_FALSE(conn.is_open());
  13417. conn.sock = 1;
  13418. EXPECT_TRUE(conn.is_open());
  13419. httplib::ClientConnection conn2(std::move(conn));
  13420. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13421. conn2.sock = INVALID_SOCKET;
  13422. }
  13423. // Unified test server for all stream::* tests
  13424. class StreamApiTest : public ::testing::Test {
  13425. protected:
  13426. void SetUp() override {
  13427. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13428. res.set_content("Hello World!", "text/plain");
  13429. });
  13430. svr_.Get("/echo-params",
  13431. [](const httplib::Request &req, httplib::Response &res) {
  13432. std::string r;
  13433. for (const auto &p : req.params) {
  13434. if (!r.empty()) r += "&";
  13435. r += p.first + "=" + p.second;
  13436. }
  13437. res.set_content(r, "text/plain");
  13438. });
  13439. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13440. res.set_content(req.body, req.get_header_value("Content-Type"));
  13441. });
  13442. svr_.Post("/echo-headers",
  13443. [](const httplib::Request &req, httplib::Response &res) {
  13444. std::string r;
  13445. for (const auto &h : req.headers)
  13446. r += h.first + ": " + h.second + "\n";
  13447. res.set_content(r, "text/plain");
  13448. });
  13449. svr_.Post("/echo-params",
  13450. [](const httplib::Request &req, httplib::Response &res) {
  13451. std::string r = "params:";
  13452. for (const auto &p : req.params)
  13453. r += p.first + "=" + p.second + ";";
  13454. res.set_content(r + " body:" + req.body, "text/plain");
  13455. });
  13456. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13457. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13458. });
  13459. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13460. res.set_content("PUT:" + req.body, "text/plain");
  13461. });
  13462. svr_.Patch("/echo",
  13463. [](const httplib::Request &req, httplib::Response &res) {
  13464. res.set_content("PATCH:" + req.body, "text/plain");
  13465. });
  13466. svr_.Delete(
  13467. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13468. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13469. "text/plain");
  13470. });
  13471. svr_.Get("/head-test",
  13472. [](const httplib::Request &, httplib::Response &res) {
  13473. res.set_content("body for HEAD", "text/plain");
  13474. });
  13475. svr_.Options("/options",
  13476. [](const httplib::Request &, httplib::Response &res) {
  13477. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13478. });
  13479. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13480. svr_.wait_until_ready();
  13481. }
  13482. void TearDown() override {
  13483. svr_.stop();
  13484. if (thread_.joinable()) thread_.join();
  13485. }
  13486. httplib::Server svr_;
  13487. std::thread thread_;
  13488. };
  13489. // stream::Get tests
  13490. TEST_F(StreamApiTest, GetBasic) {
  13491. httplib::Client cli(HOST, PORT);
  13492. auto result = httplib::stream::Get(cli, "/hello");
  13493. ASSERT_TRUE(result.is_valid());
  13494. EXPECT_EQ(200, result.status());
  13495. EXPECT_EQ("Hello World!", read_body(result));
  13496. }
  13497. TEST_F(StreamApiTest, GetWithParams) {
  13498. httplib::Client cli(HOST, PORT);
  13499. httplib::Params params{{"foo", "bar"}};
  13500. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13501. ASSERT_TRUE(result.is_valid());
  13502. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13503. }
  13504. TEST_F(StreamApiTest, GetConnectionError) {
  13505. httplib::Client cli(HOST, 9999);
  13506. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13507. }
  13508. TEST_F(StreamApiTest, Get404) {
  13509. httplib::Client cli(HOST, PORT);
  13510. auto result = httplib::stream::Get(cli, "/nonexistent");
  13511. EXPECT_TRUE(result.is_valid());
  13512. EXPECT_EQ(404, result.status());
  13513. }
  13514. // stream::Post tests
  13515. TEST_F(StreamApiTest, PostBasic) {
  13516. httplib::Client cli(HOST, PORT);
  13517. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13518. "application/json");
  13519. ASSERT_TRUE(result.is_valid());
  13520. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13521. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13522. }
  13523. TEST_F(StreamApiTest, PostWithHeaders) {
  13524. httplib::Client cli(HOST, PORT);
  13525. httplib::Headers headers{{"X-Custom", "value"}};
  13526. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13527. "text/plain");
  13528. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13529. }
  13530. TEST_F(StreamApiTest, PostWithParams) {
  13531. httplib::Client cli(HOST, PORT);
  13532. httplib::Params params{{"k", "v"}};
  13533. auto result =
  13534. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13535. auto body = read_body(result);
  13536. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13537. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13538. }
  13539. TEST_F(StreamApiTest, PostLarge) {
  13540. httplib::Client cli(HOST, PORT);
  13541. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13542. size_t total = 0;
  13543. while (result.next()) {
  13544. total += result.size();
  13545. }
  13546. EXPECT_EQ(100u * 1024u, total);
  13547. }
  13548. // stream::Put/Patch tests
  13549. TEST_F(StreamApiTest, PutAndPatch) {
  13550. httplib::Client cli(HOST, PORT);
  13551. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13552. EXPECT_EQ("PUT:test", read_body(put));
  13553. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13554. EXPECT_EQ("PATCH:test", read_body(patch));
  13555. }
  13556. // stream::Delete tests
  13557. TEST_F(StreamApiTest, Delete) {
  13558. httplib::Client cli(HOST, PORT);
  13559. auto del1 = httplib::stream::Delete(cli, "/resource");
  13560. EXPECT_EQ("Deleted", read_body(del1));
  13561. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13562. EXPECT_EQ("Deleted:data", read_body(del2));
  13563. }
  13564. // stream::Head/Options tests
  13565. TEST_F(StreamApiTest, HeadAndOptions) {
  13566. httplib::Client cli(HOST, PORT);
  13567. auto head = httplib::stream::Head(cli, "/head-test");
  13568. EXPECT_TRUE(head.is_valid());
  13569. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13570. auto opts = httplib::stream::Options(cli, "/options");
  13571. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13572. }
  13573. // SSL stream::* tests
  13574. #ifdef CPPHTTPLIB_SSL_ENABLED
  13575. class SSLStreamApiTest : public ::testing::Test {
  13576. protected:
  13577. void SetUp() override {
  13578. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13579. res.set_content("Hello SSL!", "text/plain");
  13580. });
  13581. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13582. res.set_content(req.body, "text/plain");
  13583. });
  13584. port_ = svr_.bind_to_any_port("127.0.0.1");
  13585. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13586. svr_.wait_until_ready();
  13587. }
  13588. void TearDown() override {
  13589. svr_.stop();
  13590. if (thread_.joinable()) thread_.join();
  13591. }
  13592. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13593. std::thread thread_;
  13594. int port_ = 0;
  13595. };
  13596. TEST_F(SSLStreamApiTest, GetAndPost) {
  13597. httplib::SSLClient cli("127.0.0.1", port_);
  13598. cli.enable_server_certificate_verification(false);
  13599. auto get = httplib::stream::Get(cli, "/hello");
  13600. EXPECT_EQ("Hello SSL!", read_body(get));
  13601. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13602. EXPECT_EQ("test", read_body(post));
  13603. }
  13604. #endif
  13605. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13606. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13607. // BodyReader
  13608. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13609. // Test that read timeout during streaming is detected
  13610. // Use a large content-length response where server delays mid-stream
  13611. Server svr;
  13612. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13613. // Send a large response with delay in the middle
  13614. res.set_content_provider(
  13615. 1000, // content_length
  13616. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13617. if (offset < 100) {
  13618. // Send first 100 bytes immediately
  13619. std::string data(100, 'A');
  13620. sink.write(data.c_str(), data.size());
  13621. return true;
  13622. }
  13623. // Then delay longer than client timeout
  13624. std::this_thread::sleep_for(std::chrono::seconds(3));
  13625. std::string data(900, 'B');
  13626. sink.write(data.c_str(), data.size());
  13627. return true;
  13628. });
  13629. });
  13630. auto port = 8091;
  13631. std::thread t([&]() { svr.listen("localhost", port); });
  13632. svr.wait_until_ready();
  13633. Client cli("localhost", port);
  13634. cli.set_read_timeout(1, 0); // 1 second timeout
  13635. auto handle = cli.open_stream("GET", "/slow-stream");
  13636. ASSERT_TRUE(handle.is_valid());
  13637. char buf[256];
  13638. ssize_t total = 0;
  13639. ssize_t n;
  13640. bool got_error = false;
  13641. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13642. total += n;
  13643. }
  13644. if (n < 0) {
  13645. got_error = true;
  13646. // Should be timeout or read error
  13647. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13648. handle.get_read_error() == Error::Read)
  13649. << "Actual error: " << to_string(handle.get_read_error());
  13650. }
  13651. // Either we got an error, or we got less data than expected
  13652. EXPECT_TRUE(got_error || total < 1000)
  13653. << "Expected timeout but got all " << total << " bytes";
  13654. svr.stop();
  13655. t.join();
  13656. }
  13657. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13658. // Test connection closed detection via BodyReader
  13659. Server svr;
  13660. std::atomic<bool> close_now{false};
  13661. svr.Get("/will-close", [&](const Request &, Response &res) {
  13662. res.set_content_provider(
  13663. 10000, // Large content_length that we won't fully send
  13664. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13665. if (offset < 100) {
  13666. std::string data(100, 'X');
  13667. sink.write(data.c_str(), data.size());
  13668. return true;
  13669. }
  13670. // Wait for signal then abort
  13671. while (!close_now) {
  13672. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13673. }
  13674. return false; // Abort - server will close connection
  13675. });
  13676. });
  13677. auto port = 8092;
  13678. std::thread t([&]() { svr.listen("localhost", port); });
  13679. svr.wait_until_ready();
  13680. Client cli("localhost", port);
  13681. auto handle = cli.open_stream("GET", "/will-close");
  13682. ASSERT_TRUE(handle.is_valid());
  13683. char buf[256];
  13684. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13685. EXPECT_GT(n, 0) << "First read should succeed";
  13686. // Signal server to close
  13687. close_now = true;
  13688. // Keep reading until error or EOF
  13689. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13690. // Keep reading
  13691. }
  13692. // Should get an error since content_length wasn't satisfied
  13693. if (n < 0) {
  13694. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13695. handle.get_read_error() == Error::Read)
  13696. << "Actual error: " << to_string(handle.get_read_error());
  13697. }
  13698. svr.stop();
  13699. t.join();
  13700. }
  13701. #ifdef CPPHTTPLIB_SSL_ENABLED
  13702. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13703. // Test that read timeout during SSL streaming is detected
  13704. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13705. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13706. res.set_content_provider(
  13707. 1000, "text/plain",
  13708. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13709. if (offset < 100) {
  13710. std::string data(100, 'A');
  13711. sink.write(data.c_str(), data.size());
  13712. return true;
  13713. }
  13714. std::this_thread::sleep_for(std::chrono::seconds(3));
  13715. std::string data(900, 'B');
  13716. sink.write(data.c_str(), data.size());
  13717. return true;
  13718. });
  13719. });
  13720. auto port = 8093;
  13721. std::thread t([&]() { svr.listen("localhost", port); });
  13722. svr.wait_until_ready();
  13723. SSLClient cli("localhost", port);
  13724. cli.enable_server_certificate_verification(false);
  13725. cli.set_read_timeout(1, 0); // 1 second timeout
  13726. auto handle = cli.open_stream("GET", "/slow-stream");
  13727. ASSERT_TRUE(handle.is_valid());
  13728. char buf[256];
  13729. ssize_t total = 0;
  13730. ssize_t n;
  13731. bool got_error = false;
  13732. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13733. total += n;
  13734. }
  13735. if (n < 0) {
  13736. got_error = true;
  13737. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13738. handle.get_read_error() == Error::Read)
  13739. << "Actual error: " << to_string(handle.get_read_error());
  13740. }
  13741. EXPECT_TRUE(got_error || total < 1000)
  13742. << "Expected timeout but got all " << total << " bytes";
  13743. svr.stop();
  13744. t.join();
  13745. }
  13746. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13747. // Test SSL connection closed detection
  13748. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13749. std::atomic<bool> close_now{false};
  13750. svr.Get("/will-close", [&](const Request &, Response &res) {
  13751. res.set_content_provider(
  13752. 10000, "text/plain",
  13753. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13754. if (offset < 100) {
  13755. std::string data(100, 'X');
  13756. sink.write(data.c_str(), data.size());
  13757. return true;
  13758. }
  13759. while (!close_now) {
  13760. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13761. }
  13762. return false;
  13763. });
  13764. });
  13765. auto port = 8094;
  13766. std::thread t([&]() { svr.listen("localhost", port); });
  13767. svr.wait_until_ready();
  13768. SSLClient cli("localhost", port);
  13769. cli.enable_server_certificate_verification(false);
  13770. auto handle = cli.open_stream("GET", "/will-close");
  13771. ASSERT_TRUE(handle.is_valid());
  13772. char buf[256];
  13773. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13774. EXPECT_GT(n, 0);
  13775. // Signal server to close
  13776. close_now = true;
  13777. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13778. // Keep reading
  13779. }
  13780. if (n < 0) {
  13781. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13782. handle.get_read_error() == Error::Read)
  13783. << "Actual error: " << to_string(handle.get_read_error());
  13784. }
  13785. svr.stop();
  13786. t.join();
  13787. }
  13788. #endif
  13789. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13790. using namespace httplib;
  13791. // Create a test file
  13792. const char *fname = "etag_testfile.txt";
  13793. const char *content = "etag-content";
  13794. {
  13795. std::ofstream ofs(fname);
  13796. ofs << content;
  13797. ASSERT_TRUE(ofs.good());
  13798. }
  13799. Server svr;
  13800. svr.set_mount_point("/static", ".");
  13801. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13802. svr.wait_until_ready();
  13803. Client cli(HOST, PORT);
  13804. // First request: should get 200 with ETag header
  13805. auto res1 = cli.Get("/static/etag_testfile.txt");
  13806. ASSERT_TRUE(res1);
  13807. ASSERT_EQ(200, res1->status);
  13808. ASSERT_TRUE(res1->has_header("ETag"));
  13809. std::string etag = res1->get_header_value("ETag");
  13810. EXPECT_FALSE(etag.empty());
  13811. // Verify ETag format: W/"hex-hex"
  13812. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13813. EXPECT_EQ('W', etag[0]);
  13814. EXPECT_EQ('/', etag[1]);
  13815. EXPECT_EQ('"', etag[2]);
  13816. EXPECT_EQ('"', etag.back());
  13817. // Exact match: expect 304 Not Modified
  13818. Headers h2 = {{"If-None-Match", etag}};
  13819. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13820. ASSERT_TRUE(res2);
  13821. EXPECT_EQ(304, res2->status);
  13822. // Wildcard match: expect 304 Not Modified
  13823. Headers h3 = {{"If-None-Match", "*"}};
  13824. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13825. ASSERT_TRUE(res3);
  13826. EXPECT_EQ(304, res3->status);
  13827. // Non-matching ETag: expect 200
  13828. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13829. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13830. ASSERT_TRUE(res4);
  13831. EXPECT_EQ(200, res4->status);
  13832. // Multiple ETags with one matching: expect 304
  13833. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13834. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13835. ASSERT_TRUE(res5);
  13836. EXPECT_EQ(304, res5->status);
  13837. svr.stop();
  13838. t.join();
  13839. std::remove(fname);
  13840. }
  13841. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13842. using namespace httplib;
  13843. Server svr;
  13844. svr.set_mount_point("/static", ".");
  13845. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13846. svr.wait_until_ready();
  13847. Client cli(HOST, PORT);
  13848. // Send If-None-Match: * to a non-existent file
  13849. Headers h = {{"If-None-Match", "*"}};
  13850. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13851. ASSERT_TRUE(res);
  13852. EXPECT_EQ(404, res->status);
  13853. svr.stop();
  13854. t.join();
  13855. }
  13856. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13857. using namespace httplib;
  13858. // Create a test file
  13859. const char *fname = "etag_boundary_testfile.txt";
  13860. const char *content = "boundary-test";
  13861. {
  13862. std::ofstream ofs(fname);
  13863. ofs << content;
  13864. ASSERT_TRUE(ofs.good());
  13865. }
  13866. Server svr;
  13867. svr.set_mount_point("/static", ".");
  13868. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13869. svr.wait_until_ready();
  13870. Client cli(HOST, PORT);
  13871. // Get the actual ETag
  13872. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13873. ASSERT_TRUE(res1);
  13874. ASSERT_EQ(200, res1->status);
  13875. ASSERT_TRUE(res1->has_header("ETag"));
  13876. std::string etag = res1->get_header_value("ETag");
  13877. // Test 1: Very long ETag value (longer than actual ETag)
  13878. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13879. Headers h1 = {{"If-None-Match", "W/"
  13880. "\"very-long-etag-value-that-is-much-longer-"
  13881. "than-the-actual-etag-value\""}};
  13882. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13883. ASSERT_TRUE(res2);
  13884. EXPECT_EQ(200, res2->status); // Should not match
  13885. // Test 2: Long string followed by wildcard
  13886. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13887. // string)
  13888. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13889. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13890. ASSERT_TRUE(res3);
  13891. EXPECT_EQ(304, res3->status); // Should match on "*"
  13892. // Test 3: Wildcard followed by long string
  13893. // Should match on "*" immediately and return 304
  13894. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13895. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13896. ASSERT_TRUE(res4);
  13897. EXPECT_EQ(304, res4->status); // Should match on "*"
  13898. // Test 4: Multiple long non-matching values
  13899. // Should NOT match and return 200 (test that all comparisons are safe)
  13900. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13901. "W/\"second-long-non-matching-value\", "
  13902. "W/\"third-long-non-matching-value\""}};
  13903. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13904. ASSERT_TRUE(res5);
  13905. EXPECT_EQ(200, res5->status); // Should not match
  13906. // Test 5: Single character that is not "*" (edge case)
  13907. Headers h5 = {{"If-None-Match", "X"}};
  13908. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13909. ASSERT_TRUE(res6);
  13910. EXPECT_EQ(200, res6->status); // Should not match
  13911. svr.stop();
  13912. t.join();
  13913. std::remove(fname);
  13914. }
  13915. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13916. using namespace httplib;
  13917. // Create a test file
  13918. const char *fname = "ims_testfile.txt";
  13919. const char *content = "if-modified-since-test";
  13920. {
  13921. std::ofstream ofs(fname);
  13922. ofs << content;
  13923. ASSERT_TRUE(ofs.good());
  13924. }
  13925. Server svr;
  13926. svr.set_mount_point("/static", ".");
  13927. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13928. svr.wait_until_ready();
  13929. Client cli(HOST, PORT);
  13930. // First request: should get 200 with Last-Modified header
  13931. auto res1 = cli.Get("/static/ims_testfile.txt");
  13932. ASSERT_TRUE(res1);
  13933. ASSERT_EQ(200, res1->status);
  13934. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13935. std::string last_modified = res1->get_header_value("Last-Modified");
  13936. EXPECT_FALSE(last_modified.empty());
  13937. // If-Modified-Since with same time: expect 304
  13938. Headers h2 = {{"If-Modified-Since", last_modified}};
  13939. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13940. ASSERT_TRUE(res2);
  13941. EXPECT_EQ(304, res2->status);
  13942. // If-Modified-Since with future time: expect 304
  13943. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13944. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13945. ASSERT_TRUE(res3);
  13946. EXPECT_EQ(304, res3->status);
  13947. // If-Modified-Since with past time: expect 200
  13948. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13949. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13950. ASSERT_TRUE(res4);
  13951. EXPECT_EQ(200, res4->status);
  13952. // If-None-Match takes precedence over If-Modified-Since
  13953. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13954. ASSERT_TRUE(res1->has_header("ETag"));
  13955. std::string etag = res1->get_header_value("ETag");
  13956. Headers h5 = {{"If-None-Match", etag},
  13957. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13958. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13959. ASSERT_TRUE(res5);
  13960. EXPECT_EQ(304, res5->status);
  13961. svr.stop();
  13962. t.join();
  13963. std::remove(fname);
  13964. }
  13965. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13966. using namespace httplib;
  13967. Server svr;
  13968. // Endpoint that returns compressible content
  13969. svr.Get("/compressible", [](const Request &, Response &res) {
  13970. // Return a large enough body to trigger compression
  13971. std::string body(1000, 'a');
  13972. res.set_content(body, "text/plain");
  13973. });
  13974. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13975. svr.wait_until_ready();
  13976. Client cli(HOST, PORT);
  13977. // Request with gzip support: should get Vary header when compressed
  13978. cli.set_compress(true);
  13979. auto res1 = cli.Get("/compressible");
  13980. ASSERT_TRUE(res1);
  13981. EXPECT_EQ(200, res1->status);
  13982. // If Content-Encoding is set, Vary should also be set
  13983. if (res1->has_header("Content-Encoding")) {
  13984. EXPECT_TRUE(res1->has_header("Vary"));
  13985. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13986. }
  13987. // Request without Accept-Encoding header: should not have compression
  13988. Headers h_no_compress;
  13989. auto res2 = cli.Get("/compressible", h_no_compress);
  13990. ASSERT_TRUE(res2);
  13991. EXPECT_EQ(200, res2->status);
  13992. // Verify Vary header is present when compression is applied
  13993. // (the exact behavior depends on server configuration)
  13994. svr.stop();
  13995. t.join();
  13996. }
  13997. TEST(ETagTest, IfRangeWithETag) {
  13998. using namespace httplib;
  13999. // Create a test file with known content
  14000. const char *fname = "if_range_testfile.txt";
  14001. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14002. {
  14003. std::ofstream ofs(fname);
  14004. ofs << content;
  14005. ASSERT_TRUE(ofs.good());
  14006. }
  14007. Server svr;
  14008. svr.set_mount_point("/static", ".");
  14009. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14010. svr.wait_until_ready();
  14011. Client cli(HOST, PORT);
  14012. // First request: get ETag
  14013. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14014. ASSERT_TRUE(res1);
  14015. ASSERT_EQ(200, res1->status);
  14016. ASSERT_TRUE(res1->has_header("ETag"));
  14017. std::string etag = res1->get_header_value("ETag");
  14018. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14019. // Since our server generates weak ETags (W/"..."), If-Range with our
  14020. // ETag should NOT result in partial content - it should return full content.
  14021. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14022. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14023. ASSERT_TRUE(res2);
  14024. // Weak ETag in If-Range -> full content (200), not partial (206)
  14025. EXPECT_EQ(200, res2->status);
  14026. EXPECT_EQ(content, res2->body);
  14027. EXPECT_FALSE(res2->has_header("Content-Range"));
  14028. // Range request with non-matching If-Range (ETag): should get 200 (full
  14029. // content)
  14030. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14031. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14032. ASSERT_TRUE(res3);
  14033. EXPECT_EQ(200, res3->status);
  14034. EXPECT_EQ(content, res3->body);
  14035. EXPECT_FALSE(res3->has_header("Content-Range"));
  14036. // Range request with strong ETag (hypothetical - our server doesn't generate
  14037. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14038. // should return full content)
  14039. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14040. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14041. ASSERT_TRUE(res4);
  14042. EXPECT_EQ(200, res4->status);
  14043. EXPECT_EQ(content, res4->body);
  14044. EXPECT_FALSE(res4->has_header("Content-Range"));
  14045. svr.stop();
  14046. t.join();
  14047. std::remove(fname);
  14048. }
  14049. TEST(ETagTest, IfRangeWithDate) {
  14050. using namespace httplib;
  14051. // Create a test file
  14052. const char *fname = "if_range_date_testfile.txt";
  14053. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14054. {
  14055. std::ofstream ofs(fname);
  14056. ofs << content;
  14057. ASSERT_TRUE(ofs.good());
  14058. }
  14059. Server svr;
  14060. svr.set_mount_point("/static", ".");
  14061. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14062. svr.wait_until_ready();
  14063. Client cli(HOST, PORT);
  14064. // First request: get Last-Modified
  14065. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14066. ASSERT_TRUE(res1);
  14067. ASSERT_EQ(200, res1->status);
  14068. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14069. std::string last_modified = res1->get_header_value("Last-Modified");
  14070. // Range request with matching If-Range (date): should get 206
  14071. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14072. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14073. ASSERT_TRUE(res2);
  14074. EXPECT_EQ(206, res2->status);
  14075. EXPECT_EQ("FGHIJ", res2->body);
  14076. // Range request with old If-Range date: should get 200 (full content)
  14077. Headers h3 = {{"Range", "bytes=5-9"},
  14078. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14079. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14080. ASSERT_TRUE(res3);
  14081. EXPECT_EQ(200, res3->status);
  14082. EXPECT_EQ(content, res3->body);
  14083. // Range request with future If-Range date: should get 206
  14084. Headers h4 = {{"Range", "bytes=0-4"},
  14085. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14086. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14087. ASSERT_TRUE(res4);
  14088. EXPECT_EQ(206, res4->status);
  14089. EXPECT_EQ("ABCDE", res4->body);
  14090. svr.stop();
  14091. t.join();
  14092. std::remove(fname);
  14093. }
  14094. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14095. using namespace httplib;
  14096. const char *fname = "etag_malformed.txt";
  14097. const char *content = "malformed-etag";
  14098. {
  14099. std::ofstream ofs(fname);
  14100. ofs << content;
  14101. ASSERT_TRUE(ofs.good());
  14102. }
  14103. Server svr;
  14104. svr.set_mount_point("/static", ".");
  14105. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14106. svr.wait_until_ready();
  14107. Client cli(HOST, PORT);
  14108. // baseline: should get 200 and an ETag
  14109. auto res1 = cli.Get("/static/etag_malformed.txt");
  14110. ASSERT_TRUE(res1);
  14111. ASSERT_EQ(200, res1->status);
  14112. ASSERT_TRUE(res1->has_header("ETag"));
  14113. // Malformed ETag value (missing quotes) should be treated as non-matching
  14114. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14115. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14116. ASSERT_TRUE(res_bad);
  14117. EXPECT_EQ(200, res_bad->status);
  14118. // Whitespace-only header value should be considered invalid / non-matching
  14119. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14120. "Host: localhost\r\n"
  14121. "If-None-Match: \r\n"
  14122. "Connection: close\r\n"
  14123. "\r\n";
  14124. std::string out;
  14125. ASSERT_TRUE(send_request(5, raw_req, &out));
  14126. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14127. svr.stop();
  14128. t.join();
  14129. std::remove(fname);
  14130. }
  14131. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14132. using namespace httplib;
  14133. const char *fname = "ims_invalid_format.txt";
  14134. const char *content = "ims-bad-format";
  14135. {
  14136. std::ofstream ofs(fname);
  14137. ofs << content;
  14138. ASSERT_TRUE(ofs.good());
  14139. }
  14140. Server svr;
  14141. svr.set_mount_point("/static", ".");
  14142. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14143. svr.wait_until_ready();
  14144. Client cli(HOST, PORT);
  14145. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14146. ASSERT_TRUE(res1);
  14147. ASSERT_EQ(200, res1->status);
  14148. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14149. // If-Modified-Since with invalid format should not result in 304
  14150. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14151. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14152. ASSERT_TRUE(res_bad);
  14153. EXPECT_EQ(200, res_bad->status);
  14154. // If-Range with invalid date format should be treated as mismatch -> full
  14155. // content (200)
  14156. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14157. {"If-Range", "invalid-date"}};
  14158. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14159. ASSERT_TRUE(res_ifrange);
  14160. EXPECT_EQ(200, res_ifrange->status);
  14161. svr.stop();
  14162. t.join();
  14163. std::remove(fname);
  14164. }
  14165. TEST(ETagTest, IfRangeWithMalformedETag) {
  14166. using namespace httplib;
  14167. const char *fname = "ifrange_malformed.txt";
  14168. const std::string content = "0123456789";
  14169. {
  14170. std::ofstream ofs(fname);
  14171. ofs << content;
  14172. ASSERT_TRUE(ofs.good());
  14173. }
  14174. Server svr;
  14175. svr.set_mount_point("/static", ".");
  14176. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14177. svr.wait_until_ready();
  14178. Client cli(HOST, PORT);
  14179. // First request: get ETag
  14180. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14181. ASSERT_TRUE(res1);
  14182. ASSERT_EQ(200, res1->status);
  14183. ASSERT_TRUE(res1->has_header("ETag"));
  14184. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14185. // full content (200)
  14186. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14187. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14188. ASSERT_TRUE(res2);
  14189. EXPECT_EQ(200, res2->status);
  14190. EXPECT_EQ(content, res2->body);
  14191. svr.stop();
  14192. t.join();
  14193. std::remove(fname);
  14194. }
  14195. TEST(ETagTest, ExtremeLargeDateValues) {
  14196. using namespace httplib;
  14197. const char *fname = "ims_extreme_date.txt";
  14198. const char *content = "ims-extreme-date";
  14199. {
  14200. std::ofstream ofs(fname);
  14201. ofs << content;
  14202. ASSERT_TRUE(ofs.good());
  14203. }
  14204. Server svr;
  14205. svr.set_mount_point("/static", ".");
  14206. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14207. svr.wait_until_ready();
  14208. Client cli(HOST, PORT);
  14209. auto res1 = cli.Get(std::string("/static/") + fname);
  14210. ASSERT_TRUE(res1);
  14211. ASSERT_EQ(200, res1->status);
  14212. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14213. // Extremely large year that may overflow date parsing routines.
  14214. Headers h_large_date = {
  14215. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14216. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14217. ASSERT_TRUE(res_bad);
  14218. // Expect server to treat this as invalid/mismatch and return full content
  14219. EXPECT_EQ(200, res_bad->status);
  14220. // If-Range with extremely large date should be treated as mismatch -> full
  14221. // content (200)
  14222. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14223. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14224. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14225. ASSERT_TRUE(res_ifrange);
  14226. EXPECT_EQ(200, res_ifrange->status);
  14227. svr.stop();
  14228. t.join();
  14229. std::remove(fname);
  14230. }
  14231. TEST(ETagTest, NegativeFileModificationTime) {
  14232. using namespace httplib;
  14233. const char *fname = "ims_negative_mtime.txt";
  14234. const std::string content = "negative-mtime";
  14235. {
  14236. std::ofstream ofs(fname);
  14237. ofs << content;
  14238. ASSERT_TRUE(ofs.good());
  14239. }
  14240. // Try to set file mtime to a negative value. This may fail on some
  14241. // platforms/filesystems; if it fails, the test will still verify server
  14242. // behaves safely by performing a regular conditional request.
  14243. #if defined(__APPLE__) || defined(__linux__)
  14244. bool set_negative = false;
  14245. do {
  14246. struct timeval times[2];
  14247. // access time: now
  14248. times[0].tv_sec = time(nullptr);
  14249. times[0].tv_usec = 0;
  14250. // modification time: negative (e.g., -1)
  14251. times[1].tv_sec = -1;
  14252. times[1].tv_usec = 0;
  14253. if (utimes(fname, times) == 0) { set_negative = true; }
  14254. } while (0);
  14255. #else
  14256. bool set_negative = false;
  14257. #endif
  14258. Server svr;
  14259. svr.set_mount_point("/static", ".");
  14260. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14261. svr.wait_until_ready();
  14262. Client cli(HOST, PORT);
  14263. auto res1 = cli.Get(std::string("/static/") + fname);
  14264. ASSERT_TRUE(res1);
  14265. ASSERT_EQ(200, res1->status);
  14266. bool has_last_modified = res1->has_header("Last-Modified");
  14267. std::string last_modified;
  14268. if (has_last_modified) {
  14269. last_modified = res1->get_header_value("Last-Modified");
  14270. }
  14271. if (set_negative) {
  14272. // If we successfully set a negative mtime, ensure server returns a
  14273. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14274. // with an old date and ensure server handles it without crash.
  14275. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14276. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14277. ASSERT_TRUE(res2);
  14278. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14279. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14280. } else {
  14281. // Could not set negative mtime on this platform; fall back to verifying
  14282. // that normal invalid/malformed dates are treated safely (non-304).
  14283. Headers h_bad_date = {
  14284. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14285. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14286. ASSERT_TRUE(res_bad);
  14287. EXPECT_EQ(200, res_bad->status);
  14288. }
  14289. svr.stop();
  14290. t.join();
  14291. std::remove(fname);
  14292. }
  14293. //==============================================================================
  14294. // SSE Parsing Tests
  14295. //==============================================================================
  14296. class SSEParsingTest : public ::testing::Test {
  14297. protected:
  14298. // Test helper that mimics SSE parsing behavior
  14299. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14300. int &retry_ms) {
  14301. // Blank line signals end of event
  14302. if (line.empty() || line == "\r") { return true; }
  14303. // Lines starting with ':' are comments (ignored)
  14304. if (!line.empty() && line[0] == ':') { return false; }
  14305. // Find the colon separator
  14306. auto colon_pos = line.find(':');
  14307. if (colon_pos == std::string::npos) {
  14308. // Line with no colon is treated as field name with empty value
  14309. return false;
  14310. }
  14311. std::string field = line.substr(0, colon_pos);
  14312. std::string value;
  14313. // Value starts after colon, skip optional single space
  14314. if (colon_pos + 1 < line.size()) {
  14315. size_t value_start = colon_pos + 1;
  14316. if (line[value_start] == ' ') { value_start++; }
  14317. value = line.substr(value_start);
  14318. // Remove trailing \r if present
  14319. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14320. }
  14321. // Handle known fields
  14322. if (field == "event") {
  14323. msg.event = value;
  14324. } else if (field == "data") {
  14325. // Multiple data lines are concatenated with newlines
  14326. if (!msg.data.empty()) { msg.data += "\n"; }
  14327. msg.data += value;
  14328. } else if (field == "id") {
  14329. // Empty id is valid (clears the last event ID)
  14330. msg.id = value;
  14331. } else if (field == "retry") {
  14332. // Parse retry interval in milliseconds
  14333. {
  14334. int v = 0;
  14335. auto res =
  14336. detail::from_chars(value.data(), value.data() + value.size(), v);
  14337. if (res.ec == std::errc{}) { retry_ms = v; }
  14338. }
  14339. }
  14340. // Unknown fields are ignored per SSE spec
  14341. return false;
  14342. }
  14343. };
  14344. // Test: Single-line data
  14345. TEST_F(SSEParsingTest, SingleLineData) {
  14346. sse::SSEMessage msg;
  14347. int retry_ms = 3000;
  14348. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14349. EXPECT_EQ(msg.data, "hello");
  14350. EXPECT_EQ(msg.event, "message");
  14351. // Blank line ends event
  14352. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14353. }
  14354. // Test: Multi-line data
  14355. TEST_F(SSEParsingTest, MultiLineData) {
  14356. sse::SSEMessage msg;
  14357. int retry_ms = 3000;
  14358. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14359. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14360. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14361. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14362. }
  14363. // Test: Custom event types
  14364. TEST_F(SSEParsingTest, CustomEventType) {
  14365. sse::SSEMessage msg;
  14366. int retry_ms = 3000;
  14367. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14368. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14369. EXPECT_EQ(msg.event, "update");
  14370. EXPECT_EQ(msg.data, "payload");
  14371. }
  14372. // Test: Event ID handling
  14373. TEST_F(SSEParsingTest, EventIdHandling) {
  14374. sse::SSEMessage msg;
  14375. int retry_ms = 3000;
  14376. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14377. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14378. EXPECT_EQ(msg.id, "12345");
  14379. }
  14380. // Test: Empty event ID (clears last event ID)
  14381. TEST_F(SSEParsingTest, EmptyEventId) {
  14382. sse::SSEMessage msg;
  14383. msg.id = "previous";
  14384. int retry_ms = 3000;
  14385. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14386. EXPECT_EQ(msg.id, "");
  14387. }
  14388. // Test: Retry field parsing
  14389. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14390. sse::SSEMessage msg;
  14391. int retry_ms = 3000;
  14392. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14393. EXPECT_EQ(retry_ms, 5000);
  14394. }
  14395. // Test: Invalid retry value
  14396. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14397. sse::SSEMessage msg;
  14398. int retry_ms = 3000;
  14399. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14400. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14401. }
  14402. // Test: Comments (lines starting with :)
  14403. TEST_F(SSEParsingTest, CommentsIgnored) {
  14404. sse::SSEMessage msg;
  14405. int retry_ms = 3000;
  14406. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14407. EXPECT_EQ(msg.data, "");
  14408. EXPECT_EQ(msg.event, "message");
  14409. }
  14410. // Test: Colon in value
  14411. TEST_F(SSEParsingTest, ColonInValue) {
  14412. sse::SSEMessage msg;
  14413. int retry_ms = 3000;
  14414. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14415. EXPECT_EQ(msg.data, "hello:world:test");
  14416. }
  14417. // Test: Line with no colon (field name only)
  14418. TEST_F(SSEParsingTest, FieldNameOnly) {
  14419. sse::SSEMessage msg;
  14420. int retry_ms = 3000;
  14421. // According to SSE spec, this is treated as field name with empty value
  14422. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14423. // Since we don't recognize "data" without colon, data should be empty
  14424. EXPECT_EQ(msg.data, "");
  14425. }
  14426. // Test: Trailing \r handling
  14427. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14428. sse::SSEMessage msg;
  14429. int retry_ms = 3000;
  14430. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14431. EXPECT_EQ(msg.data, "hello");
  14432. }
  14433. // Test: Unknown fields ignored
  14434. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14435. sse::SSEMessage msg;
  14436. int retry_ms = 3000;
  14437. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14438. EXPECT_EQ(msg.data, "");
  14439. EXPECT_EQ(msg.event, "message");
  14440. }
  14441. // Test: Space after colon is optional
  14442. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14443. sse::SSEMessage msg1, msg2;
  14444. int retry_ms = 3000;
  14445. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14446. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14447. EXPECT_EQ(msg1.data, "hello");
  14448. EXPECT_EQ(msg2.data, "hello");
  14449. }
  14450. // Test: SSEMessage clear
  14451. TEST_F(SSEParsingTest, MessageClear) {
  14452. sse::SSEMessage msg;
  14453. msg.event = "custom";
  14454. msg.data = "some data";
  14455. msg.id = "123";
  14456. msg.clear();
  14457. EXPECT_EQ(msg.event, "message");
  14458. EXPECT_EQ(msg.data, "");
  14459. EXPECT_EQ(msg.id, "");
  14460. }
  14461. // Test: Complete event parsing
  14462. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14463. sse::SSEMessage msg;
  14464. int retry_ms = 3000;
  14465. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14466. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14467. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14468. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14469. // Blank line ends event
  14470. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14471. EXPECT_EQ(msg.event, "notification");
  14472. EXPECT_EQ(msg.id, "evt-42");
  14473. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14474. EXPECT_EQ(retry_ms, 1000);
  14475. }
  14476. //==============================================================================
  14477. // Integration Tests with Server
  14478. //==============================================================================
  14479. class SSEIntegrationTest : public ::testing::Test {
  14480. protected:
  14481. void SetUp() override {
  14482. stop_server_.store(false);
  14483. events_.clear();
  14484. server_ = httplib::detail::make_unique<Server>();
  14485. setup_server();
  14486. start_server();
  14487. }
  14488. void TearDown() override {
  14489. stop_server_.store(true);
  14490. event_cv_.notify_all();
  14491. server_->stop();
  14492. if (server_thread_.joinable()) { server_thread_.join(); }
  14493. }
  14494. void setup_server() {
  14495. // Simple SSE endpoint
  14496. server_->Get("/events", [this](const Request &req, Response &res) {
  14497. auto last_id = req.get_header_value("Last-Event-ID");
  14498. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14499. res.set_chunked_content_provider(
  14500. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14501. std::unique_lock<std::mutex> lock(event_mutex_);
  14502. if (event_cv_.wait_for(
  14503. lock, std::chrono::milliseconds(200), [this] {
  14504. return !events_.empty() || stop_server_.load();
  14505. })) {
  14506. if (stop_server_.load()) { return false; }
  14507. if (!events_.empty()) {
  14508. std::string event = events_.front();
  14509. events_.erase(events_.begin());
  14510. sink.write(event.data(), event.size());
  14511. return true;
  14512. }
  14513. }
  14514. return !stop_server_.load();
  14515. });
  14516. });
  14517. // Endpoint that returns error
  14518. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14519. res.status = 500;
  14520. res.set_content("Internal Server Error", "text/plain");
  14521. });
  14522. // Endpoint for custom event types
  14523. server_->Get("/custom-events", [](const Request &, Response &res) {
  14524. res.set_chunked_content_provider(
  14525. "text/event-stream", [](size_t offset, DataSink &sink) {
  14526. if (offset == 0) {
  14527. std::string event = "event: update\ndata: updated\n\n"
  14528. "event: delete\ndata: deleted\n\n";
  14529. sink.write(event.data(), event.size());
  14530. }
  14531. return false; // End stream after sending
  14532. });
  14533. });
  14534. }
  14535. void start_server() {
  14536. port_ = server_->bind_to_any_port(HOST);
  14537. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14538. // Wait for server to start
  14539. while (!server_->is_running()) {
  14540. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14541. }
  14542. }
  14543. int get_port() const { return port_; }
  14544. void send_event(const std::string &event) {
  14545. std::lock_guard<std::mutex> lock(event_mutex_);
  14546. events_.push_back(event);
  14547. event_cv_.notify_all();
  14548. }
  14549. std::unique_ptr<Server> server_;
  14550. std::thread server_thread_;
  14551. std::mutex event_mutex_;
  14552. std::condition_variable event_cv_;
  14553. std::vector<std::string> events_;
  14554. std::atomic<bool> stop_server_{false};
  14555. std::string last_received_event_id_;
  14556. int port_ = 0;
  14557. };
  14558. // Test: Successful connection and on_open callback
  14559. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14560. // Add a simple endpoint that sends one event and closes
  14561. server_->Get("/simple-event", [](const Request &, Response &res) {
  14562. res.set_chunked_content_provider(
  14563. "text/event-stream", [](size_t offset, DataSink &sink) {
  14564. if (offset == 0) {
  14565. std::string event = "data: hello\n\n";
  14566. sink.write(event.data(), event.size());
  14567. }
  14568. return false; // Close stream after sending
  14569. });
  14570. });
  14571. Client client("localhost", get_port());
  14572. sse::SSEClient sse(client, "/simple-event");
  14573. std::atomic<bool> open_called{false};
  14574. std::atomic<bool> message_received{false};
  14575. sse.on_open([&open_called]() { open_called.store(true); });
  14576. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14577. if (msg.data == "hello") { message_received.store(true); }
  14578. });
  14579. sse.set_reconnect_interval(100);
  14580. sse.set_max_reconnect_attempts(1);
  14581. // Start async
  14582. sse.start_async();
  14583. // Wait for message to be processed
  14584. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14585. sse.stop();
  14586. EXPECT_TRUE(open_called.load());
  14587. EXPECT_TRUE(message_received.load());
  14588. }
  14589. // Test: on_message callback
  14590. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14591. // Endpoint that sends multiple events then closes
  14592. server_->Get("/multi-event", [](const Request &, Response &res) {
  14593. res.set_chunked_content_provider(
  14594. "text/event-stream", [](size_t offset, DataSink &sink) {
  14595. if (offset == 0) {
  14596. std::string events = "data: message1\n\ndata: message2\n\n";
  14597. sink.write(events.data(), events.size());
  14598. }
  14599. return false;
  14600. });
  14601. });
  14602. Client client("localhost", get_port());
  14603. sse::SSEClient sse(client, "/multi-event");
  14604. std::vector<std::string> received_messages;
  14605. std::mutex messages_mutex;
  14606. sse.on_message([&](const sse::SSEMessage &msg) {
  14607. std::lock_guard<std::mutex> lock(messages_mutex);
  14608. received_messages.push_back(msg.data);
  14609. });
  14610. sse.set_reconnect_interval(100);
  14611. sse.set_max_reconnect_attempts(1);
  14612. sse.start_async();
  14613. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14614. sse.stop();
  14615. std::lock_guard<std::mutex> lock(messages_mutex);
  14616. EXPECT_GE(received_messages.size(), 2u);
  14617. if (received_messages.size() >= 2) {
  14618. EXPECT_EQ(received_messages[0], "message1");
  14619. EXPECT_EQ(received_messages[1], "message2");
  14620. }
  14621. }
  14622. // Test: on_event for specific types
  14623. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14624. Client client("localhost", get_port());
  14625. sse::SSEClient sse(client, "/custom-events");
  14626. std::atomic<bool> update_received{false};
  14627. std::atomic<bool> delete_received{false};
  14628. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14629. if (msg.data == "updated") { update_received.store(true); }
  14630. });
  14631. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14632. if (msg.data == "deleted") { delete_received.store(true); }
  14633. });
  14634. sse.set_max_reconnect_attempts(1);
  14635. sse.start_async();
  14636. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14637. sse.stop();
  14638. EXPECT_TRUE(update_received.load());
  14639. EXPECT_TRUE(delete_received.load());
  14640. }
  14641. // Test: on_error callback on connection failure
  14642. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14643. // Connect to a non-existent port
  14644. Client client("localhost", 59999);
  14645. sse::SSEClient sse(client, "/events");
  14646. std::atomic<bool> error_called{false};
  14647. Error received_error = Error::Success;
  14648. sse.on_error([&](Error err) {
  14649. error_called.store(true);
  14650. received_error = err;
  14651. });
  14652. sse.set_reconnect_interval(50);
  14653. sse.set_max_reconnect_attempts(1);
  14654. sse.start_async();
  14655. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14656. sse.stop();
  14657. EXPECT_TRUE(error_called.load());
  14658. EXPECT_NE(received_error, Error::Success);
  14659. }
  14660. // Test: Last-Event-ID header sent on reconnect
  14661. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14662. // Endpoint that sends event with ID
  14663. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14664. res.set_chunked_content_provider(
  14665. "text/event-stream", [](size_t offset, DataSink &sink) {
  14666. if (offset == 0) {
  14667. std::string event = "id: evt-123\ndata: test\n\n";
  14668. sink.write(event.data(), event.size());
  14669. }
  14670. return false;
  14671. });
  14672. });
  14673. Client client("localhost", get_port());
  14674. sse::SSEClient sse(client, "/event-with-id");
  14675. std::atomic<bool> id_received{false};
  14676. sse.on_message([&](const sse::SSEMessage &msg) {
  14677. if (!msg.id.empty()) { id_received.store(true); }
  14678. });
  14679. sse.set_reconnect_interval(100);
  14680. sse.set_max_reconnect_attempts(1);
  14681. sse.start_async();
  14682. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14683. sse.stop();
  14684. EXPECT_TRUE(id_received.load());
  14685. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14686. }
  14687. // Test: Manual stop
  14688. TEST_F(SSEIntegrationTest, ManualStop) {
  14689. // Endpoint that sends one event and stays open briefly
  14690. std::atomic<bool> handler_running{true};
  14691. server_->Get("/stay-open", [&handler_running](const Request &,
  14692. Response &res) {
  14693. res.set_chunked_content_provider(
  14694. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14695. if (offset == 0) {
  14696. std::string event = "data: connected\n\n";
  14697. sink.write(event.data(), event.size());
  14698. }
  14699. // Keep connection open while handler_running is true
  14700. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14701. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14702. }
  14703. return false;
  14704. });
  14705. });
  14706. Client client("localhost", get_port());
  14707. sse::SSEClient sse(client, "/stay-open");
  14708. std::atomic<bool> connected{false};
  14709. sse.on_open([&connected]() { connected.store(true); });
  14710. sse.set_reconnect_interval(100);
  14711. sse.set_max_reconnect_attempts(1);
  14712. sse.start_async();
  14713. // Wait for connection to establish
  14714. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14715. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14716. }
  14717. EXPECT_TRUE(connected.load());
  14718. EXPECT_TRUE(sse.is_connected());
  14719. // Signal handler to stop
  14720. handler_running.store(false);
  14721. // Stop SSE client
  14722. sse.stop();
  14723. EXPECT_FALSE(sse.is_connected());
  14724. }
  14725. // Test: SSEClient with custom headers
  14726. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14727. // Setup a server endpoint that checks for custom header
  14728. std::atomic<bool> header_received{false};
  14729. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14730. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14731. header_received.store(true);
  14732. }
  14733. res.set_chunked_content_provider("text/event-stream",
  14734. [](size_t, DataSink &) { return false; });
  14735. });
  14736. Client client("localhost", get_port());
  14737. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14738. sse::SSEClient sse(client, "/header-check", headers);
  14739. sse.set_max_reconnect_attempts(1);
  14740. sse.start_async();
  14741. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14742. sse.stop();
  14743. EXPECT_TRUE(header_received.load());
  14744. }
  14745. // Test: Reconnect interval configuration
  14746. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14747. Client client("localhost", get_port());
  14748. sse::SSEClient sse(client, "/events");
  14749. auto &result = sse.set_reconnect_interval(500);
  14750. // Builder pattern should return reference to self
  14751. EXPECT_EQ(&result, &sse);
  14752. }
  14753. // Test: Max reconnect attempts
  14754. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14755. // Connect to non-existent port to force reconnects
  14756. Client client("localhost", 59998);
  14757. sse::SSEClient sse(client, "/events");
  14758. std::atomic<int> error_count{0};
  14759. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14760. sse.set_reconnect_interval(50);
  14761. sse.set_max_reconnect_attempts(2);
  14762. auto start = std::chrono::steady_clock::now();
  14763. sse.start(); // Blocking call
  14764. auto end = std::chrono::steady_clock::now();
  14765. // Should have stopped after 2 failed attempts
  14766. EXPECT_GE(error_count.load(), 2);
  14767. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14768. auto duration =
  14769. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14770. #ifdef _WIN32
  14771. // Windows is much slower for socket connection failures
  14772. EXPECT_LT(duration.count(), 7000);
  14773. #else
  14774. EXPECT_LT(duration.count(), 1000);
  14775. #endif
  14776. }
  14777. // Test: Multi-line data in integration
  14778. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14779. // Endpoint with multi-line data
  14780. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14781. res.set_chunked_content_provider(
  14782. "text/event-stream", [](size_t offset, DataSink &sink) {
  14783. if (offset == 0) {
  14784. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14785. sink.write(event.data(), event.size());
  14786. }
  14787. return false;
  14788. });
  14789. });
  14790. Client client("localhost", get_port());
  14791. sse::SSEClient sse(client, "/multiline-data");
  14792. std::string received_data;
  14793. std::mutex data_mutex;
  14794. sse.on_message([&](const sse::SSEMessage &msg) {
  14795. std::lock_guard<std::mutex> lock(data_mutex);
  14796. received_data = msg.data;
  14797. });
  14798. sse.set_reconnect_interval(100);
  14799. sse.set_max_reconnect_attempts(1);
  14800. sse.start_async();
  14801. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14802. sse.stop();
  14803. std::lock_guard<std::mutex> lock(data_mutex);
  14804. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14805. }
  14806. // Test: Auto-reconnect after server disconnection
  14807. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14808. std::atomic<int> connection_count{0};
  14809. std::atomic<int> message_count{0};
  14810. // Endpoint that sends one event and closes, forcing reconnect
  14811. server_->Get("/reconnect-test",
  14812. [&connection_count](const Request &, Response &res) {
  14813. connection_count.fetch_add(1);
  14814. res.set_chunked_content_provider(
  14815. "text/event-stream", [](size_t offset, DataSink &sink) {
  14816. if (offset == 0) {
  14817. std::string event = "data: hello\n\n";
  14818. sink.write(event.data(), event.size());
  14819. }
  14820. return false; // Close connection after sending
  14821. });
  14822. });
  14823. Client client("localhost", get_port());
  14824. sse::SSEClient sse(client, "/reconnect-test");
  14825. sse.on_message([&message_count](const sse::SSEMessage &) {
  14826. message_count.fetch_add(1);
  14827. });
  14828. sse.set_reconnect_interval(100);
  14829. sse.set_max_reconnect_attempts(3);
  14830. sse.start_async();
  14831. // Wait long enough for multiple reconnects
  14832. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14833. sse.stop();
  14834. // Should have connected multiple times (initial + reconnects)
  14835. EXPECT_GE(connection_count.load(), 2);
  14836. // Should have received messages from multiple connections
  14837. EXPECT_GE(message_count.load(), 2);
  14838. }
  14839. // Test: Last-Event-ID sent on reconnect
  14840. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14841. std::atomic<int> connection_count{0};
  14842. std::vector<std::string> received_last_event_ids;
  14843. std::mutex id_mutex;
  14844. // Endpoint that checks Last-Event-ID header and sends event with ID
  14845. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14846. int conn = connection_count.fetch_add(1);
  14847. // Capture the Last-Event-ID header from each connection
  14848. {
  14849. std::lock_guard<std::mutex> lock(id_mutex);
  14850. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14851. }
  14852. res.set_chunked_content_provider(
  14853. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14854. if (offset == 0) {
  14855. std::string event =
  14856. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14857. sink.write(event.data(), event.size());
  14858. }
  14859. return false;
  14860. });
  14861. });
  14862. Client client("localhost", get_port());
  14863. sse::SSEClient sse(client, "/reconnect-with-id");
  14864. sse.set_reconnect_interval(100);
  14865. sse.set_max_reconnect_attempts(3);
  14866. sse.start_async();
  14867. // Wait for at least 2 connections
  14868. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14869. sse.stop();
  14870. // Verify behavior
  14871. std::lock_guard<std::mutex> lock(id_mutex);
  14872. EXPECT_GE(received_last_event_ids.size(), 2u);
  14873. // First connection should have no Last-Event-ID
  14874. if (!received_last_event_ids.empty()) {
  14875. EXPECT_EQ(received_last_event_ids[0], "");
  14876. }
  14877. // Second connection should have Last-Event-ID from first connection
  14878. if (received_last_event_ids.size() >= 2) {
  14879. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14880. }
  14881. }
  14882. // Test: set_headers updates headers used on reconnect
  14883. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14884. std::vector<std::string> received_tokens;
  14885. std::mutex token_mutex;
  14886. // Endpoint that captures Authorization header
  14887. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14888. {
  14889. std::lock_guard<std::mutex> lock(token_mutex);
  14890. received_tokens.push_back(req.get_header_value("Authorization"));
  14891. }
  14892. res.set_chunked_content_provider(
  14893. "text/event-stream", [](size_t offset, DataSink &sink) {
  14894. if (offset == 0) {
  14895. std::string event = "data: hello\n\n";
  14896. sink.write(event.data(), event.size());
  14897. }
  14898. return false; // Close connection to trigger reconnect
  14899. });
  14900. });
  14901. Client client("localhost", get_port());
  14902. Headers headers = {{"Authorization", "Bearer old-token"}};
  14903. sse::SSEClient sse(client, "/auth-check", headers);
  14904. // Update headers on each successful connection
  14905. sse.on_open(
  14906. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14907. sse.set_reconnect_interval(100);
  14908. sse.set_max_reconnect_attempts(3);
  14909. sse.start_async();
  14910. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14911. sse.stop();
  14912. std::lock_guard<std::mutex> lock(token_mutex);
  14913. ASSERT_GE(received_tokens.size(), 2u);
  14914. // First connection uses original header
  14915. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14916. // Second connection uses updated header from set_headers
  14917. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14918. }
  14919. // Test: 401 allows reconnection (so on_error can refresh headers)
  14920. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14921. std::atomic<int> connection_count{0};
  14922. // Endpoint: returns 401 on first attempt, 200 on second
  14923. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14924. int conn = connection_count.fetch_add(1);
  14925. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14926. res.status = StatusCode::Unauthorized_401;
  14927. res.set_content("Unauthorized", "text/plain");
  14928. return;
  14929. }
  14930. res.set_chunked_content_provider(
  14931. "text/event-stream", [](size_t offset, DataSink &sink) {
  14932. if (offset == 0) {
  14933. std::string event = "data: authenticated\n\n";
  14934. sink.write(event.data(), event.size());
  14935. }
  14936. return false;
  14937. });
  14938. });
  14939. Client client("localhost", get_port());
  14940. Headers headers = {{"Authorization", "Bearer expired"}};
  14941. sse::SSEClient sse(client, "/auth-retry", headers);
  14942. std::atomic<bool> message_received{false};
  14943. // Refresh token on error
  14944. sse.on_error(
  14945. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14946. sse.on_message([&](const sse::SSEMessage &msg) {
  14947. if (msg.data == "authenticated") { message_received.store(true); }
  14948. });
  14949. sse.set_reconnect_interval(100);
  14950. sse.set_max_reconnect_attempts(3);
  14951. sse.start_async();
  14952. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14953. sse.stop();
  14954. // Should have reconnected after 401 and succeeded with new token
  14955. EXPECT_GE(connection_count.load(), 2);
  14956. EXPECT_TRUE(message_received.load());
  14957. }
  14958. TEST(Issue2318Test, EmptyHostString) {
  14959. {
  14960. httplib::Client cli_empty("", PORT);
  14961. auto res = cli_empty.Get("/");
  14962. ASSERT_FALSE(res);
  14963. EXPECT_EQ(httplib::Error::Connection, res.error());
  14964. }
  14965. {
  14966. httplib::Client cli(" ", PORT);
  14967. auto res = cli.Get("/");
  14968. ASSERT_FALSE(res);
  14969. EXPECT_EQ(httplib::Error::Connection, res.error());
  14970. }
  14971. }
  14972. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14973. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14974. Server svr;
  14975. // Set a small payload limit (1KB)
  14976. svr.set_payload_max_length(1024);
  14977. svr.Post("/test", [&](const Request &req, Response &res) {
  14978. res.set_content("Body size: " + std::to_string(req.body.size()),
  14979. "text/plain");
  14980. });
  14981. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14982. auto se = detail::scope_exit([&] {
  14983. svr.stop();
  14984. listen_thread.join();
  14985. });
  14986. svr.wait_until_ready();
  14987. // Create data that compresses well but exceeds limit when decompressed
  14988. // 8KB of repeated null bytes compresses to a very small size
  14989. std::string original_data(8 * 1024, '\0');
  14990. // Compress the data using gzip
  14991. std::string compressed_data;
  14992. detail::gzip_compressor compressor;
  14993. compressor.compress(original_data.data(), original_data.size(), true,
  14994. [&](const char *data, size_t size) {
  14995. compressed_data.append(data, size);
  14996. return true;
  14997. });
  14998. // Verify compression worked (compressed should be much smaller)
  14999. ASSERT_LT(compressed_data.size(), original_data.size());
  15000. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15001. // Send compressed data with Content-Encoding: gzip
  15002. Client cli(HOST, PORT);
  15003. Headers headers = {{"Content-Encoding", "gzip"}};
  15004. auto res =
  15005. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15006. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15007. ASSERT_TRUE(res);
  15008. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15009. }
  15010. #endif
  15011. // ============================================================================
  15012. // OpenSSL-Specific Tests
  15013. // ============================================================================
  15014. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15015. X509 *readCertificate(const std::string &strFileName) {
  15016. std::ifstream inStream(strFileName);
  15017. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15018. std::istreambuf_iterator<char>());
  15019. if (strCertPEM.empty()) return (nullptr);
  15020. BIO *pbCert = BIO_new(BIO_s_mem());
  15021. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15022. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15023. BIO_free(pbCert);
  15024. return (pCert);
  15025. }
  15026. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15027. std::ifstream inStream(strFileName);
  15028. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15029. std::istreambuf_iterator<char>());
  15030. if (strPrivateKeyPEM.empty()) return (nullptr);
  15031. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15032. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15033. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15034. BIO_free(pbPrivKey);
  15035. return (pPrivateKey);
  15036. }
  15037. TEST(BindServerTest, UpdateCerts) {
  15038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15039. int port = svr.bind_to_any_port("0.0.0.0");
  15040. ASSERT_TRUE(svr.is_valid());
  15041. ASSERT_TRUE(port > 0);
  15042. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15043. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15044. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15045. ASSERT_TRUE(cert != nullptr);
  15046. ASSERT_TRUE(ca_cert != nullptr);
  15047. ASSERT_TRUE(key != nullptr);
  15048. X509_STORE *cert_store = X509_STORE_new();
  15049. X509_STORE_add_cert(cert_store, ca_cert);
  15050. // svr.update_certs(cert, key, cert_store); // deprecated
  15051. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15052. CLIENT_CA_CERT_FILE);
  15053. ASSERT_TRUE(svr.is_valid());
  15054. svr.stop();
  15055. X509_STORE_free(cert_store);
  15056. X509_free(cert);
  15057. X509_free(ca_cert);
  15058. EVP_PKEY_free(key);
  15059. }
  15060. // Test that update_certs() updates client CA list correctly
  15061. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15062. // Start with file-based constructor
  15063. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15064. ASSERT_TRUE(svr.is_valid());
  15065. // Initially no client CA list should be set
  15066. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15067. ASSERT_TRUE(ssl_ctx != nullptr);
  15068. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15069. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15070. EXPECT_EQ(0, count_before);
  15071. // Now update with client CA (PEM string)
  15072. std::string cert_pem, key_pem, ca_pem;
  15073. read_file(SERVER_CERT_FILE, cert_pem);
  15074. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15075. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15076. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15077. ASSERT_TRUE(svr.is_valid());
  15078. // Now client CA list should be set
  15079. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15080. ASSERT_TRUE(ca_list_after != nullptr);
  15081. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15082. }
  15083. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15084. // Test that the file-path SSLServer constructor properly sets the client CA
  15085. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15087. ASSERT_TRUE(svr.is_valid());
  15088. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15089. ASSERT_TRUE(ssl_ctx != nullptr);
  15090. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15091. ASSERT_TRUE(ca_list != nullptr);
  15092. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15093. }
  15094. #endif
  15095. // ============================================================================
  15096. // MbedTLS-Specific Tests
  15097. // ============================================================================
  15098. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15099. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15100. using namespace httplib::tls;
  15101. // Track if callback was invoked
  15102. bool callback_invoked = false;
  15103. // The callback receives void* ctx which is actually MbedTlsContext*
  15104. // We can access the mbedtls_ssl_config via the context
  15105. auto setup_callback = [&callback_invoked](void *ctx) {
  15106. callback_invoked = true;
  15107. // Cast to MbedTlsContext* to access the ssl config
  15108. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15109. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15110. // Use static variables to hold certificate data (simplified for test)
  15111. static mbedtls_x509_crt own_cert;
  15112. static mbedtls_pk_context own_key;
  15113. static mbedtls_x509_crt ca_chain;
  15114. static bool initialized = false;
  15115. if (!initialized) {
  15116. mbedtls_x509_crt_init(&own_cert);
  15117. mbedtls_pk_init(&own_key);
  15118. mbedtls_x509_crt_init(&ca_chain);
  15119. // Load server certificate
  15120. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15121. return false;
  15122. }
  15123. // Load server private key
  15124. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15125. #if MBEDTLS_VERSION_MAJOR >= 3
  15126. ,
  15127. mbedtls_ctr_drbg_random, nullptr
  15128. #endif
  15129. ) != 0) {
  15130. return false;
  15131. }
  15132. // Load CA chain for client verification
  15133. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15134. return false;
  15135. }
  15136. initialized = true;
  15137. }
  15138. // Configure the SSL config
  15139. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15140. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15141. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15142. // Set minimum TLS version using mbedTLS native API
  15143. #if MBEDTLS_VERSION_MAJOR >= 3
  15144. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15145. #else
  15146. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15147. MBEDTLS_SSL_MINOR_VERSION_3);
  15148. #endif
  15149. return true;
  15150. };
  15151. SSLServer svr(setup_callback);
  15152. ASSERT_TRUE(svr.is_valid());
  15153. ASSERT_TRUE(callback_invoked);
  15154. svr.Get("/test", [&](const Request &req, Response &res) {
  15155. res.set_content("test", "text/plain");
  15156. auto cert = req.peer_cert();
  15157. ASSERT_TRUE(static_cast<bool>(cert));
  15158. auto common_name = cert.subject_cn();
  15159. EXPECT_EQ("Common Name", common_name);
  15160. });
  15161. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15162. auto se = detail::scope_exit([&] {
  15163. svr.stop();
  15164. t.join();
  15165. ASSERT_FALSE(svr.is_running());
  15166. });
  15167. svr.wait_until_ready();
  15168. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15169. cli.enable_server_certificate_verification(false);
  15170. cli.set_connection_timeout(30);
  15171. auto res = cli.Get("/test");
  15172. ASSERT_TRUE(res);
  15173. ASSERT_EQ(StatusCode::OK_200, res->status);
  15174. }
  15175. #endif
  15176. // WebSocket Tests
  15177. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15178. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15179. // defining the meaning of these bits has been negotiated.
  15180. auto make_frame = [](uint8_t first_byte) {
  15181. std::string frame;
  15182. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15183. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15184. frame += "Hello";
  15185. return frame;
  15186. };
  15187. // RSV1 set (0x40)
  15188. {
  15189. detail::BufferStream strm;
  15190. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15191. ws::Opcode opcode;
  15192. std::string payload;
  15193. bool fin;
  15194. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15195. false, 1024));
  15196. }
  15197. // RSV2 set (0x20)
  15198. {
  15199. detail::BufferStream strm;
  15200. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15201. ws::Opcode opcode;
  15202. std::string payload;
  15203. bool fin;
  15204. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15205. false, 1024));
  15206. }
  15207. // RSV3 set (0x10)
  15208. {
  15209. detail::BufferStream strm;
  15210. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15211. ws::Opcode opcode;
  15212. std::string payload;
  15213. bool fin;
  15214. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15215. false, 1024));
  15216. }
  15217. // No RSV bits set - should succeed
  15218. {
  15219. detail::BufferStream strm;
  15220. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15221. ws::Opcode opcode;
  15222. std::string payload;
  15223. bool fin;
  15224. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15225. false, 1024));
  15226. EXPECT_EQ(ws::Opcode::Text, opcode);
  15227. EXPECT_EQ("Hello", payload);
  15228. EXPECT_TRUE(fin);
  15229. }
  15230. }
  15231. TEST(WebSocketTest, ControlFrameValidation) {
  15232. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15233. // payload length <= 125.
  15234. // Ping with FIN=0 - must be rejected
  15235. {
  15236. detail::BufferStream strm;
  15237. std::string frame;
  15238. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15239. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15240. strm.write(frame.data(), frame.size());
  15241. ws::Opcode opcode;
  15242. std::string payload;
  15243. bool fin;
  15244. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15245. false, 1024));
  15246. }
  15247. // Close with FIN=0 - must be rejected
  15248. {
  15249. detail::BufferStream strm;
  15250. std::string frame;
  15251. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15252. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15253. strm.write(frame.data(), frame.size());
  15254. ws::Opcode opcode;
  15255. std::string payload;
  15256. bool fin;
  15257. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15258. false, 1024));
  15259. }
  15260. // Ping with payload_len=126 (extended length) - must be rejected
  15261. {
  15262. detail::BufferStream strm;
  15263. std::string frame;
  15264. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15265. frame += static_cast<char>(126); // payload_len=126 (>125)
  15266. frame += static_cast<char>(0x00); // extended length high byte
  15267. frame += static_cast<char>(126); // extended length low byte
  15268. frame += std::string(126, 'x');
  15269. strm.write(frame.data(), frame.size());
  15270. ws::Opcode opcode;
  15271. std::string payload;
  15272. bool fin;
  15273. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15274. false, 1024));
  15275. }
  15276. // Ping with FIN=1 and payload_len=125 - should succeed
  15277. {
  15278. detail::BufferStream strm;
  15279. std::string frame;
  15280. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15281. frame += static_cast<char>(125); // payload_len=125
  15282. frame += std::string(125, 'x');
  15283. strm.write(frame.data(), frame.size());
  15284. ws::Opcode opcode;
  15285. std::string payload;
  15286. bool fin;
  15287. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15288. false, 1024));
  15289. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15290. EXPECT_EQ(125u, payload.size());
  15291. EXPECT_TRUE(fin);
  15292. }
  15293. }
  15294. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15295. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15296. // length MUST be 0.
  15297. // MSB set - must be rejected
  15298. {
  15299. detail::BufferStream strm;
  15300. std::string frame;
  15301. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15302. frame += static_cast<char>(127); // 64-bit extended length
  15303. frame += static_cast<char>(0x80); // MSB set (invalid)
  15304. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15305. strm.write(frame.data(), frame.size());
  15306. ws::Opcode opcode;
  15307. std::string payload;
  15308. bool fin;
  15309. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15310. false, 1024));
  15311. }
  15312. // MSB clear - should pass length parsing (will be rejected by max_len,
  15313. // but that's a different check; use a small length to verify)
  15314. {
  15315. detail::BufferStream strm;
  15316. std::string frame;
  15317. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15318. frame += static_cast<char>(127); // 64-bit extended length
  15319. frame += std::string(7, '\0'); // high bytes = 0
  15320. frame += static_cast<char>(0x03); // length = 3
  15321. frame += "abc";
  15322. strm.write(frame.data(), frame.size());
  15323. ws::Opcode opcode;
  15324. std::string payload;
  15325. bool fin;
  15326. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15327. false, 1024));
  15328. EXPECT_EQ(ws::Opcode::Text, opcode);
  15329. EXPECT_EQ("abc", payload);
  15330. }
  15331. }
  15332. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15333. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15334. // Valid UTF-8
  15335. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15336. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15337. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15338. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15339. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15340. // Invalid UTF-8
  15341. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15342. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15343. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15344. EXPECT_FALSE(
  15345. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15346. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15347. }
  15348. TEST(WebSocketTest, ConnectAndDisconnect) {
  15349. Server svr;
  15350. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15351. std::string msg;
  15352. while (ws.read(msg)) {}
  15353. });
  15354. auto port = svr.bind_to_any_port(HOST);
  15355. std::thread t([&]() { svr.listen_after_bind(); });
  15356. svr.wait_until_ready();
  15357. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15358. ASSERT_TRUE(client.connect());
  15359. EXPECT_TRUE(client.is_open());
  15360. client.close();
  15361. EXPECT_FALSE(client.is_open());
  15362. svr.stop();
  15363. t.join();
  15364. }
  15365. TEST(WebSocketTest, ValidURL) {
  15366. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15367. EXPECT_TRUE(ws1.is_valid());
  15368. ws::WebSocketClient ws2("ws://example.com/path");
  15369. EXPECT_TRUE(ws2.is_valid());
  15370. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15371. EXPECT_TRUE(ws3.is_valid());
  15372. #ifdef CPPHTTPLIB_SSL_ENABLED
  15373. ws::WebSocketClient wss1("wss://example.com/path");
  15374. EXPECT_TRUE(wss1.is_valid());
  15375. ws::WebSocketClient wss2("wss://example.com:443/path");
  15376. EXPECT_TRUE(wss2.is_valid());
  15377. #endif
  15378. }
  15379. TEST(WebSocketTest, InvalidURL) {
  15380. // No scheme
  15381. ws::WebSocketClient ws1("localhost:8080/path");
  15382. EXPECT_FALSE(ws1.is_valid());
  15383. // No path
  15384. ws::WebSocketClient ws2("ws://localhost:8080");
  15385. EXPECT_FALSE(ws2.is_valid());
  15386. // Empty string
  15387. ws::WebSocketClient ws3("");
  15388. EXPECT_FALSE(ws3.is_valid());
  15389. // Missing host
  15390. ws::WebSocketClient ws4("ws://:8080/path");
  15391. EXPECT_FALSE(ws4.is_valid());
  15392. // Port number overflow — should not crash
  15393. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15394. EXPECT_FALSE(ws5.is_valid());
  15395. // Port out of range
  15396. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15397. EXPECT_FALSE(ws6.is_valid());
  15398. }
  15399. TEST(WebSocketTest, UnsupportedScheme) {
  15400. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15401. ws::WebSocketClient ws1("http://localhost:8080/path");
  15402. EXPECT_FALSE(ws1.is_valid());
  15403. ws::WebSocketClient ws2("https://localhost:8080/path");
  15404. EXPECT_FALSE(ws2.is_valid());
  15405. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15406. EXPECT_FALSE(ws3.is_valid());
  15407. #else
  15408. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15409. std::invalid_argument);
  15410. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15411. std::invalid_argument);
  15412. #endif
  15413. }
  15414. TEST(WebSocketTest, ConnectWhenInvalid) {
  15415. ws::WebSocketClient ws("not a valid url");
  15416. EXPECT_FALSE(ws.is_valid());
  15417. EXPECT_FALSE(ws.connect());
  15418. }
  15419. TEST(WebSocketTest, DefaultPort) {
  15420. ws::WebSocketClient ws1("ws://example.com/path");
  15421. EXPECT_TRUE(ws1.is_valid());
  15422. // ws:// defaults to port 80 (verified by successful parse)
  15423. #ifdef CPPHTTPLIB_SSL_ENABLED
  15424. ws::WebSocketClient ws2("wss://example.com/path");
  15425. EXPECT_TRUE(ws2.is_valid());
  15426. // wss:// defaults to port 443 (verified by successful parse)
  15427. #endif
  15428. }
  15429. TEST(WebSocketTest, IPv6LiteralAddress) {
  15430. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15431. EXPECT_TRUE(ws1.is_valid());
  15432. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15433. EXPECT_TRUE(ws2.is_valid());
  15434. }
  15435. TEST(WebSocketTest, ComplexPath) {
  15436. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15437. EXPECT_TRUE(ws1.is_valid());
  15438. ws::WebSocketClient ws2("ws://localhost:8080/");
  15439. EXPECT_TRUE(ws2.is_valid());
  15440. }
  15441. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15442. Server svr;
  15443. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15444. std::string msg;
  15445. while (ws.read(msg)) {}
  15446. });
  15447. auto port = svr.bind_to_any_port(HOST);
  15448. std::thread t([&]() { svr.listen_after_bind(); });
  15449. svr.wait_until_ready();
  15450. auto another_host = "example.com";
  15451. auto wrong_ip = "192.0.2.1";
  15452. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15453. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15454. ASSERT_TRUE(client.connect());
  15455. EXPECT_TRUE(client.is_open());
  15456. client.close();
  15457. svr.stop();
  15458. t.join();
  15459. }
  15460. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15461. Server svr;
  15462. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15463. std::string msg;
  15464. while (ws.read(msg)) {}
  15465. });
  15466. auto port = svr.bind_to_any_port(HOST);
  15467. std::thread t([&]() { svr.listen_after_bind(); });
  15468. svr.wait_until_ready();
  15469. auto wrong_ip = "192.0.2.1";
  15470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15471. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15472. client.set_connection_timeout(1);
  15473. client.set_read_timeout(1);
  15474. client.set_write_timeout(1);
  15475. EXPECT_FALSE(client.connect());
  15476. EXPECT_FALSE(client.is_open());
  15477. svr.stop();
  15478. t.join();
  15479. }
  15480. class WebSocketIntegrationTest : public ::testing::Test {
  15481. protected:
  15482. void SetUp() override {
  15483. server_ = httplib::detail::make_unique<Server>();
  15484. setup_server();
  15485. start_server();
  15486. }
  15487. void TearDown() override {
  15488. server_->stop();
  15489. if (server_thread_.joinable()) { server_thread_.join(); }
  15490. }
  15491. void setup_server() {
  15492. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15493. std::string msg;
  15494. ws::ReadResult ret;
  15495. while ((ret = ws.read(msg))) {
  15496. if (ret == ws::Binary) {
  15497. ws.send(msg.data(), msg.size());
  15498. } else {
  15499. ws.send(msg);
  15500. }
  15501. }
  15502. });
  15503. server_->WebSocket("/ws-echo-string",
  15504. [](const Request &, ws::WebSocket &ws) {
  15505. std::string msg;
  15506. while (ws.read(msg)) {
  15507. ws.send("echo: " + msg);
  15508. }
  15509. });
  15510. server_->WebSocket(
  15511. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15512. // Echo back request metadata
  15513. ws.send("path:" + req.path);
  15514. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15515. std::string msg;
  15516. while (ws.read(msg)) {}
  15517. });
  15518. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15519. std::string msg;
  15520. ws.read(msg); // wait for a message
  15521. ws.close();
  15522. });
  15523. server_->WebSocket("/ws-close-status",
  15524. [](const Request &, ws::WebSocket &ws) {
  15525. std::string msg;
  15526. ws.read(msg); // wait for a message
  15527. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15528. });
  15529. server_->WebSocket(
  15530. "/ws-subprotocol",
  15531. [](const Request &, ws::WebSocket &ws) {
  15532. std::string msg;
  15533. while (ws.read(msg)) {
  15534. ws.send(msg);
  15535. }
  15536. },
  15537. [](const std::vector<std::string> &protocols) -> std::string {
  15538. for (const auto &p : protocols) {
  15539. if (p == "graphql-ws") { return p; }
  15540. }
  15541. return "";
  15542. });
  15543. }
  15544. void start_server() {
  15545. port_ = server_->bind_to_any_port(HOST);
  15546. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15547. server_->wait_until_ready();
  15548. }
  15549. std::unique_ptr<Server> server_;
  15550. std::thread server_thread_;
  15551. int port_ = 0;
  15552. };
  15553. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15554. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15555. "/ws-echo");
  15556. ASSERT_TRUE(client.connect());
  15557. ASSERT_TRUE(client.is_open());
  15558. ASSERT_TRUE(client.send("Hello WebSocket"));
  15559. std::string msg;
  15560. EXPECT_EQ(ws::Text, client.read(msg));
  15561. EXPECT_EQ("Hello WebSocket", msg);
  15562. client.close();
  15563. }
  15564. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15565. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15566. "/ws-echo");
  15567. ASSERT_TRUE(client.connect());
  15568. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15569. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15570. std::string msg;
  15571. EXPECT_EQ(ws::Binary, client.read(msg));
  15572. EXPECT_EQ(binary_data, msg);
  15573. client.close();
  15574. }
  15575. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15576. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15577. "/ws-echo");
  15578. ASSERT_TRUE(client.connect());
  15579. for (int i = 0; i < 10; i++) {
  15580. auto text = "message " + std::to_string(i);
  15581. ASSERT_TRUE(client.send(text));
  15582. std::string msg;
  15583. ASSERT_TRUE(client.read(msg));
  15584. EXPECT_EQ(text, msg);
  15585. }
  15586. client.close();
  15587. }
  15588. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15589. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15590. "/ws-close");
  15591. ASSERT_TRUE(client.connect());
  15592. // Send a message to trigger the server to close
  15593. ASSERT_TRUE(client.send("trigger close"));
  15594. // The server will close, so read should return false
  15595. std::string msg;
  15596. EXPECT_FALSE(client.read(msg));
  15597. EXPECT_FALSE(client.is_open());
  15598. }
  15599. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15600. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15601. "/ws-echo");
  15602. ASSERT_TRUE(client.connect());
  15603. // 128KB message
  15604. std::string large_data(128 * 1024, 'X');
  15605. ASSERT_TRUE(client.send(large_data));
  15606. std::string msg;
  15607. ASSERT_TRUE(client.read(msg));
  15608. EXPECT_EQ(large_data, msg);
  15609. client.close();
  15610. }
  15611. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15613. "/ws-echo");
  15614. ASSERT_TRUE(client.connect());
  15615. const int num_threads = 4;
  15616. std::vector<std::thread> threads;
  15617. std::atomic<int> send_count{0};
  15618. for (int t = 0; t < num_threads; t++) {
  15619. threads.emplace_back([&client, &send_count, t]() {
  15620. for (int i = 0; i < 5; i++) {
  15621. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15622. if (client.send(text)) { send_count++; }
  15623. }
  15624. });
  15625. }
  15626. for (auto &th : threads) {
  15627. th.join();
  15628. }
  15629. int received = 0;
  15630. std::string msg;
  15631. while (received < send_count.load()) {
  15632. if (!client.read(msg)) { break; }
  15633. received++;
  15634. }
  15635. EXPECT_EQ(send_count.load(), received);
  15636. client.close();
  15637. }
  15638. TEST_F(WebSocketIntegrationTest, ReadString) {
  15639. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15640. "/ws-echo-string");
  15641. ASSERT_TRUE(client.connect());
  15642. ASSERT_TRUE(client.send("hello"));
  15643. std::string msg;
  15644. ASSERT_TRUE(client.read(msg));
  15645. EXPECT_EQ("echo: hello", msg);
  15646. ASSERT_TRUE(client.send("world"));
  15647. ASSERT_TRUE(client.read(msg));
  15648. EXPECT_EQ("echo: world", msg);
  15649. client.close();
  15650. }
  15651. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15652. Headers headers = {{"X-Test-Header", "test-value"}};
  15653. ws::WebSocketClient client(
  15654. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15655. ASSERT_TRUE(client.connect());
  15656. std::string msg;
  15657. ASSERT_TRUE(client.read(msg));
  15658. EXPECT_EQ("path:/ws-request-info", msg);
  15659. ASSERT_TRUE(client.read(msg));
  15660. EXPECT_EQ("header:test-value", msg);
  15661. client.close();
  15662. }
  15663. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15664. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15665. "/ws-echo");
  15666. client.set_read_timeout(1, 0); // 1 second
  15667. ASSERT_TRUE(client.connect());
  15668. // Don't send anything — server echo handler waits for a message,
  15669. // so read() should time out and return false.
  15670. std::string msg;
  15671. EXPECT_FALSE(client.read(msg));
  15672. }
  15673. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15674. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15675. "/ws-echo");
  15676. client.set_read_timeout(5, 0);
  15677. ASSERT_TRUE(client.connect());
  15678. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15679. // The server should reject it and close the connection.
  15680. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15681. client.send(oversized);
  15682. // The server's read() should have failed due to payload limit,
  15683. // so our read() should return false (connection closed).
  15684. std::string msg;
  15685. EXPECT_FALSE(client.read(msg));
  15686. }
  15687. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15688. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15689. "/ws-echo");
  15690. client.set_read_timeout(10, 0);
  15691. ASSERT_TRUE(client.connect());
  15692. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15693. // This should succeed.
  15694. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15695. ASSERT_TRUE(client.send(at_limit));
  15696. std::string msg;
  15697. ASSERT_TRUE(client.read(msg));
  15698. EXPECT_EQ(at_limit.size(), msg.size());
  15699. client.close();
  15700. }
  15701. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15703. "/nonexistent");
  15704. EXPECT_FALSE(client.connect());
  15705. EXPECT_FALSE(client.is_open());
  15706. }
  15707. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15708. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15709. "/ws-echo");
  15710. ASSERT_TRUE(client.connect());
  15711. ASSERT_TRUE(client.send(""));
  15712. std::string msg;
  15713. EXPECT_EQ(ws::Text, client.read(msg));
  15714. EXPECT_EQ("", msg);
  15715. client.close();
  15716. }
  15717. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15718. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15719. "/ws-echo");
  15720. // First connection
  15721. ASSERT_TRUE(client.connect());
  15722. ASSERT_TRUE(client.send("first"));
  15723. std::string msg;
  15724. ASSERT_TRUE(client.read(msg));
  15725. EXPECT_EQ("first", msg);
  15726. client.close();
  15727. EXPECT_FALSE(client.is_open());
  15728. // Reconnect using the same client object
  15729. ASSERT_TRUE(client.connect());
  15730. ASSERT_TRUE(client.is_open());
  15731. ASSERT_TRUE(client.send("second"));
  15732. ASSERT_TRUE(client.read(msg));
  15733. EXPECT_EQ("second", msg);
  15734. client.close();
  15735. }
  15736. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15737. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15738. "/ws-close-status");
  15739. ASSERT_TRUE(client.connect());
  15740. // Trigger the server to close with GoingAway status
  15741. ASSERT_TRUE(client.send("trigger"));
  15742. // read() should return false after receiving the close frame
  15743. std::string msg;
  15744. EXPECT_FALSE(client.read(msg));
  15745. EXPECT_FALSE(client.is_open());
  15746. }
  15747. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15748. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15749. "/ws-echo");
  15750. ASSERT_TRUE(client.connect());
  15751. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15752. EXPECT_FALSE(client.is_open());
  15753. }
  15754. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15755. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15756. ws::WebSocketClient client(
  15757. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15758. ASSERT_TRUE(client.connect());
  15759. // Server should have selected graphql-ws
  15760. EXPECT_EQ("graphql-ws", client.subprotocol());
  15761. client.close();
  15762. }
  15763. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15764. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15765. ws::WebSocketClient client(
  15766. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15767. ASSERT_TRUE(client.connect());
  15768. // Server should not have selected any subprotocol
  15769. EXPECT_TRUE(client.subprotocol().empty());
  15770. client.close();
  15771. }
  15772. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15773. // Connect without requesting any subprotocol
  15774. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15775. "/ws-subprotocol");
  15776. ASSERT_TRUE(client.connect());
  15777. EXPECT_TRUE(client.subprotocol().empty());
  15778. client.close();
  15779. }
  15780. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15781. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15782. "/ws-echo");
  15783. client.set_tcp_nodelay(true);
  15784. client.set_connection_timeout(3, 0);
  15785. bool socket_options_called = false;
  15786. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15787. ASSERT_TRUE(client.connect());
  15788. ASSERT_TRUE(client.is_open());
  15789. EXPECT_TRUE(socket_options_called);
  15790. ASSERT_TRUE(client.send("hello"));
  15791. std::string msg;
  15792. auto result = client.read(msg);
  15793. EXPECT_EQ(result, ws::ReadResult::Text);
  15794. EXPECT_EQ(msg, "hello");
  15795. client.close();
  15796. }
  15797. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15798. Server svr;
  15799. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15800. if (!req.has_header("Authorization")) {
  15801. res.status = StatusCode::Unauthorized_401;
  15802. res.set_content("Unauthorized", "text/plain");
  15803. return Server::HandlerResponse::Handled;
  15804. }
  15805. return Server::HandlerResponse::Unhandled;
  15806. });
  15807. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15808. std::string msg;
  15809. while (ws.read(msg)) {
  15810. ws.send(msg);
  15811. }
  15812. });
  15813. auto port = svr.bind_to_any_port("localhost");
  15814. std::thread t([&]() { svr.listen_after_bind(); });
  15815. svr.wait_until_ready();
  15816. // Without Authorization header - should be rejected before upgrade
  15817. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15818. EXPECT_FALSE(client1.connect());
  15819. // With Authorization header - should succeed
  15820. Headers headers = {{"Authorization", "Bearer token123"}};
  15821. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15822. headers);
  15823. ASSERT_TRUE(client2.connect());
  15824. ASSERT_TRUE(client2.send("hello"));
  15825. std::string msg;
  15826. ASSERT_TRUE(client2.read(msg));
  15827. EXPECT_EQ("hello", msg);
  15828. client2.close();
  15829. svr.stop();
  15830. t.join();
  15831. }
  15832. TEST(WebSocketTest, QueryStringInHandshake) {
  15833. Server svr;
  15834. std::mutex mtx;
  15835. std::string received_target;
  15836. std::string received_token;
  15837. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15838. {
  15839. std::lock_guard<std::mutex> lock(mtx);
  15840. received_target = req.target;
  15841. if (req.has_param("token")) {
  15842. received_token = req.get_param_value("token");
  15843. }
  15844. }
  15845. std::string msg;
  15846. while (ws.read(msg)) {
  15847. ws.send(msg);
  15848. }
  15849. });
  15850. auto port = svr.bind_to_any_port("localhost");
  15851. std::thread t([&]() { svr.listen_after_bind(); });
  15852. svr.wait_until_ready();
  15853. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15854. "/ws?token=ABC&session=123");
  15855. ASSERT_TRUE(client.connect());
  15856. // Round-trip ensures the handler has run and captured the request.
  15857. ASSERT_TRUE(client.send("hello"));
  15858. std::string msg;
  15859. ASSERT_TRUE(client.read(msg));
  15860. EXPECT_EQ("hello", msg);
  15861. client.close();
  15862. {
  15863. std::lock_guard<std::mutex> lock(mtx);
  15864. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15865. EXPECT_EQ("ABC", received_token);
  15866. }
  15867. svr.stop();
  15868. t.join();
  15869. }
  15870. TEST(WebSocketTest, HostHeaderInHandshake) {
  15871. Server svr;
  15872. std::mutex mtx;
  15873. std::string received_host;
  15874. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15875. {
  15876. std::lock_guard<std::mutex> lock(mtx);
  15877. received_host = req.get_header_value("Host");
  15878. }
  15879. std::string msg;
  15880. while (ws.read(msg)) {
  15881. ws.send(msg);
  15882. }
  15883. });
  15884. auto port = svr.bind_to_any_port("localhost");
  15885. std::thread t([&]() { svr.listen_after_bind(); });
  15886. svr.wait_until_ready();
  15887. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15888. ASSERT_TRUE(client.connect());
  15889. // Round-trip ensures the handler has run and captured the request.
  15890. ASSERT_TRUE(client.send("hello"));
  15891. std::string msg;
  15892. ASSERT_TRUE(client.read(msg));
  15893. client.close();
  15894. {
  15895. std::lock_guard<std::mutex> lock(mtx);
  15896. // Non-default port must be present in the Host header. Default ports
  15897. // (80/443) are omitted; that logic is covered by
  15898. // MakeHostAndPortStringTest.
  15899. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  15900. }
  15901. svr.stop();
  15902. t.join();
  15903. }
  15904. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15905. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15906. protected:
  15907. void SetUp() override {
  15908. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15909. SERVER_PRIVATE_KEY_FILE);
  15910. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15911. std::string msg;
  15912. ws::ReadResult ret;
  15913. while ((ret = ws.read(msg))) {
  15914. if (ret == ws::Binary) {
  15915. ws.send(msg.data(), msg.size());
  15916. } else {
  15917. ws.send(msg);
  15918. }
  15919. }
  15920. });
  15921. port_ = server_->bind_to_any_port(HOST);
  15922. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15923. server_->wait_until_ready();
  15924. }
  15925. void TearDown() override {
  15926. server_->stop();
  15927. if (server_thread_.joinable()) { server_thread_.join(); }
  15928. }
  15929. std::unique_ptr<SSLServer> server_;
  15930. std::thread server_thread_;
  15931. int port_ = 0;
  15932. };
  15933. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15934. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15935. "/ws-echo");
  15936. client.enable_server_certificate_verification(false);
  15937. ASSERT_TRUE(client.connect());
  15938. ASSERT_TRUE(client.is_open());
  15939. ASSERT_TRUE(client.send("Hello WSS"));
  15940. std::string msg;
  15941. EXPECT_EQ(ws::Text, client.read(msg));
  15942. EXPECT_EQ("Hello WSS", msg);
  15943. client.close();
  15944. }
  15945. #endif
  15946. #ifdef CPPHTTPLIB_SSL_ENABLED
  15947. class WebSocketSSLCATest : public ::testing::Test {
  15948. protected:
  15949. void SetUp() override {
  15950. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  15951. SERVER_PRIVATE_KEY_FILE);
  15952. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15953. std::string msg;
  15954. while (ws.read(msg)) {
  15955. ws.send(msg);
  15956. }
  15957. });
  15958. port_ = server_->bind_to_any_port("127.0.0.1");
  15959. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15960. server_->wait_until_ready();
  15961. }
  15962. void TearDown() override {
  15963. server_->stop();
  15964. if (server_thread_.joinable()) { server_thread_.join(); }
  15965. }
  15966. std::string url() const {
  15967. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  15968. }
  15969. std::unique_ptr<SSLServer> server_;
  15970. std::thread server_thread_;
  15971. int port_ = 0;
  15972. };
  15973. // A custom CA loaded as PEM verifies the server with full certificate
  15974. // verification enabled
  15975. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  15976. ws::WebSocketClient client(url());
  15977. std::string cert;
  15978. read_file(SERVER_CERT2_FILE, cert);
  15979. client.load_ca_cert_store(cert.c_str(), cert.size());
  15980. ASSERT_TRUE(client.connect());
  15981. ASSERT_TRUE(client.send("hello"));
  15982. std::string msg;
  15983. EXPECT_EQ(ws::Text, client.read(msg));
  15984. EXPECT_EQ("hello", msg);
  15985. client.close();
  15986. }
  15987. // A custom CA that does not cover the server must fail verification (the
  15988. // custom CA is exclusive; system certs are not loaded alongside it)
  15989. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  15990. ws::WebSocketClient client(url());
  15991. std::string cert;
  15992. read_file(CLIENT_CA_CERT_FILE, cert);
  15993. client.load_ca_cert_store(cert.c_str(), cert.size());
  15994. ASSERT_FALSE(client.connect());
  15995. }
  15996. // Regression test: reconnecting with a native custom CA store used to reuse
  15997. // a store handle the previous TLS context had already freed (use-after-free
  15998. // under the OpenSSL backend). The context now lives as long as the client.
  15999. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16000. ws::WebSocketClient client(url());
  16001. std::string cert;
  16002. read_file(SERVER_CERT2_FILE, cert);
  16003. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16004. ASSERT_TRUE(client.connect());
  16005. client.close();
  16006. ASSERT_TRUE(client.connect());
  16007. ASSERT_TRUE(client.send("again"));
  16008. std::string msg;
  16009. EXPECT_EQ(ws::Text, client.read(msg));
  16010. EXPECT_EQ("again", msg);
  16011. client.close();
  16012. }
  16013. // Regression test: a certificate with a trusted chain but no identity match
  16014. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16015. // verification entirely for IP hosts, so this connection succeeded there.
  16016. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16017. // chain verification while the identity check must still fail.
  16018. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16019. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16020. ASSERT_TRUE(svr.is_valid());
  16021. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16022. std::string msg;
  16023. while (ws.read(msg)) {
  16024. ws.send(msg);
  16025. }
  16026. });
  16027. auto port = svr.bind_to_any_port("127.0.0.1");
  16028. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16029. auto se = detail::scope_exit([&] {
  16030. svr.stop();
  16031. t.join();
  16032. });
  16033. svr.wait_until_ready();
  16034. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16035. "/echo");
  16036. std::string cert;
  16037. read_file(SERVER_CERT_FILE, cert);
  16038. client.load_ca_cert_store(cert.c_str(), cert.size());
  16039. ASSERT_FALSE(client.connect());
  16040. }
  16041. #endif
  16042. #if !defined(_WIN32)
  16043. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16044. auto secret_dir = std::string("./symlink_test_secret");
  16045. auto served_dir = std::string("./symlink_test_served");
  16046. auto secret_file = secret_dir + "/secret.txt";
  16047. auto symlink_path = served_dir + "/escape";
  16048. // Setup: create directories and files
  16049. mkdir(secret_dir.c_str(), 0755);
  16050. mkdir(served_dir.c_str(), 0755);
  16051. {
  16052. std::ofstream ofs(secret_file);
  16053. ofs << "SECRET_DATA";
  16054. }
  16055. // Create symlink using absolute path so it resolves correctly
  16056. #ifdef PATH_MAX
  16057. char abs_secret[PATH_MAX];
  16058. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16059. #else
  16060. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16061. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16062. ASSERT_NE(nullptr, abs_secret);
  16063. #endif
  16064. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16065. auto se = detail::scope_exit([&] {
  16066. unlink(symlink_path.c_str());
  16067. unlink(secret_file.c_str());
  16068. rmdir(served_dir.c_str());
  16069. rmdir(secret_dir.c_str());
  16070. });
  16071. Server svr;
  16072. svr.set_mount_point("/", served_dir);
  16073. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16074. auto se2 = detail::scope_exit([&] {
  16075. svr.stop();
  16076. listen_thread.join();
  16077. });
  16078. svr.wait_until_ready();
  16079. Client cli("localhost", PORT);
  16080. // Symlink pointing outside base dir should be blocked
  16081. auto res = cli.Get("/escape/secret.txt");
  16082. ASSERT_TRUE(res);
  16083. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16084. }
  16085. #endif
  16086. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16087. // A GET request with Content-Length to a static file handler must have its
  16088. // body drained before the keep-alive connection is reused. Otherwise the
  16089. // unread body bytes are interpreted as the next HTTP request.
  16090. //
  16091. // The body is sent AFTER receiving the first response (as in the original
  16092. // PoC) so that the stream_line_reader cannot buffer it together with the
  16093. // headers of the first request.
  16094. Server svr;
  16095. svr.set_mount_point("/", "./www");
  16096. std::atomic<int> smuggled_count(0);
  16097. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16098. smuggled_count++;
  16099. res.set_content("oops", "text/plain");
  16100. });
  16101. auto port = svr.bind_to_any_port("localhost");
  16102. thread t = thread([&] { svr.listen_after_bind(); });
  16103. auto se = detail::scope_exit([&] {
  16104. svr.stop();
  16105. t.join();
  16106. });
  16107. svr.wait_until_ready();
  16108. auto error = Error::Success;
  16109. auto sock = detail::create_client_socket(
  16110. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16111. /*connection_timeout_sec=*/2, 0,
  16112. /*read_timeout_sec=*/2, 0,
  16113. /*write_timeout_sec=*/2, 0, std::string(), error);
  16114. ASSERT_NE(INVALID_SOCKET, sock);
  16115. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16116. // The "smuggled" request will be sent as the body of the outer GET
  16117. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16118. "Host: localhost\r\n"
  16119. "Connection: close\r\n"
  16120. "\r\n";
  16121. // Step 1: Send only the outer request headers (no body yet)
  16122. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16123. "Host: localhost\r\n"
  16124. "Content-Length: " +
  16125. std::to_string(smuggled.size()) +
  16126. "\r\n"
  16127. "\r\n";
  16128. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16129. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16130. // Step 2: Read the first response (server serves file without reading body)
  16131. std::string first_response;
  16132. char buf[4096];
  16133. for (;;) {
  16134. auto n = recv(sock, buf, sizeof(buf), 0);
  16135. if (n <= 0) break;
  16136. first_response.append(buf, static_cast<size_t>(n));
  16137. // Stop once we have a complete response (headers + body)
  16138. auto hdr_end = first_response.find("\r\n\r\n");
  16139. if (hdr_end != std::string::npos) {
  16140. // Check for Content-Length to know when the body is complete
  16141. auto cl_pos = first_response.find("Content-Length:");
  16142. if (cl_pos != std::string::npos) {
  16143. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16144. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16145. auto cl = std::stoul(
  16146. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16147. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16148. } else {
  16149. break; // No Content-Length, assume headers-only response
  16150. }
  16151. }
  16152. }
  16153. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16154. // Step 3: Now send the body, which looks like a new HTTP request.
  16155. // On a vulnerable server the keep-alive loop reads this as a second request.
  16156. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16157. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16158. // Step 4: Try to read a second response (should NOT exist after fix)
  16159. std::string second_response;
  16160. for (;;) {
  16161. auto n = recv(sock, buf, sizeof(buf), 0);
  16162. if (n <= 0) break;
  16163. second_response.append(buf, static_cast<size_t>(n));
  16164. }
  16165. // The smuggled request must NOT have been processed
  16166. EXPECT_EQ(0, smuggled_count.load());
  16167. }
  16168. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16169. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16170. // must be rejected with 400 Bad Request.
  16171. Server svr;
  16172. svr.Post("/test", [&](const Request &, Response &res) {
  16173. res.set_content("ok", "text/plain");
  16174. });
  16175. thread t = thread([&] { svr.listen(HOST, PORT); });
  16176. auto se = detail::scope_exit([&] {
  16177. svr.stop();
  16178. t.join();
  16179. ASSERT_FALSE(svr.is_running());
  16180. });
  16181. svr.wait_until_ready();
  16182. // Exact "chunked"
  16183. {
  16184. auto req = "POST /test HTTP/1.1\r\n"
  16185. "Host: localhost\r\n"
  16186. "Content-Length: 5\r\n"
  16187. "Transfer-Encoding: chunked\r\n"
  16188. "Connection: close\r\n"
  16189. "\r\n"
  16190. "hello";
  16191. std::string response;
  16192. ASSERT_TRUE(send_request(1, req, &response));
  16193. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16194. response.substr(0, response.find("\r\n")));
  16195. }
  16196. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16197. {
  16198. auto req = "POST /test HTTP/1.1\r\n"
  16199. "Host: localhost\r\n"
  16200. "Content-Length: 5\r\n"
  16201. "Transfer-Encoding: gzip, chunked\r\n"
  16202. "Connection: close\r\n"
  16203. "\r\n"
  16204. "hello";
  16205. std::string response;
  16206. ASSERT_TRUE(send_request(1, req, &response));
  16207. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16208. response.substr(0, response.find("\r\n")));
  16209. }
  16210. }
  16211. // Regression for issue #2450: a DELETE without Content-Length on a
  16212. // keep-alive connection must not let the post-response drain consume the
  16213. // next request's bytes.
  16214. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16215. Server svr;
  16216. std::atomic<int> delete_count(0);
  16217. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16218. delete_count++;
  16219. res.status = StatusCode::NoContent_204;
  16220. });
  16221. auto port = svr.bind_to_any_port(HOST);
  16222. thread t = thread([&] { svr.listen_after_bind(); });
  16223. auto se = detail::scope_exit([&] {
  16224. svr.stop();
  16225. t.join();
  16226. });
  16227. svr.wait_until_ready();
  16228. auto error = Error::Success;
  16229. auto sock = detail::create_client_socket(
  16230. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16231. /*connection_timeout_sec=*/2, 0,
  16232. /*read_timeout_sec=*/2, 0,
  16233. /*write_timeout_sec=*/2, 0, std::string(), error);
  16234. ASSERT_NE(INVALID_SOCKET, sock);
  16235. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16236. auto send_request_and_read_response = [&](const std::string &req,
  16237. std::string &out) -> bool {
  16238. auto sent = send(sock, req.data(), req.size(), 0);
  16239. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16240. char buf[4096];
  16241. for (;;) {
  16242. auto n = recv(sock, buf, sizeof(buf), 0);
  16243. if (n <= 0) { return !out.empty(); }
  16244. out.append(buf, static_cast<size_t>(n));
  16245. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16246. }
  16247. };
  16248. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16249. "Host: localhost\r\n"
  16250. "\r\n";
  16251. std::string resp1;
  16252. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16253. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16254. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16255. "Host: localhost\r\n"
  16256. "Connection: close\r\n"
  16257. "\r\n";
  16258. std::string resp2;
  16259. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16260. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16261. EXPECT_EQ(2, delete_count.load());
  16262. }
  16263. namespace no_proxy_test {
  16264. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16265. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16266. // calling listen().
  16267. class ScopedServer {
  16268. public:
  16269. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16270. ~ScopedServer() {
  16271. svr_.stop();
  16272. if (th_.joinable()) { th_.join(); }
  16273. }
  16274. Server &svr() { return svr_; }
  16275. int port() const { return port_; }
  16276. void listen() {
  16277. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16278. svr_.wait_until_ready();
  16279. }
  16280. private:
  16281. Server svr_;
  16282. std::thread th_;
  16283. int port_ = 0;
  16284. };
  16285. class ProxyAndTargetServers {
  16286. public:
  16287. ProxyAndTargetServers() {
  16288. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16289. proxy_hits_++;
  16290. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16291. res.set_content("via-proxy", "text/plain");
  16292. });
  16293. target_.Get(".*", [this](const Request &req, Response &res) {
  16294. target_hits_++;
  16295. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16296. res.set_content("direct", "text/plain");
  16297. });
  16298. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16299. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16300. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16301. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16302. proxy_mock_.wait_until_ready();
  16303. target_.wait_until_ready();
  16304. }
  16305. ~ProxyAndTargetServers() {
  16306. proxy_mock_.stop();
  16307. target_.stop();
  16308. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16309. if (target_thread_.joinable()) { target_thread_.join(); }
  16310. }
  16311. Server &proxy_mock() { return proxy_mock_; }
  16312. Server &target() { return target_; }
  16313. int proxy_port() const { return proxy_port_; }
  16314. int target_port() const { return target_port_; }
  16315. int proxy_hits() const { return proxy_hits_.load(); }
  16316. int target_hits() const { return target_hits_.load(); }
  16317. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16318. void reset_counters() {
  16319. proxy_hits_ = 0;
  16320. target_hits_ = 0;
  16321. last_had_proxy_authz_ = false;
  16322. }
  16323. private:
  16324. Server proxy_mock_;
  16325. Server target_;
  16326. std::thread proxy_thread_;
  16327. std::thread target_thread_;
  16328. int proxy_port_ = 0;
  16329. int target_port_ = 0;
  16330. std::atomic<int> proxy_hits_{0};
  16331. std::atomic<int> target_hits_{0};
  16332. std::atomic<bool> last_had_proxy_authz_{false};
  16333. };
  16334. inline std::unique_ptr<Client> make_client(const std::string &host,
  16335. ProxyAndTargetServers &s) {
  16336. auto cli = detail::make_unique<Client>(host, s.target_port());
  16337. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16338. cli->set_proxy("127.0.0.1", s.proxy_port());
  16339. return cli;
  16340. }
  16341. } // namespace no_proxy_test
  16342. using no_proxy_test::make_client;
  16343. using no_proxy_test::ProxyAndTargetServers;
  16344. TEST(NoProxyTest, ExactHostnameBypasses) {
  16345. ProxyAndTargetServers s;
  16346. auto cli = make_client("example.com", s);
  16347. cli->set_no_proxy({"example.com"});
  16348. auto res = cli->Get("/");
  16349. ASSERT_TRUE(res);
  16350. EXPECT_EQ(0, s.proxy_hits());
  16351. EXPECT_EQ(1, s.target_hits());
  16352. }
  16353. TEST(NoProxyTest, SubdomainBypasses) {
  16354. ProxyAndTargetServers s;
  16355. auto cli = make_client("foo.example.com", s);
  16356. cli->set_no_proxy({"example.com"});
  16357. auto res = cli->Get("/");
  16358. ASSERT_TRUE(res);
  16359. EXPECT_EQ(0, s.proxy_hits());
  16360. EXPECT_EQ(1, s.target_hits());
  16361. }
  16362. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16363. // Regression guard: "evilexample.com" must not be considered a subdomain
  16364. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16365. // check would let traffic bypass the proxy and leak credentials direct
  16366. // to the attacker host.
  16367. ProxyAndTargetServers s;
  16368. auto cli = make_client("evilexample.com", s);
  16369. cli->set_no_proxy({"example.com"});
  16370. auto res = cli->Get("/");
  16371. ASSERT_TRUE(res);
  16372. EXPECT_GE(s.proxy_hits(), 1);
  16373. EXPECT_EQ(0, s.target_hits());
  16374. }
  16375. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16376. ProxyAndTargetServers s;
  16377. auto cli = make_client("example.com.evil.com", s);
  16378. cli->set_no_proxy({"example.com"});
  16379. auto res = cli->Get("/");
  16380. ASSERT_TRUE(res);
  16381. EXPECT_GE(s.proxy_hits(), 1);
  16382. EXPECT_EQ(0, s.target_hits());
  16383. }
  16384. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16385. ProxyAndTargetServers s;
  16386. auto cli = make_client("example.com", s);
  16387. cli->set_no_proxy({".example.com"});
  16388. auto res = cli->Get("/");
  16389. ASSERT_TRUE(res);
  16390. EXPECT_EQ(0, s.proxy_hits());
  16391. EXPECT_EQ(1, s.target_hits());
  16392. }
  16393. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16394. ProxyAndTargetServers s;
  16395. auto cli = make_client("Example.COM", s);
  16396. cli->set_no_proxy({"EXAMPLE.com"});
  16397. auto res = cli->Get("/");
  16398. ASSERT_TRUE(res);
  16399. EXPECT_EQ(0, s.proxy_hits());
  16400. EXPECT_EQ(1, s.target_hits());
  16401. }
  16402. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16403. ProxyAndTargetServers s;
  16404. auto cli = make_client("example.com.", s);
  16405. cli->set_no_proxy({"example.com"});
  16406. auto res = cli->Get("/");
  16407. ASSERT_TRUE(res);
  16408. EXPECT_EQ(0, s.proxy_hits());
  16409. EXPECT_EQ(1, s.target_hits());
  16410. }
  16411. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16412. // Trailing dots must be normalized on BOTH sides — host and entry.
  16413. // An implementation that only strips the host-side trailing dot would
  16414. // fail to match host "example.com" against entry "example.com." because
  16415. // a literal substring search would compare 11 chars against 12.
  16416. ProxyAndTargetServers s;
  16417. auto cli = make_client("example.com", s);
  16418. cli->set_no_proxy({"example.com."});
  16419. auto res = cli->Get("/");
  16420. ASSERT_TRUE(res);
  16421. EXPECT_EQ(0, s.proxy_hits());
  16422. EXPECT_EQ(1, s.target_hits());
  16423. }
  16424. TEST(NoProxyTest, WildcardBypassesEverything) {
  16425. ProxyAndTargetServers s;
  16426. auto cli = make_client("anything.invalid.test", s);
  16427. cli->set_no_proxy({"*"});
  16428. auto res = cli->Get("/");
  16429. ASSERT_TRUE(res);
  16430. EXPECT_EQ(0, s.proxy_hits());
  16431. EXPECT_EQ(1, s.target_hits());
  16432. }
  16433. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16434. ProxyAndTargetServers s;
  16435. Client cli("127.0.0.1", s.target_port());
  16436. cli.set_proxy("127.0.0.1", s.proxy_port());
  16437. cli.set_no_proxy({"127.0.0.1"});
  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, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16444. ProxyAndTargetServers s;
  16445. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16446. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16447. cli.set_proxy("127.0.0.1", s.proxy_port());
  16448. cli.set_no_proxy({"::1"});
  16449. auto res = cli.Get("/");
  16450. ASSERT_TRUE(res);
  16451. EXPECT_EQ(0, s.proxy_hits());
  16452. EXPECT_EQ(1, s.target_hits());
  16453. }
  16454. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16455. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16456. // must still be recognized as IPv6 for CIDR matching. Implementations
  16457. // that detect IPv6 only when the host begins with '[' would parse the
  16458. // host as a hostname and miss the match.
  16459. ProxyAndTargetServers s;
  16460. Client cli("fe80::1", s.target_port());
  16461. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16462. cli.set_proxy("127.0.0.1", s.proxy_port());
  16463. cli.set_no_proxy({"fe80::/10"});
  16464. auto res = cli.Get("/");
  16465. ASSERT_TRUE(res);
  16466. EXPECT_EQ(0, s.proxy_hits());
  16467. EXPECT_EQ(1, s.target_hits());
  16468. }
  16469. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16470. ProxyAndTargetServers s;
  16471. Client cli("::1", s.target_port());
  16472. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16473. cli.set_proxy("127.0.0.1", s.proxy_port());
  16474. cli.set_no_proxy({"[::1]"});
  16475. auto res = cli.Get("/");
  16476. ASSERT_TRUE(res);
  16477. EXPECT_EQ(0, s.proxy_hits());
  16478. EXPECT_EQ(1, s.target_hits());
  16479. }
  16480. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16481. ProxyAndTargetServers s;
  16482. Client cli("fe80::1", s.target_port());
  16483. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16484. cli.set_proxy("127.0.0.1", s.proxy_port());
  16485. cli.set_no_proxy({"[fe80::]/10"});
  16486. auto res = cli.Get("/");
  16487. ASSERT_TRUE(res);
  16488. EXPECT_EQ(0, s.proxy_hits());
  16489. EXPECT_EQ(1, s.target_hits());
  16490. }
  16491. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16492. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16493. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16494. // tricks via address-family conversion.
  16495. ProxyAndTargetServers s;
  16496. Client cli("::ffff:127.0.0.1", s.target_port());
  16497. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16498. cli.set_proxy("127.0.0.1", s.proxy_port());
  16499. cli.set_no_proxy({"127.0.0.1"});
  16500. auto res = cli.Get("/");
  16501. ASSERT_TRUE(res);
  16502. EXPECT_GE(s.proxy_hits(), 1);
  16503. EXPECT_EQ(0, s.target_hits());
  16504. }
  16505. TEST(NoProxyTest, IPv4CidrMatch) {
  16506. ProxyAndTargetServers s;
  16507. Client cli("127.0.0.1", s.target_port());
  16508. cli.set_proxy("127.0.0.1", s.proxy_port());
  16509. cli.set_no_proxy({"127.0.0.0/8"});
  16510. auto res = cli.Get("/");
  16511. ASSERT_TRUE(res);
  16512. EXPECT_EQ(0, s.proxy_hits());
  16513. EXPECT_EQ(1, s.target_hits());
  16514. }
  16515. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16516. ProxyAndTargetServers s;
  16517. Client cli("127.0.0.1", s.target_port());
  16518. cli.set_proxy("127.0.0.1", s.proxy_port());
  16519. cli.set_no_proxy({"10.0.0.0/8"});
  16520. auto res = cli.Get("/");
  16521. ASSERT_TRUE(res);
  16522. EXPECT_GE(s.proxy_hits(), 1);
  16523. EXPECT_EQ(0, s.target_hits());
  16524. }
  16525. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16526. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16527. // IPv4 target matches.
  16528. ProxyAndTargetServers s;
  16529. Client cli("127.0.0.1", s.target_port());
  16530. cli.set_proxy("127.0.0.1", s.proxy_port());
  16531. cli.set_no_proxy({"0.0.0.0/0"});
  16532. auto res = cli.Get("/");
  16533. ASSERT_TRUE(res);
  16534. EXPECT_EQ(0, s.proxy_hits());
  16535. EXPECT_EQ(1, s.target_hits());
  16536. }
  16537. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  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.1"});
  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, MalformedCidrPrefixIsDropped) {
  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({"127.0.0.0/33"});
  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, TrailingSlashCidrIsRejected) {
  16558. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16559. ProxyAndTargetServers s;
  16560. Client cli("127.0.0.1", s.target_port());
  16561. cli.set_proxy("127.0.0.1", s.proxy_port());
  16562. cli.set_no_proxy({"127.0.0.1/"});
  16563. auto res = cli.Get("/");
  16564. ASSERT_TRUE(res);
  16565. EXPECT_GE(s.proxy_hits(), 1);
  16566. EXPECT_EQ(0, s.target_hits());
  16567. }
  16568. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16569. ProxyAndTargetServers s;
  16570. auto cli = make_client("internal.corp", s);
  16571. cli->set_proxy_basic_auth("u", "p");
  16572. cli->set_no_proxy({"internal.corp"});
  16573. auto res = cli->Get("/");
  16574. ASSERT_TRUE(res);
  16575. EXPECT_EQ(1, s.target_hits());
  16576. EXPECT_EQ(0, s.proxy_hits());
  16577. EXPECT_FALSE(s.last_had_proxy_authz())
  16578. << "Proxy-Authorization must not be sent direct to the target";
  16579. }
  16580. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16581. ProxyAndTargetServers s;
  16582. auto cli = make_client("public.example", s);
  16583. cli->set_proxy_basic_auth("u", "p");
  16584. cli->set_no_proxy({"internal.corp"}); // does not match
  16585. auto res = cli->Get("/");
  16586. ASSERT_TRUE(res);
  16587. EXPECT_GE(s.proxy_hits(), 1);
  16588. EXPECT_TRUE(s.last_had_proxy_authz());
  16589. }
  16590. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16591. ProxyAndTargetServers s;
  16592. auto cli = make_client("anything.test", s);
  16593. auto res = cli->Get("/");
  16594. ASSERT_TRUE(res);
  16595. EXPECT_GE(s.proxy_hits(), 1);
  16596. EXPECT_EQ(0, s.target_hits());
  16597. }
  16598. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16599. ProxyAndTargetServers s;
  16600. auto cli = make_client("example.com", s);
  16601. cli->set_no_proxy({"example.com:8080"});
  16602. auto res = cli->Get("/");
  16603. ASSERT_TRUE(res);
  16604. EXPECT_GE(s.proxy_hits(), 1);
  16605. EXPECT_EQ(0, s.target_hits());
  16606. }
  16607. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16608. ProxyAndTargetServers s;
  16609. auto cli = make_client("anything.test", s);
  16610. cli->set_no_proxy({"", " ", "\t"});
  16611. auto res = cli->Get("/");
  16612. ASSERT_TRUE(res);
  16613. EXPECT_GE(s.proxy_hits(), 1);
  16614. EXPECT_EQ(0, s.target_hits());
  16615. }
  16616. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16617. // An entry with leading/trailing whitespace must still match — env-style
  16618. // values are commonly pasted with stray spaces and an implementation
  16619. // that feeds the raw token directly to inet_pton would fail to match
  16620. // valid CIDRs because of the spaces.
  16621. ProxyAndTargetServers s;
  16622. Client cli("127.0.0.1", s.target_port());
  16623. cli.set_proxy("127.0.0.1", s.proxy_port());
  16624. cli.set_no_proxy({" 127.0.0.0/8 "});
  16625. auto res = cli.Get("/");
  16626. ASSERT_TRUE(res);
  16627. EXPECT_EQ(0, s.proxy_hits());
  16628. EXPECT_EQ(1, s.target_hits());
  16629. }
  16630. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16631. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16632. // go direct and must NOT carry Proxy-Authorization.
  16633. std::atomic<int> proxy_hits{0};
  16634. std::atomic<int> target_hits{0};
  16635. std::atomic<bool> target_saw_authz{false};
  16636. no_proxy_test::ScopedServer proxy_mock, target;
  16637. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16638. proxy_hits++;
  16639. res.status = 302;
  16640. res.set_header("Location", "http://127.0.0.1:" +
  16641. std::to_string(target.port()) + "/landed");
  16642. });
  16643. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16644. target_hits++;
  16645. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16646. res.set_content("direct", "text/plain");
  16647. });
  16648. proxy_mock.listen();
  16649. target.listen();
  16650. Client cli("public.example", target.port());
  16651. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16652. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16653. cli.set_proxy_basic_auth("u", "p");
  16654. cli.set_no_proxy({"127.0.0.1"});
  16655. cli.set_follow_location(true);
  16656. auto res = cli.Get("/redir");
  16657. ASSERT_TRUE(res);
  16658. EXPECT_GE(proxy_hits.load(), 1);
  16659. EXPECT_GE(target_hits.load(), 1);
  16660. EXPECT_FALSE(target_saw_authz.load());
  16661. }
  16662. #ifdef CPPHTTPLIB_SSL_ENABLED
  16663. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16664. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16665. // proxy creds would be sent to the (possibly hostile) origin.
  16666. std::atomic<int> target_hits{0};
  16667. std::atomic<bool> target_saw_proxy_authz{false};
  16668. no_proxy_test::ScopedServer target;
  16669. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16670. target_hits++;
  16671. if (req.has_header("Proxy-Authorization")) {
  16672. target_saw_proxy_authz = true;
  16673. }
  16674. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16675. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16676. "nonce=\"abc\", algorithm=MD5");
  16677. });
  16678. target.listen();
  16679. // The proxy address is set to the target's port: the bypass MUST kick in;
  16680. // if it doesn't, the test still routes "via proxy" to the same server and
  16681. // the Proxy-Authorization assertion below catches the leak.
  16682. Client cli("evil.example", target.port());
  16683. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16684. cli.set_proxy("127.0.0.1", target.port());
  16685. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16686. cli.set_no_proxy({"evil.example"});
  16687. auto res = cli.Get("/x");
  16688. ASSERT_TRUE(res);
  16689. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16690. EXPECT_EQ(1, target_hits.load());
  16691. EXPECT_FALSE(target_saw_proxy_authz.load());
  16692. }
  16693. #endif
  16694. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16695. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16696. std::atomic<int> proxy_hits{0};
  16697. std::atomic<int> bypass_hits{0};
  16698. std::atomic<bool> proxy_saw_c_url{false};
  16699. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16700. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16701. proxy_hits++;
  16702. if (req.path.find("/start") != std::string::npos) {
  16703. res.status = 302;
  16704. res.set_header("Location", "http://127.0.0.1:" +
  16705. std::to_string(bypass_server.port()) +
  16706. "/middle");
  16707. return;
  16708. }
  16709. if (req.path.find("/end") != std::string::npos) {
  16710. proxy_saw_c_url = true;
  16711. res.set_content("c-via-proxy", "text/plain");
  16712. return;
  16713. }
  16714. res.set_content("unexpected", "text/plain");
  16715. });
  16716. // public.example's "advertised" port is arbitrary (the request never lands
  16717. // there — it goes through the proxy), but use a dynamic value to stay
  16718. // friendly with sharded parallel runs.
  16719. int public_port = bypass_server.port();
  16720. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16721. bypass_hits++;
  16722. res.status = 302;
  16723. res.set_header("Location", "http://public.example:" +
  16724. std::to_string(public_port) + "/end");
  16725. });
  16726. proxy_mock.listen();
  16727. bypass_server.listen();
  16728. Client cli("public.example", public_port);
  16729. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16730. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16731. cli.set_no_proxy({"127.0.0.1"});
  16732. cli.set_follow_location(true);
  16733. auto res = cli.Get("/start");
  16734. ASSERT_TRUE(res);
  16735. EXPECT_EQ(StatusCode::OK_200, res->status);
  16736. EXPECT_EQ("c-via-proxy", res->body);
  16737. EXPECT_GE(proxy_hits.load(), 2);
  16738. EXPECT_GE(bypass_hits.load(), 1);
  16739. EXPECT_TRUE(proxy_saw_c_url.load());
  16740. }
  16741. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16742. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16743. // request reconnects to the correct endpoint.
  16744. std::atomic<int> proxy_hits{0};
  16745. std::atomic<int> target_hits{0};
  16746. no_proxy_test::ScopedServer proxy_mock, target;
  16747. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16748. proxy_hits++;
  16749. res.set_content("via-proxy", "text/plain");
  16750. });
  16751. target.svr().Get(".*", [&](const Request &, Response &res) {
  16752. target_hits++;
  16753. res.set_content("direct", "text/plain");
  16754. });
  16755. proxy_mock.listen();
  16756. target.listen();
  16757. Client cli("public.example", target.port());
  16758. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16759. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16760. cli.set_keep_alive(true);
  16761. auto res1 = cli.Get("/a");
  16762. ASSERT_TRUE(res1);
  16763. EXPECT_EQ("via-proxy", res1->body);
  16764. EXPECT_EQ(1, proxy_hits.load());
  16765. EXPECT_EQ(0, target_hits.load());
  16766. cli.set_no_proxy({"public.example"});
  16767. auto res2 = cli.Get("/b");
  16768. ASSERT_TRUE(res2);
  16769. EXPECT_EQ("direct", res2->body);
  16770. EXPECT_EQ(1, proxy_hits.load());
  16771. EXPECT_EQ(1, target_hits.load());
  16772. }
  16773. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16774. namespace proxy_tunnel_test {
  16775. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16776. class ScopedSSLServer {
  16777. public:
  16778. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16779. port_ = svr_.bind_to_any_port("127.0.0.1");
  16780. }
  16781. ~ScopedSSLServer() {
  16782. svr_.stop();
  16783. if (th_.joinable()) { th_.join(); }
  16784. }
  16785. SSLServer &svr() { return svr_; }
  16786. int port() const { return port_; }
  16787. void listen() {
  16788. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16789. svr_.wait_until_ready();
  16790. }
  16791. private:
  16792. SSLServer svr_;
  16793. std::thread th_;
  16794. int port_ = 0;
  16795. };
  16796. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16797. class ScopedConnectProxy {
  16798. public:
  16799. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16800. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16801. if (listen_fd_ < 0) { return; }
  16802. int yes = 1;
  16803. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16804. sockaddr_in a{};
  16805. a.sin_family = AF_INET;
  16806. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16807. a.sin_port = 0;
  16808. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16809. return;
  16810. }
  16811. socklen_t alen = sizeof(a);
  16812. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16813. 0) {
  16814. return;
  16815. }
  16816. port_ = ntohs(a.sin_port);
  16817. if (::listen(listen_fd_, 1) != 0) { return; }
  16818. th_ = std::thread([this] { run(); });
  16819. }
  16820. ~ScopedConnectProxy() {
  16821. stop_ = true;
  16822. if (listen_fd_ >= 0) {
  16823. ::shutdown(listen_fd_, SHUT_RDWR);
  16824. ::close(listen_fd_);
  16825. }
  16826. if (th_.joinable()) { th_.join(); }
  16827. }
  16828. int port() const { return port_; }
  16829. int connect_hits() const { return connect_hits_.load(); }
  16830. private:
  16831. void run() {
  16832. while (!stop_.load()) {
  16833. fd_set rfds;
  16834. FD_ZERO(&rfds);
  16835. FD_SET(listen_fd_, &rfds);
  16836. timeval tv{0, 100 * 1000};
  16837. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16838. if (sel <= 0) { continue; }
  16839. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16840. if (client_fd < 0) { continue; }
  16841. std::string req;
  16842. char buf[2048];
  16843. while (req.find("\r\n\r\n") == std::string::npos) {
  16844. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16845. if (n <= 0) { break; }
  16846. req.append(buf, static_cast<size_t>(n));
  16847. }
  16848. if (req.compare(0, 7, "CONNECT") != 0) {
  16849. ::close(client_fd);
  16850. continue;
  16851. }
  16852. connect_hits_++;
  16853. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16854. ::send(client_fd, ok, std::strlen(ok), 0);
  16855. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16856. sockaddr_in o{};
  16857. o.sin_family = AF_INET;
  16858. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16859. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16860. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16861. 0) {
  16862. ::close(client_fd);
  16863. ::close(origin_fd);
  16864. continue;
  16865. }
  16866. auto forward = [](int from, int to) {
  16867. char b[8192];
  16868. for (;;) {
  16869. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16870. if (n <= 0) { break; }
  16871. ssize_t off = 0;
  16872. while (off < n) {
  16873. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16874. if (s <= 0) {
  16875. off = n;
  16876. break;
  16877. }
  16878. off += s;
  16879. }
  16880. }
  16881. ::shutdown(to, SHUT_WR);
  16882. };
  16883. std::thread t1([&] { forward(client_fd, origin_fd); });
  16884. std::thread t2([&] { forward(origin_fd, client_fd); });
  16885. t1.join();
  16886. t2.join();
  16887. ::close(client_fd);
  16888. ::close(origin_fd);
  16889. }
  16890. }
  16891. int forward_port_ = -1;
  16892. int listen_fd_ = -1;
  16893. int port_ = 0;
  16894. std::thread th_;
  16895. std::atomic<bool> stop_{false};
  16896. std::atomic<int> connect_hits_{0};
  16897. };
  16898. } // namespace proxy_tunnel_test
  16899. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16900. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16901. // retry; otherwise proxy creds would be sent to the origin.
  16902. std::atomic<int> origin_hits{0};
  16903. std::atomic<bool> origin_saw_proxy_authz{false};
  16904. proxy_tunnel_test::ScopedSSLServer origin;
  16905. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16906. origin_hits++;
  16907. if (req.has_header("Proxy-Authorization")) {
  16908. origin_saw_proxy_authz = true;
  16909. }
  16910. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16911. res.set_header("Proxy-Authenticate",
  16912. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16913. "algorithm=MD5");
  16914. });
  16915. origin.listen();
  16916. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16917. ASSERT_NE(0, proxy.port());
  16918. SSLClient cli(HOST, origin.port());
  16919. cli.enable_server_certificate_verification(false);
  16920. cli.set_proxy(HOST, proxy.port());
  16921. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16922. auto res = cli.Get("/x");
  16923. ASSERT_TRUE(res);
  16924. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16925. EXPECT_EQ(1, origin_hits.load());
  16926. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16927. EXPECT_EQ(1, proxy.connect_hits());
  16928. }
  16929. #endif