test.cc 624 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242
  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(FromCharsTest, Double) {
  547. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  548. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  549. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  550. auto parse = [](const std::string &s, double &v) {
  551. return detail::from_chars(s.data(), s.data() + s.size(), v);
  552. };
  553. double v = -1.0;
  554. // Representative quality values.
  555. EXPECT_EQ(parse("0", v).ec, std::errc{});
  556. EXPECT_DOUBLE_EQ(v, 0.0);
  557. EXPECT_EQ(parse("1", v).ec, std::errc{});
  558. EXPECT_DOUBLE_EQ(v, 1.0);
  559. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  560. EXPECT_DOUBLE_EQ(v, 0.8);
  561. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  562. EXPECT_DOUBLE_EQ(v, 0.001);
  563. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  564. EXPECT_DOUBLE_EQ(v, 1.0);
  565. // A missing integer or fractional part is tolerated.
  566. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  567. EXPECT_DOUBLE_EQ(v, 0.5);
  568. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  569. EXPECT_DOUBLE_EQ(v, 5.0);
  570. // Values outside [0, 1] still parse; the caller range-checks them.
  571. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  572. EXPECT_DOUBLE_EQ(v, 123.456);
  573. // Stops at the first byte that is not part of the number and reports where.
  574. std::string trailing = "0.9, text/html";
  575. auto r = parse(trailing, v);
  576. EXPECT_EQ(r.ec, std::errc{});
  577. EXPECT_DOUBLE_EQ(v, 0.9);
  578. EXPECT_EQ(*r.ptr, ',');
  579. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  580. // outright, and an 'e'/'E' simply ends the number.
  581. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  582. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  583. std::string exp_input = "1.5e3";
  584. r = parse(exp_input, v);
  585. EXPECT_EQ(r.ec, std::errc{});
  586. EXPECT_DOUBLE_EQ(v, 1.5);
  587. EXPECT_EQ(*r.ptr, 'e');
  588. // Invalid inputs.
  589. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  590. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  591. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  592. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  593. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  594. // Pathological but well-formed inputs must stay bounded (no overflow, no
  595. // out-of-bounds table access) and stay within [0, 1] for the caller.
  596. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  597. std::errc{});
  598. EXPECT_DOUBLE_EQ(v, 0.0);
  599. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  600. std::errc{});
  601. EXPECT_GE(v, 0.0);
  602. EXPECT_LE(v, 1.0);
  603. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  604. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  605. }
  606. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  607. // Simple case without quality values
  608. std::vector<std::string> result1;
  609. EXPECT_TRUE(detail::parse_accept_header(
  610. "text/html,application/json,text/plain", result1));
  611. EXPECT_EQ(result1.size(), 3U);
  612. EXPECT_EQ(result1[0], "text/html");
  613. EXPECT_EQ(result1[1], "application/json");
  614. EXPECT_EQ(result1[2], "text/plain");
  615. // With quality values
  616. std::vector<std::string> result2;
  617. EXPECT_TRUE(detail::parse_accept_header(
  618. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  619. EXPECT_EQ(result2.size(), 3U);
  620. EXPECT_EQ(result2[0], "application/json"); // highest q value
  621. EXPECT_EQ(result2[1], "text/html");
  622. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  623. }
  624. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  625. // Mixed with and without quality values
  626. std::vector<std::string> result;
  627. EXPECT_TRUE(detail::parse_accept_header(
  628. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  629. EXPECT_EQ(result.size(), 3U);
  630. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  631. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  632. EXPECT_EQ(result[2], "application/json"); // q=0.5
  633. }
  634. TEST(ParseAcceptHeaderTest, EdgeCases) {
  635. // Empty header
  636. std::vector<std::string> empty_result;
  637. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  638. EXPECT_TRUE(empty_result.empty());
  639. // Single type
  640. std::vector<std::string> single_result;
  641. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  642. EXPECT_EQ(single_result.size(), 1U);
  643. EXPECT_EQ(single_result[0], "application/json");
  644. // Wildcard types
  645. std::vector<std::string> wildcard_result;
  646. EXPECT_TRUE(detail::parse_accept_header(
  647. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  648. EXPECT_EQ(wildcard_result.size(), 3U);
  649. EXPECT_EQ(wildcard_result[0], "application/json");
  650. EXPECT_EQ(wildcard_result[1], "text/*");
  651. EXPECT_EQ(wildcard_result[2], "*/*");
  652. }
  653. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  654. // Common browser Accept header
  655. std::vector<std::string> browser_result;
  656. EXPECT_TRUE(
  657. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  658. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  659. browser_result));
  660. EXPECT_EQ(browser_result.size(), 6U);
  661. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  662. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  663. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  664. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  665. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  666. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  667. // API client header
  668. std::vector<std::string> api_result;
  669. EXPECT_TRUE(detail::parse_accept_header(
  670. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  671. api_result));
  672. EXPECT_EQ(api_result.size(), 3U);
  673. EXPECT_EQ(api_result[0], "application/json");
  674. EXPECT_EQ(api_result[1], "application/xml");
  675. EXPECT_EQ(api_result[2], "text/plain");
  676. }
  677. TEST(ParseAcceptHeaderTest, SpecialCases) {
  678. // Quality value with 3 decimal places
  679. std::vector<std::string> decimal_result;
  680. EXPECT_TRUE(detail::parse_accept_header(
  681. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  682. EXPECT_EQ(decimal_result.size(), 2U);
  683. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  684. EXPECT_EQ(decimal_result[1], "text/html");
  685. // Zero quality (should still be included but with lowest priority)
  686. std::vector<std::string> zero_q_result;
  687. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  688. zero_q_result));
  689. EXPECT_EQ(zero_q_result.size(), 2U);
  690. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  691. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  692. // No spaces around commas
  693. std::vector<std::string> no_space_result;
  694. EXPECT_TRUE(detail::parse_accept_header(
  695. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  696. no_space_result));
  697. EXPECT_EQ(no_space_result.size(), 3U);
  698. EXPECT_EQ(no_space_result[0], "text/html");
  699. EXPECT_EQ(no_space_result[1], "application/json");
  700. EXPECT_EQ(no_space_result[2], "text/plain");
  701. }
  702. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  703. // Quality values always use '.' as the decimal separator, so parsing must
  704. // not depend on the process locale. An embedding application may have
  705. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  706. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  707. std::string saved = cur ? cur : "C";
  708. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  709. "fr_FR.UTF-8"};
  710. bool switched = false;
  711. for (const auto loc : comma_locales) {
  712. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  713. std::localeconv()->decimal_point[0] == ',') {
  714. switched = true;
  715. break;
  716. }
  717. }
  718. if (!switched) {
  719. std::setlocale(LC_NUMERIC, saved.c_str());
  720. GTEST_SKIP() << "no comma-decimal locale available on this host";
  721. }
  722. // The higher-weighted type appears later in the list, so a correct parse
  723. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  724. // sensitive parse reads both weights as 0 and leaves the original order.
  725. std::vector<std::string> result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "application/json;q=0.1,text/html;q=0.9", result));
  728. ASSERT_EQ(result.size(), 2U);
  729. EXPECT_EQ(result[0], "text/html");
  730. EXPECT_EQ(result[1], "application/json");
  731. std::setlocale(LC_NUMERIC, saved.c_str());
  732. }
  733. TEST(ParseAcceptHeaderTest, InvalidCases) {
  734. std::vector<std::string> result;
  735. // Invalid quality value (> 1.0)
  736. EXPECT_FALSE(
  737. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  738. // Invalid quality value (< 0.0)
  739. EXPECT_FALSE(
  740. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  741. // Invalid quality value (not a number)
  742. EXPECT_FALSE(detail::parse_accept_header(
  743. "text/html;q=invalid,application/json", result));
  744. // Empty quality value
  745. EXPECT_FALSE(
  746. detail::parse_accept_header("text/html;q=,application/json", result));
  747. // Invalid media type format (no slash and not wildcard)
  748. EXPECT_FALSE(
  749. detail::parse_accept_header("invalidtype,application/json", result));
  750. // Empty media type
  751. result.clear();
  752. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  753. // Only commas
  754. result.clear();
  755. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  756. // Valid cases should still work
  757. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  758. EXPECT_EQ(result.size(), 1U);
  759. EXPECT_EQ(result[0], "*/*");
  760. EXPECT_TRUE(detail::parse_accept_header("*", result));
  761. EXPECT_EQ(result.size(), 1U);
  762. EXPECT_EQ(result[0], "*");
  763. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  764. EXPECT_EQ(result.size(), 1U);
  765. EXPECT_EQ(result[0], "text/*");
  766. }
  767. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  768. Server svr;
  769. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  770. EXPECT_EQ(req.accept_content_types.size(), 3U);
  771. EXPECT_EQ(req.accept_content_types[0], "application/json");
  772. EXPECT_EQ(req.accept_content_types[1], "text/html");
  773. EXPECT_EQ(req.accept_content_types[2], "*/*");
  774. res.set_content("ok", "text/plain");
  775. });
  776. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  777. EXPECT_TRUE(false);
  778. res.set_content("bad request", "text/plain");
  779. });
  780. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  781. auto se = detail::scope_exit([&] {
  782. svr.stop();
  783. listen_thread.join();
  784. ASSERT_FALSE(svr.is_running());
  785. });
  786. svr.wait_until_ready();
  787. Client cli("localhost", PORT);
  788. {
  789. auto res =
  790. cli.Get("/accept_ok",
  791. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  792. ASSERT_TRUE(res);
  793. EXPECT_EQ(StatusCode::OK_200, res->status);
  794. }
  795. {
  796. auto res = cli.Get("/accept_bad_request",
  797. {{"Accept", "text/html;q=abc,application/json"}});
  798. ASSERT_TRUE(res);
  799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  800. }
  801. }
  802. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  803. Server svr;
  804. svr.Get("/", [](const Request & /*req*/, Response &res) {
  805. res.set_content("ok", "text/plain");
  806. });
  807. std::atomic<int> start_count{0};
  808. std::atomic<bool> running_when_called{false};
  809. svr.set_start_handler([&]() {
  810. running_when_called = svr.is_running();
  811. start_count++;
  812. });
  813. auto port = svr.bind_to_any_port(HOST);
  814. std::thread t([&]() { svr.listen_after_bind(); });
  815. auto se = detail::scope_exit([&] {
  816. svr.stop();
  817. t.join();
  818. ASSERT_FALSE(svr.is_running());
  819. });
  820. svr.wait_until_ready();
  821. // A successful request proves the accept loop is running, which the start
  822. // handler precedes; so by now the handler must have run exactly once.
  823. Client cli(HOST, port);
  824. cli.set_connection_timeout(std::chrono::seconds(5));
  825. auto res = cli.Get("/");
  826. ASSERT_TRUE(res);
  827. EXPECT_EQ(StatusCode::OK_200, res->status);
  828. EXPECT_EQ(1, start_count.load());
  829. EXPECT_TRUE(running_when_called.load());
  830. }
  831. TEST(DivideTest, DivideStringTests) {
  832. auto divide = [](const std::string &str, char d) {
  833. std::string lhs;
  834. std::string rhs;
  835. detail::divide(str, d,
  836. [&](const char *lhs_data, std::size_t lhs_size,
  837. const char *rhs_data, std::size_t rhs_size) {
  838. lhs.assign(lhs_data, lhs_size);
  839. rhs.assign(rhs_data, rhs_size);
  840. });
  841. return std::make_pair(std::move(lhs), std::move(rhs));
  842. };
  843. {
  844. const auto res = divide("", '=');
  845. EXPECT_EQ(res.first, "");
  846. EXPECT_EQ(res.second, "");
  847. }
  848. {
  849. const auto res = divide("=", '=');
  850. EXPECT_EQ(res.first, "");
  851. EXPECT_EQ(res.second, "");
  852. }
  853. {
  854. const auto res = divide(" ", '=');
  855. EXPECT_EQ(res.first, " ");
  856. EXPECT_EQ(res.second, "");
  857. }
  858. {
  859. const auto res = divide("a", '=');
  860. EXPECT_EQ(res.first, "a");
  861. EXPECT_EQ(res.second, "");
  862. }
  863. {
  864. const auto res = divide("a=", '=');
  865. EXPECT_EQ(res.first, "a");
  866. EXPECT_EQ(res.second, "");
  867. }
  868. {
  869. const auto res = divide("=b", '=');
  870. EXPECT_EQ(res.first, "");
  871. EXPECT_EQ(res.second, "b");
  872. }
  873. {
  874. const auto res = divide("a=b", '=');
  875. EXPECT_EQ(res.first, "a");
  876. EXPECT_EQ(res.second, "b");
  877. }
  878. {
  879. const auto res = divide("a=b=", '=');
  880. EXPECT_EQ(res.first, "a");
  881. EXPECT_EQ(res.second, "b=");
  882. }
  883. {
  884. const auto res = divide("a=b=c", '=');
  885. EXPECT_EQ(res.first, "a");
  886. EXPECT_EQ(res.second, "b=c");
  887. }
  888. }
  889. TEST(SplitTest, ParseQueryString) {
  890. string s = "key1=val1&key2=val2&key3=val3";
  891. Params dic;
  892. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  893. [&](const char *b, const char *e) {
  894. string key, val;
  895. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  896. if (key.empty()) {
  897. key.assign(b2, e2);
  898. } else {
  899. val.assign(b2, e2);
  900. }
  901. });
  902. dic.emplace(key, val);
  903. });
  904. EXPECT_EQ("val1", dic.find("key1")->second);
  905. EXPECT_EQ("val2", dic.find("key2")->second);
  906. EXPECT_EQ("val3", dic.find("key3")->second);
  907. }
  908. TEST(SplitTest, ParseInvalidQueryTests) {
  909. {
  910. string s = " ";
  911. Params dict;
  912. detail::parse_query_text(s, dict);
  913. EXPECT_TRUE(dict.empty());
  914. }
  915. {
  916. string s = " = =";
  917. Params dict;
  918. detail::parse_query_text(s, dict);
  919. EXPECT_TRUE(dict.empty());
  920. }
  921. }
  922. TEST(ParseQueryTest, ParseQueryString) {
  923. {
  924. std::string s = "key1=val1&key2=val2&key3=val3";
  925. Params dic;
  926. detail::parse_query_text(s, dic);
  927. EXPECT_EQ("val1", dic.find("key1")->second);
  928. EXPECT_EQ("val2", dic.find("key2")->second);
  929. EXPECT_EQ("val3", dic.find("key3")->second);
  930. }
  931. {
  932. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  933. Params dic;
  934. detail::parse_query_text(s, dic);
  935. EXPECT_EQ("", dic.find("key1")->second);
  936. EXPECT_EQ("val1", dic.find("key2")->second);
  937. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  938. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  939. }
  940. }
  941. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  942. Params dic;
  943. EXPECT_EQ(detail::params_to_query_str(dic), "");
  944. dic.emplace("key1", "val1");
  945. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  946. dic.emplace("key2", "val2");
  947. dic.emplace("key3", "val3");
  948. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  949. }
  950. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  951. string content_type = "multipart/form-data; boundary=something";
  952. string boundary;
  953. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  954. EXPECT_TRUE(ret);
  955. EXPECT_EQ(boundary, "something");
  956. }
  957. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  958. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  959. string boundary;
  960. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  961. EXPECT_TRUE(ret);
  962. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  963. }
  964. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  965. string content_type =
  966. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  967. string boundary;
  968. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  969. EXPECT_TRUE(ret);
  970. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  971. }
  972. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  973. string content_type =
  974. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  975. string boundary;
  976. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  977. EXPECT_TRUE(ret);
  978. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  979. }
  980. TEST(GetHeaderValueTest, DefaultValue) {
  981. Headers headers = {{"Dummy", "Dummy"}};
  982. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  983. EXPECT_STREQ("text/plain", val);
  984. }
  985. TEST(GetHeaderValueTest, DefaultValueInt) {
  986. Headers headers = {{"Dummy", "Dummy"}};
  987. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  988. EXPECT_EQ(100ull, val);
  989. }
  990. TEST(GetHeaderValueTest, RegularValue) {
  991. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  992. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  993. EXPECT_STREQ("text/html", val);
  994. }
  995. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  996. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  997. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  998. EXPECT_STREQ("text/html", val);
  999. }
  1000. TEST(GetHeaderValueTest, SetContent) {
  1001. Response res;
  1002. res.set_content("html", "text/html");
  1003. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1004. res.set_content("text", "text/plain");
  1005. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1006. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1007. }
  1008. TEST(GetHeaderValueTest, RegularValueInt) {
  1009. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1010. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1011. EXPECT_EQ(100ull, val);
  1012. }
  1013. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1014. Headers headers = {{"Content-Length", "x"}};
  1015. auto is_invalid_value = false;
  1016. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1017. is_invalid_value);
  1018. EXPECT_EQ(0ull, val);
  1019. EXPECT_TRUE(is_invalid_value);
  1020. }
  1021. TEST(GetHeaderValueTest, Range) {
  1022. {
  1023. Headers headers = {make_range_header({{1, -1}})};
  1024. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1025. EXPECT_STREQ("bytes=1-", val);
  1026. }
  1027. {
  1028. Headers headers = {make_range_header({{-1, 1}})};
  1029. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1030. EXPECT_STREQ("bytes=-1", val);
  1031. }
  1032. {
  1033. Headers headers = {make_range_header({{1, 10}})};
  1034. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1035. EXPECT_STREQ("bytes=1-10", val);
  1036. }
  1037. {
  1038. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1039. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1040. EXPECT_STREQ("bytes=1-10, 100-", val);
  1041. }
  1042. {
  1043. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1044. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1045. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1046. }
  1047. {
  1048. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1049. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1050. EXPECT_STREQ("bytes=0-0, -1", val);
  1051. }
  1052. }
  1053. TEST(ParseHeaderValueTest, Range) {
  1054. {
  1055. Ranges ranges;
  1056. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1057. EXPECT_TRUE(ret);
  1058. EXPECT_EQ(1u, ranges.size());
  1059. EXPECT_EQ(1u, ranges[0].first);
  1060. EXPECT_EQ(-1, ranges[0].second);
  1061. }
  1062. {
  1063. Ranges ranges;
  1064. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1065. EXPECT_TRUE(ret);
  1066. EXPECT_EQ(1u, ranges.size());
  1067. EXPECT_EQ(-1, ranges[0].first);
  1068. EXPECT_EQ(1u, ranges[0].second);
  1069. }
  1070. {
  1071. Ranges ranges;
  1072. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1073. EXPECT_TRUE(ret);
  1074. EXPECT_EQ(1u, ranges.size());
  1075. EXPECT_EQ(1u, ranges[0].first);
  1076. EXPECT_EQ(10u, ranges[0].second);
  1077. }
  1078. {
  1079. Ranges ranges;
  1080. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1081. EXPECT_FALSE(ret);
  1082. }
  1083. {
  1084. Ranges ranges;
  1085. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1086. EXPECT_TRUE(ret);
  1087. EXPECT_EQ(2u, ranges.size());
  1088. EXPECT_EQ(1u, ranges[0].first);
  1089. EXPECT_EQ(10u, ranges[0].second);
  1090. EXPECT_EQ(100u, ranges[1].first);
  1091. EXPECT_EQ(-1, ranges[1].second);
  1092. }
  1093. {
  1094. Ranges ranges;
  1095. auto ret =
  1096. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1097. EXPECT_TRUE(ret);
  1098. EXPECT_EQ(3u, ranges.size());
  1099. EXPECT_EQ(1u, ranges[0].first);
  1100. EXPECT_EQ(10u, ranges[0].second);
  1101. EXPECT_EQ(100u, ranges[1].first);
  1102. EXPECT_EQ(200u, ranges[1].second);
  1103. EXPECT_EQ(300u, ranges[2].first);
  1104. EXPECT_EQ(400u, ranges[2].second);
  1105. }
  1106. {
  1107. Ranges ranges;
  1108. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1109. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1110. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1111. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1112. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1113. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1114. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1115. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1116. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1117. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1118. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1119. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1120. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1121. EXPECT_TRUE(ranges.empty());
  1122. }
  1123. }
  1124. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1125. Request req;
  1126. req.set_header("Accept-Encoding", "gzip");
  1127. Response res;
  1128. res.set_header("Content-Type", "text/plain");
  1129. auto ret = detail::encoding_type(req, res);
  1130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1131. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1132. #else
  1133. EXPECT_TRUE(ret == detail::EncodingType::None);
  1134. #endif
  1135. }
  1136. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1137. Request req;
  1138. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1139. Response res;
  1140. res.set_header("Content-Type", "text/plain");
  1141. auto ret = detail::encoding_type(req, res);
  1142. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1143. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1144. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1145. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1146. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1147. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1148. #else
  1149. EXPECT_TRUE(ret == detail::EncodingType::None);
  1150. #endif
  1151. }
  1152. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1153. Request req;
  1154. req.set_header("Accept-Encoding",
  1155. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1156. Response res;
  1157. res.set_header("Content-Type", "text/plain");
  1158. auto ret = detail::encoding_type(req, res);
  1159. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1160. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1161. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1162. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1163. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1164. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1165. #else
  1166. EXPECT_TRUE(ret == detail::EncodingType::None);
  1167. #endif
  1168. }
  1169. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1170. // All supported encodings rejected with q=0 should return None
  1171. Request req;
  1172. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1173. Response res;
  1174. res.set_header("Content-Type", "text/plain");
  1175. auto ret = detail::encoding_type(req, res);
  1176. EXPECT_TRUE(ret == detail::EncodingType::None);
  1177. }
  1178. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1179. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1180. Request req;
  1181. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1182. Response res;
  1183. res.set_header("Content-Type", "text/plain");
  1184. auto ret = detail::encoding_type(req, res);
  1185. EXPECT_TRUE(ret == detail::EncodingType::None);
  1186. }
  1187. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1188. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1189. Request req;
  1190. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1191. Response res;
  1192. res.set_header("Content-Type", "text/plain");
  1193. auto ret = detail::encoding_type(req, res);
  1194. EXPECT_TRUE(ret == detail::EncodingType::None);
  1195. }
  1196. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1197. // RFC 7231: Accept-Encoding values are case-insensitive
  1198. Request req;
  1199. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1200. Response res;
  1201. res.set_header("Content-Type", "text/plain");
  1202. auto ret = detail::encoding_type(req, res);
  1203. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1204. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1205. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1206. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1207. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1208. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1209. #else
  1210. EXPECT_TRUE(ret == detail::EncodingType::None);
  1211. #endif
  1212. }
  1213. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1214. // q value should determine priority, not hardcoded order
  1215. Request req;
  1216. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1217. Response res;
  1218. res.set_header("Content-Type", "text/plain");
  1219. auto ret = detail::encoding_type(req, res);
  1220. // gzip has highest q=1.0, so it should be selected even though
  1221. // br and zstd are also supported
  1222. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1223. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1224. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1225. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1226. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1227. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1228. #else
  1229. EXPECT_TRUE(ret == detail::EncodingType::None);
  1230. #endif
  1231. }
  1232. TEST(BufferStreamTest, read) {
  1233. detail::BufferStream strm1;
  1234. Stream &strm = strm1;
  1235. EXPECT_EQ(5, strm.write("hello"));
  1236. char buf[512];
  1237. EXPECT_EQ(2, strm.read(buf, 2));
  1238. EXPECT_EQ('h', buf[0]);
  1239. EXPECT_EQ('e', buf[1]);
  1240. EXPECT_EQ(2, strm.read(buf, 2));
  1241. EXPECT_EQ('l', buf[0]);
  1242. EXPECT_EQ('l', buf[1]);
  1243. EXPECT_EQ(1, strm.read(buf, 1));
  1244. EXPECT_EQ('o', buf[0]);
  1245. EXPECT_EQ(0, strm.read(buf, 1));
  1246. }
  1247. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1248. auto host = "www.httpwatch.com";
  1249. auto ip = hosted_at(host);
  1250. EXPECT_EQ("23.96.13.243", ip);
  1251. std::vector<std::string> addrs;
  1252. hosted_at(host, addrs);
  1253. EXPECT_EQ(1u, addrs.size());
  1254. }
  1255. #if 0 // It depends on each test environment...
  1256. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1257. auto host = "www.youtube.com";
  1258. std::vector<std::string> addrs;
  1259. hosted_at(host, addrs);
  1260. EXPECT_EQ(20u, addrs.size());
  1261. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1262. EXPECT_TRUE(it != addrs.end());
  1263. }
  1264. #endif
  1265. class ChunkedEncodingTest : public ::testing::Test {
  1266. protected:
  1267. ChunkedEncodingTest()
  1268. : cli_(HOST, PORT)
  1269. #ifdef CPPHTTPLIB_SSL_ENABLED
  1270. ,
  1271. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1272. #endif
  1273. {
  1274. cli_.set_connection_timeout(2);
  1275. #ifdef CPPHTTPLIB_SSL_ENABLED
  1276. cli_.enable_server_certificate_verification(false);
  1277. #endif
  1278. }
  1279. virtual void SetUp() {
  1280. read_file("./image.jpg", image_data_);
  1281. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1282. res.set_content("Hello World!", "text/plain");
  1283. });
  1284. svr_.Get(
  1285. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1286. res.set_chunked_content_provider(
  1287. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1288. size_t remaining = image_data_.size() - offset;
  1289. if (remaining == 0) {
  1290. sink.done();
  1291. } else {
  1292. constexpr size_t CHUNK_SIZE = 1024;
  1293. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1294. sink.write(&image_data_[offset], send_size);
  1295. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1296. }
  1297. return true;
  1298. });
  1299. });
  1300. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1301. svr_.wait_until_ready();
  1302. }
  1303. virtual void TearDown() {
  1304. svr_.stop();
  1305. if (!request_threads_.empty()) {
  1306. std::this_thread::sleep_for(std::chrono::seconds(1));
  1307. for (auto &t : request_threads_) {
  1308. t.join();
  1309. }
  1310. }
  1311. t_.join();
  1312. }
  1313. #ifdef CPPHTTPLIB_SSL_ENABLED
  1314. SSLClient cli_;
  1315. SSLServer svr_;
  1316. #else
  1317. Client cli_;
  1318. Server svr_;
  1319. #endif
  1320. thread t_;
  1321. std::vector<thread> request_threads_;
  1322. std::string image_data_;
  1323. };
  1324. TEST_F(ChunkedEncodingTest, NormalGet) {
  1325. auto res = cli_.Get("/chunked");
  1326. ASSERT_TRUE(res);
  1327. std::string out;
  1328. read_file("./image.jpg", out);
  1329. EXPECT_EQ(StatusCode::OK_200, res->status);
  1330. EXPECT_EQ(out, res->body);
  1331. }
  1332. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1333. std::string body;
  1334. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1335. body.append(data, data_length);
  1336. return true;
  1337. });
  1338. ASSERT_TRUE(res);
  1339. std::string out;
  1340. read_file("./image.jpg", out);
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. EXPECT_EQ(out, body);
  1343. }
  1344. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1345. std::string body;
  1346. auto res = cli_.Get(
  1347. "/chunked",
  1348. [&](const Response &response) {
  1349. EXPECT_EQ(StatusCode::OK_200, response.status);
  1350. return true;
  1351. },
  1352. [&](const char *data, size_t data_length) {
  1353. body.append(data, data_length);
  1354. return true;
  1355. });
  1356. ASSERT_TRUE(res);
  1357. std::string out;
  1358. read_file("./image.jpg", out);
  1359. EXPECT_EQ(StatusCode::OK_200, res->status);
  1360. EXPECT_EQ(out, body);
  1361. }
  1362. TEST(RangeTest, FromHTTPBin_Online) {
  1363. auto host = "httpbingo.org";
  1364. auto path = std::string{"/range/32"};
  1365. #ifdef CPPHTTPLIB_SSL_ENABLED
  1366. auto port = 443;
  1367. SSLClient cli(host, port);
  1368. #else
  1369. auto port = 80;
  1370. Client cli(host, port);
  1371. #endif
  1372. cli.set_connection_timeout(5);
  1373. {
  1374. auto res = cli.Get(path);
  1375. ASSERT_TRUE(res);
  1376. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1377. EXPECT_EQ(StatusCode::OK_200, res->status);
  1378. }
  1379. {
  1380. Headers headers = {make_range_header({{1, -1}})};
  1381. auto res = cli.Get(path, headers);
  1382. ASSERT_TRUE(res);
  1383. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1385. }
  1386. {
  1387. Headers headers = {make_range_header({{1, 10}})};
  1388. auto res = cli.Get(path, headers);
  1389. ASSERT_TRUE(res);
  1390. EXPECT_EQ("bcdefghijk", res->body);
  1391. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1392. }
  1393. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1394. // entire resource, while the original httpbin returned 200. Both are
  1395. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1396. {
  1397. Headers headers = {make_range_header({{0, 31}})};
  1398. auto res = cli.Get(path, headers);
  1399. ASSERT_TRUE(res);
  1400. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1401. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1402. res->status == StatusCode::PartialContent_206);
  1403. }
  1404. {
  1405. Headers headers = {make_range_header({{0, -1}})};
  1406. auto res = cli.Get(path, headers);
  1407. ASSERT_TRUE(res);
  1408. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1409. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1410. res->status == StatusCode::PartialContent_206);
  1411. }
  1412. // go-httpbin returns 206 with clamped range for over-range requests,
  1413. // while the original httpbin returned 416. Both behaviors are observed
  1414. // in real servers, so we only verify the request succeeds.
  1415. {
  1416. Headers headers = {make_range_header({{0, 32}})};
  1417. auto res = cli.Get(path, headers);
  1418. ASSERT_TRUE(res);
  1419. }
  1420. }
  1421. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1422. auto host = "unresolvableaddress.local";
  1423. auto path = std::string{"/"};
  1424. #ifdef CPPHTTPLIB_SSL_ENABLED
  1425. auto port = 443;
  1426. SSLClient cli(host, port);
  1427. #else
  1428. auto port = 80;
  1429. Client cli(host, port);
  1430. #endif
  1431. cli.set_connection_timeout(1);
  1432. {
  1433. auto res = cli.Get(path);
  1434. ASSERT_FALSE(res);
  1435. }
  1436. std::this_thread::sleep_for(std::chrono::seconds(8));
  1437. }
  1438. #if defined(__linux__) && defined(__GLIBC__) && \
  1439. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1440. // Forward declaration: in split builds split.py strips `inline` and moves the
  1441. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1442. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1443. // against the symbol in both header-only and split builds.
  1444. namespace httplib {
  1445. namespace detail {
  1446. int getaddrinfo_with_timeout(const char *node, const char *service,
  1447. const struct addrinfo *hints,
  1448. struct addrinfo **res, time_t timeout_sec);
  1449. } // namespace detail
  1450. } // namespace httplib
  1451. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1452. //
  1453. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1454. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1455. // gai_suspend() call hits the connection timeout the function calls
  1456. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1457. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1458. // still alive and still references the now-destroyed stack frame.
  1459. //
  1460. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1461. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1462. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1463. // and runs them in a container.
  1464. namespace {
  1465. bool should_run_issue_2431_tests() {
  1466. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1467. return v && *v && std::string(v) != "0";
  1468. }
  1469. std::string unique_unresolvable_host(int n) {
  1470. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1471. // glibc still asks the configured nameserver — which is exactly the path
  1472. // we want to exercise. A unique label per call avoids the resolver cache.
  1473. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1474. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1475. std::to_string(n) + ".invalid";
  1476. }
  1477. } // namespace
  1478. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1479. if (!should_run_issue_2431_tests()) {
  1480. GTEST_SKIP()
  1481. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1482. }
  1483. for (int i = 0; i < 8; ++i) {
  1484. struct addrinfo hints;
  1485. memset(&hints, 0, sizeof(hints));
  1486. hints.ai_family = AF_UNSPEC;
  1487. hints.ai_socktype = SOCK_STREAM;
  1488. auto host = unique_unresolvable_host(i);
  1489. struct addrinfo *result = nullptr;
  1490. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1491. &result, /*timeout_sec=*/1);
  1492. if (rc == 0 && result) { freeaddrinfo(result); }
  1493. }
  1494. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1495. // stack region they still believe holds their gaicb.
  1496. std::this_thread::sleep_for(std::chrono::seconds(3));
  1497. }
  1498. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1499. if (!should_run_issue_2431_tests()) {
  1500. GTEST_SKIP()
  1501. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1502. }
  1503. std::atomic<bool> stop{false};
  1504. std::vector<std::thread> threads;
  1505. for (int t = 0; t < 8; ++t) {
  1506. threads.emplace_back([t, &stop] {
  1507. int i = 0;
  1508. while (!stop.load(std::memory_order_relaxed)) {
  1509. struct addrinfo hints;
  1510. memset(&hints, 0, sizeof(hints));
  1511. hints.ai_family = AF_UNSPEC;
  1512. hints.ai_socktype = SOCK_STREAM;
  1513. auto host = unique_unresolvable_host(t * 100000 + i++);
  1514. struct addrinfo *result = nullptr;
  1515. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1516. &result, /*timeout_sec=*/1);
  1517. if (rc == 0 && result) { freeaddrinfo(result); }
  1518. }
  1519. });
  1520. }
  1521. std::this_thread::sleep_for(std::chrono::seconds(8));
  1522. stop.store(true, std::memory_order_relaxed);
  1523. for (auto &th : threads) {
  1524. th.join();
  1525. }
  1526. std::this_thread::sleep_for(std::chrono::seconds(3));
  1527. }
  1528. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1529. if (!should_run_issue_2431_tests()) {
  1530. GTEST_SKIP()
  1531. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1532. }
  1533. std::atomic<bool> stop{false};
  1534. std::vector<std::thread> threads;
  1535. for (int t = 0; t < 8; ++t) {
  1536. threads.emplace_back([t, &stop] {
  1537. int i = 0;
  1538. while (!stop.load(std::memory_order_relaxed)) {
  1539. auto host = unique_unresolvable_host(t * 100000 + i++);
  1540. Client cli(host, 80);
  1541. cli.set_connection_timeout(1, 0);
  1542. cli.set_read_timeout(1, 0);
  1543. cli.set_write_timeout(1, 0);
  1544. (void)cli.Get("/");
  1545. }
  1546. });
  1547. }
  1548. std::this_thread::sleep_for(std::chrono::seconds(8));
  1549. stop.store(true, std::memory_order_relaxed);
  1550. for (auto &th : threads) {
  1551. th.join();
  1552. }
  1553. std::this_thread::sleep_for(std::chrono::seconds(3));
  1554. }
  1555. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1556. TEST(ConnectionErrorTest, InvalidHost) {
  1557. auto host = "-abcde.com";
  1558. #ifdef CPPHTTPLIB_SSL_ENABLED
  1559. auto port = 443;
  1560. SSLClient cli(host, port);
  1561. #else
  1562. auto port = 80;
  1563. Client cli(host, port);
  1564. #endif
  1565. cli.set_connection_timeout(std::chrono::seconds(2));
  1566. auto res = cli.Get("/");
  1567. ASSERT_TRUE(!res);
  1568. EXPECT_EQ(Error::Connection, res.error());
  1569. }
  1570. TEST(ConnectionErrorTest, InvalidHost2) {
  1571. auto host = "httpcan.org/";
  1572. #ifdef CPPHTTPLIB_SSL_ENABLED
  1573. SSLClient cli(host);
  1574. #else
  1575. Client cli(host);
  1576. #endif
  1577. cli.set_connection_timeout(std::chrono::seconds(2));
  1578. auto res = cli.Get("/");
  1579. ASSERT_TRUE(!res);
  1580. EXPECT_EQ(Error::Connection, res.error());
  1581. }
  1582. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1583. auto host = "httpcan.org/";
  1584. #ifdef CPPHTTPLIB_SSL_ENABLED
  1585. SSLClient cli(host);
  1586. #else
  1587. Client cli(host);
  1588. #endif
  1589. cli.set_connection_timeout(std::chrono::seconds(2));
  1590. auto res = cli.Get("/");
  1591. ASSERT_TRUE(!res);
  1592. stringstream s;
  1593. s << "error code: " << res.error();
  1594. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1595. }
  1596. TEST(ConnectionErrorTest, InvalidPort) {
  1597. auto host = "localhost";
  1598. auto port = 44380;
  1599. #ifdef CPPHTTPLIB_SSL_ENABLED
  1600. SSLClient cli(host, port);
  1601. #else
  1602. Client cli(host, port);
  1603. #endif
  1604. cli.set_connection_timeout(std::chrono::seconds(2));
  1605. auto res = cli.Get("/");
  1606. ASSERT_TRUE(!res);
  1607. EXPECT_TRUE(Error::Connection == res.error() ||
  1608. Error::ConnectionTimeout == res.error());
  1609. }
  1610. TEST(ConnectionErrorTest, Timeout_Online) {
  1611. auto host = "google.com";
  1612. #ifdef CPPHTTPLIB_SSL_ENABLED
  1613. auto port = 44380;
  1614. SSLClient cli(host, port);
  1615. #else
  1616. auto port = 8080;
  1617. Client cli(host, port);
  1618. #endif
  1619. cli.set_connection_timeout(std::chrono::seconds(2));
  1620. // only probe one address type so that the error reason
  1621. // correlates to the timed-out IPv4, not the unsupported
  1622. // IPv6 connection attempt
  1623. cli.set_address_family(AF_INET);
  1624. auto res = cli.Get("/");
  1625. ASSERT_TRUE(!res);
  1626. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1627. }
  1628. TEST(CancelTest, NoCancel_Online) {
  1629. auto host = "httpbingo.org";
  1630. auto path = std::string{"/range/32"};
  1631. #ifdef CPPHTTPLIB_SSL_ENABLED
  1632. auto port = 443;
  1633. SSLClient cli(host, port);
  1634. #else
  1635. auto port = 80;
  1636. Client cli(host, port);
  1637. #endif
  1638. cli.set_connection_timeout(std::chrono::seconds(5));
  1639. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1640. ASSERT_TRUE(res);
  1641. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1642. EXPECT_EQ(StatusCode::OK_200, res->status);
  1643. }
  1644. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1645. // Use /bytes with a large payload so that the DownloadProgress callback
  1646. // (which only fires for Content-Length responses) is invoked before the
  1647. // entire body is received, giving cancellation a chance to fire.
  1648. auto host = "httpbingo.org";
  1649. auto path = std::string{"/bytes/524288"};
  1650. #ifdef CPPHTTPLIB_SSL_ENABLED
  1651. auto port = 443;
  1652. SSLClient cli(host, port);
  1653. #else
  1654. auto port = 80;
  1655. Client cli(host, port);
  1656. #endif
  1657. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1658. cli.set_connection_timeout(std::chrono::seconds(5));
  1659. ASSERT_TRUE(!res);
  1660. EXPECT_EQ(Error::Canceled, res.error());
  1661. }
  1662. TEST(CancelTest, WithCancelLargePayload_Online) {
  1663. auto host = "httpbingo.org";
  1664. auto path = std::string{"/bytes/524288"};
  1665. #ifdef CPPHTTPLIB_SSL_ENABLED
  1666. auto port = 443;
  1667. SSLClient cli(host, port);
  1668. #else
  1669. auto port = 80;
  1670. Client cli(host, port);
  1671. #endif
  1672. cli.set_connection_timeout(std::chrono::seconds(5));
  1673. uint32_t count = 0;
  1674. auto res =
  1675. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1676. ASSERT_TRUE(!res);
  1677. EXPECT_EQ(Error::Canceled, res.error());
  1678. }
  1679. TEST(CancelTest, NoCancelPost) {
  1680. Server svr;
  1681. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1682. res.set_content("Hello World!", "text/plain");
  1683. });
  1684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1685. auto se = detail::scope_exit([&] {
  1686. svr.stop();
  1687. thread.join();
  1688. ASSERT_FALSE(svr.is_running());
  1689. });
  1690. svr.wait_until_ready();
  1691. Client cli(HOST, PORT);
  1692. cli.set_connection_timeout(std::chrono::seconds(5));
  1693. auto res =
  1694. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1695. "application/json", [](uint64_t, uint64_t) { return true; });
  1696. ASSERT_TRUE(res);
  1697. EXPECT_EQ("Hello World!", res->body);
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. TEST(CancelTest, WithCancelSmallPayloadPost) {
  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 false; });
  1717. ASSERT_TRUE(!res);
  1718. EXPECT_EQ(Error::Canceled, res.error());
  1719. }
  1720. TEST(CancelTest, WithCancelLargePayloadPost) {
  1721. Server svr;
  1722. svr.set_payload_max_length(200 * 1024 * 1024);
  1723. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1724. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  1735. cli.set_connection_timeout(std::chrono::seconds(5));
  1736. auto res =
  1737. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1738. "application/json", [](uint64_t, uint64_t) { return false; });
  1739. ASSERT_TRUE(!res);
  1740. EXPECT_EQ(Error::Canceled, res.error());
  1741. }
  1742. TEST(CancelTest, NoCancelPut) {
  1743. Server svr;
  1744. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  1756. auto res =
  1757. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1758. "application/json", [](uint64_t, uint64_t) { return true; });
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ("Hello World!", res->body);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. }
  1763. TEST(CancelTest, WithCancelSmallPayloadPut) {
  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 false; });
  1780. ASSERT_TRUE(!res);
  1781. EXPECT_EQ(Error::Canceled, res.error());
  1782. }
  1783. TEST(CancelTest, WithCancelLargePayloadPut) {
  1784. Server svr;
  1785. svr.set_payload_max_length(200 * 1024 * 1024);
  1786. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1787. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  1798. cli.set_connection_timeout(std::chrono::seconds(5));
  1799. auto res =
  1800. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1801. "application/json", [](uint64_t, uint64_t) { return false; });
  1802. ASSERT_TRUE(!res);
  1803. EXPECT_EQ(Error::Canceled, res.error());
  1804. }
  1805. TEST(CancelTest, NoCancelPatch) {
  1806. Server svr;
  1807. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1808. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  1819. auto res =
  1820. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1821. "application/json", [](uint64_t, uint64_t) { return true; });
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ("Hello World!", res->body);
  1824. EXPECT_EQ(StatusCode::OK_200, res->status);
  1825. }
  1826. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  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 false; });
  1843. ASSERT_TRUE(!res);
  1844. EXPECT_EQ(Error::Canceled, res.error());
  1845. }
  1846. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1847. Server svr;
  1848. svr.set_payload_max_length(200 * 1024 * 1024);
  1849. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1850. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  1861. cli.set_connection_timeout(std::chrono::seconds(5));
  1862. auto res =
  1863. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1864. "application/json", [](uint64_t, uint64_t) { return false; });
  1865. ASSERT_TRUE(!res);
  1866. EXPECT_EQ(Error::Canceled, res.error());
  1867. }
  1868. TEST(CancelTest, NoCancelDelete) {
  1869. Server svr;
  1870. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1871. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  1882. auto res =
  1883. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1884. "application/json", [](uint64_t, uint64_t) { return true; });
  1885. ASSERT_TRUE(res);
  1886. EXPECT_EQ("Hello World!", res->body);
  1887. EXPECT_EQ(StatusCode::OK_200, res->status);
  1888. }
  1889. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  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 false; });
  1906. ASSERT_TRUE(!res);
  1907. EXPECT_EQ(Error::Canceled, res.error());
  1908. }
  1909. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1910. Server svr;
  1911. svr.set_payload_max_length(200 * 1024 * 1024);
  1912. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  1924. cli.set_connection_timeout(std::chrono::seconds(5));
  1925. auto res =
  1926. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1927. "application/json", [](uint64_t, uint64_t) { return false; });
  1928. ASSERT_TRUE(!res);
  1929. EXPECT_EQ(Error::Canceled, res.error());
  1930. }
  1931. static std::string remove_whitespace(const std::string &input) {
  1932. std::string output;
  1933. output.reserve(input.size());
  1934. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1935. [](unsigned char c) { return !std::isspace(c); });
  1936. return output;
  1937. }
  1938. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1939. auto host = "httpbingo.org";
  1940. auto path = std::string{"/basic-auth/hello/world"};
  1941. #ifdef CPPHTTPLIB_SSL_ENABLED
  1942. auto port = 443;
  1943. SSLClient cli(host, port);
  1944. #else
  1945. auto port = 80;
  1946. Client cli(host, port);
  1947. #endif
  1948. {
  1949. auto res = cli.Get(path);
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1952. }
  1953. {
  1954. auto res =
  1955. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1956. ASSERT_TRUE(res);
  1957. auto body = remove_whitespace(res->body);
  1958. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1959. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. }
  1962. {
  1963. cli.set_basic_auth("hello", "world");
  1964. auto res = cli.Get(path);
  1965. ASSERT_TRUE(res);
  1966. auto body = remove_whitespace(res->body);
  1967. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1968. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1969. EXPECT_EQ(StatusCode::OK_200, res->status);
  1970. }
  1971. {
  1972. cli.set_basic_auth("hello", "bad");
  1973. auto res = cli.Get(path);
  1974. ASSERT_TRUE(res);
  1975. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1976. }
  1977. {
  1978. cli.set_basic_auth("bad", "world");
  1979. auto res = cli.Get(path);
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1982. }
  1983. }
  1984. #ifdef CPPHTTPLIB_SSL_ENABLED
  1985. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1986. auto host = "httpbingo.org";
  1987. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1988. auto paths = std::vector<std::string>{
  1989. "/digest-auth/auth/hello/world/MD5",
  1990. "/digest-auth/auth/hello/world/SHA-256",
  1991. };
  1992. auto port = 443;
  1993. SSLClient cli(host, port);
  1994. {
  1995. auto res = cli.Get(unauth_path);
  1996. ASSERT_TRUE(res);
  1997. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1998. }
  1999. {
  2000. cli.set_digest_auth("hello", "world");
  2001. for (const auto &path : paths) {
  2002. auto res = cli.Get(path.c_str());
  2003. ASSERT_TRUE(res);
  2004. auto body = remove_whitespace(res->body);
  2005. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2006. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2007. EXPECT_EQ(StatusCode::OK_200, res->status);
  2008. }
  2009. cli.set_digest_auth("hello", "bad");
  2010. for (const auto &path : paths) {
  2011. auto res = cli.Get(path.c_str());
  2012. ASSERT_TRUE(res);
  2013. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2014. }
  2015. }
  2016. }
  2017. #endif
  2018. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2019. auto host = "google.com";
  2020. auto another_host = "example.com";
  2021. auto wrong_ip = "0.0.0.0";
  2022. #ifdef CPPHTTPLIB_SSL_ENABLED
  2023. SSLClient cli(host);
  2024. #else
  2025. Client cli(host);
  2026. #endif
  2027. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2028. auto res = cli.Get("/");
  2029. ASSERT_TRUE(res);
  2030. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2031. }
  2032. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2033. auto host = "google.com";
  2034. auto wrong_ip = "0.0.0.0";
  2035. #ifdef CPPHTTPLIB_SSL_ENABLED
  2036. SSLClient cli(host);
  2037. #else
  2038. Client cli(host);
  2039. #endif
  2040. cli.set_hostname_addr_map({{host, wrong_ip}});
  2041. auto res = cli.Get("/");
  2042. ASSERT_TRUE(!res);
  2043. EXPECT_EQ(Error::Connection, res.error());
  2044. }
  2045. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2046. auto host = "httpbingo.org";
  2047. auto path = std::string{"/absolute-redirect/3"};
  2048. #ifdef CPPHTTPLIB_SSL_ENABLED
  2049. SSLClient cli(host);
  2050. #else
  2051. Client cli(host);
  2052. #endif
  2053. cli.set_follow_location(true);
  2054. auto res = cli.Get(path);
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(StatusCode::OK_200, res->status);
  2057. }
  2058. TEST(RedirectTest, Redirect_Online) {
  2059. auto host = "httpbingo.org";
  2060. auto path = std::string{"/redirect/3"};
  2061. #ifdef CPPHTTPLIB_SSL_ENABLED
  2062. SSLClient cli(host);
  2063. #else
  2064. Client cli(host);
  2065. #endif
  2066. cli.set_follow_location(true);
  2067. auto res = cli.Get(path);
  2068. ASSERT_TRUE(res);
  2069. EXPECT_EQ(StatusCode::OK_200, res->status);
  2070. }
  2071. TEST(RelativeRedirectTest, Redirect_Online) {
  2072. auto host = "httpbingo.org";
  2073. auto path = std::string{"/relative-redirect/3"};
  2074. #ifdef CPPHTTPLIB_SSL_ENABLED
  2075. SSLClient cli(host);
  2076. #else
  2077. Client cli(host);
  2078. #endif
  2079. cli.set_follow_location(true);
  2080. auto res = cli.Get(path);
  2081. ASSERT_TRUE(res);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. }
  2084. TEST(TooManyRedirectTest, Redirect_Online) {
  2085. auto host = "httpbingo.org";
  2086. auto path = std::string{"/redirect/21"};
  2087. #ifdef CPPHTTPLIB_SSL_ENABLED
  2088. SSLClient cli(host);
  2089. #else
  2090. Client cli(host);
  2091. #endif
  2092. cli.set_follow_location(true);
  2093. auto res = cli.Get(path);
  2094. ASSERT_TRUE(!res);
  2095. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2096. }
  2097. #ifdef CPPHTTPLIB_SSL_ENABLED
  2098. TEST(YahooRedirectTest, Redirect_Online) {
  2099. Client cli("yahoo.com");
  2100. auto res = cli.Get("/");
  2101. ASSERT_TRUE(res);
  2102. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2103. cli.set_follow_location(true);
  2104. res = cli.Get("/");
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(StatusCode::OK_200, res->status);
  2107. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2108. }
  2109. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2110. #define REDIR_HOST "httpbingo.org"
  2111. #define REDIR_PATH "/redirect-to"
  2112. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2113. SSLClient cli(REDIR_HOST);
  2114. cli.set_follow_location(true);
  2115. auto res =
  2116. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2117. ASSERT_TRUE(res);
  2118. EXPECT_EQ(StatusCode::OK_200, res->status);
  2119. }
  2120. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2121. SSLClient cli(REDIR_HOST);
  2122. cli.set_follow_location(true);
  2123. Params params;
  2124. params.emplace("url", "http://example.com");
  2125. params.emplace("status_code", "302");
  2126. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(StatusCode::OK_200, res->status);
  2129. }
  2130. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2131. SSLClient cli(REDIR_HOST);
  2132. cli.set_follow_location(true);
  2133. Params params;
  2134. params.emplace("url", "http://example.com");
  2135. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2136. ASSERT_TRUE(res);
  2137. EXPECT_EQ(StatusCode::OK_200, res->status);
  2138. }
  2139. TEST(UrlWithSpace, Redirect_Online) {
  2140. SSLClient cli("edge.forgecdn.net");
  2141. cli.set_follow_location(true);
  2142. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2143. ASSERT_TRUE(res);
  2144. EXPECT_EQ(StatusCode::OK_200, res->status);
  2145. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2146. }
  2147. #endif
  2148. #if !defined(_WIN32) && !defined(_WIN64)
  2149. TEST(ReceiveSignals, Signal) {
  2150. auto setupSignalHandlers = []() {
  2151. struct sigaction act;
  2152. sigemptyset(&act.sa_mask);
  2153. act.sa_flags = SA_SIGINFO;
  2154. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2155. switch (sig) {
  2156. case SIGINT:
  2157. default: break;
  2158. }
  2159. };
  2160. ::sigaction(SIGINT, &act, nullptr);
  2161. };
  2162. Server svr;
  2163. int port = 0;
  2164. auto thread = std::thread([&]() {
  2165. setupSignalHandlers();
  2166. port = svr.bind_to_any_port(HOST);
  2167. svr.listen_after_bind();
  2168. });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. ASSERT_TRUE(svr.is_running());
  2176. pthread_kill(thread.native_handle(), SIGINT);
  2177. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2178. ASSERT_TRUE(svr.is_running());
  2179. }
  2180. #endif
  2181. TEST(RedirectToDifferentPort, Redirect) {
  2182. Server svr1;
  2183. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2184. res.set_content("Hello World!", "text/plain");
  2185. });
  2186. int svr1_port = 0;
  2187. auto thread1 = std::thread([&]() {
  2188. svr1_port = svr1.bind_to_any_port(HOST);
  2189. svr1.listen_after_bind();
  2190. });
  2191. Server svr2;
  2192. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2193. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2194. });
  2195. int svr2_port = 0;
  2196. auto thread2 = std::thread([&]() {
  2197. svr2_port = svr2.bind_to_any_port(HOST);
  2198. svr2.listen_after_bind();
  2199. });
  2200. auto se = detail::scope_exit([&] {
  2201. svr2.stop();
  2202. thread2.join();
  2203. svr1.stop();
  2204. thread1.join();
  2205. ASSERT_FALSE(svr2.is_running());
  2206. ASSERT_FALSE(svr1.is_running());
  2207. });
  2208. svr1.wait_until_ready();
  2209. svr2.wait_until_ready();
  2210. Client cli("localhost", svr2_port);
  2211. cli.set_follow_location(true);
  2212. auto res = cli.Get("/2");
  2213. ASSERT_TRUE(res);
  2214. EXPECT_EQ(StatusCode::OK_200, res->status);
  2215. EXPECT_EQ("Hello World!", res->body);
  2216. }
  2217. static void
  2218. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2219. Server svr1;
  2220. std::string captured_authorization;
  2221. svr1.Get("/target", [&](const Request &req, Response &res) {
  2222. captured_authorization = req.get_header_value("Authorization");
  2223. res.set_content("OK", "text/plain");
  2224. });
  2225. int svr1_port = 0;
  2226. auto thread1 = std::thread([&]() {
  2227. svr1_port = svr1.bind_to_any_port(HOST);
  2228. svr1.listen_after_bind();
  2229. });
  2230. Server svr2;
  2231. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2232. res.set_redirect(
  2233. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2234. });
  2235. int svr2_port = 0;
  2236. auto thread2 = std::thread([&]() {
  2237. svr2_port = svr2.bind_to_any_port(HOST);
  2238. svr2.listen_after_bind();
  2239. });
  2240. auto se = detail::scope_exit([&] {
  2241. svr2.stop();
  2242. thread2.join();
  2243. svr1.stop();
  2244. thread1.join();
  2245. ASSERT_FALSE(svr2.is_running());
  2246. ASSERT_FALSE(svr1.is_running());
  2247. });
  2248. svr1.wait_until_ready();
  2249. svr2.wait_until_ready();
  2250. Client cli("localhost", svr2_port);
  2251. cli.set_follow_location(true);
  2252. set_auth(cli);
  2253. auto res = cli.Get("/redir");
  2254. ASSERT_TRUE(res);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2257. EXPECT_TRUE(captured_authorization.empty());
  2258. }
  2259. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2260. TestDoNotForwardCredentialsOnRedirect(
  2261. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2262. }
  2263. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2264. TestDoNotForwardCredentialsOnRedirect(
  2265. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2266. }
  2267. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2268. Server svr;
  2269. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2270. // Port number that overflows int — should not crash
  2271. res.set_redirect("http://localhost:99999999999999999999/target");
  2272. });
  2273. auto port = svr.bind_to_any_port(HOST);
  2274. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2275. auto se = detail::scope_exit([&] {
  2276. svr.stop();
  2277. thread.join();
  2278. ASSERT_FALSE(svr.is_running());
  2279. });
  2280. svr.wait_until_ready();
  2281. Client cli(HOST, port);
  2282. cli.set_follow_location(true);
  2283. auto res = cli.Get("/redir");
  2284. // Should fail gracefully, not crash (no valid response due to bad port)
  2285. EXPECT_FALSE(res);
  2286. }
  2287. TEST(RedirectFromPageWithContent, Redirect) {
  2288. Server svr;
  2289. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2290. res.set_content("___", "text/plain");
  2291. res.set_redirect("/2");
  2292. });
  2293. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2294. res.set_content("Hello World!", "text/plain");
  2295. });
  2296. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2297. auto se = detail::scope_exit([&] {
  2298. svr.stop();
  2299. th.join();
  2300. ASSERT_FALSE(svr.is_running());
  2301. });
  2302. svr.wait_until_ready();
  2303. {
  2304. Client cli("localhost", PORT);
  2305. cli.set_follow_location(true);
  2306. std::string body;
  2307. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2308. body.append(data, data_length);
  2309. return true;
  2310. });
  2311. ASSERT_TRUE(res);
  2312. EXPECT_EQ(StatusCode::OK_200, res->status);
  2313. EXPECT_EQ("Hello World!", body);
  2314. }
  2315. {
  2316. Client cli("localhost", PORT);
  2317. std::string body;
  2318. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2319. body.append(data, data_length);
  2320. return true;
  2321. });
  2322. ASSERT_TRUE(res);
  2323. EXPECT_EQ(StatusCode::Found_302, res->status);
  2324. EXPECT_EQ("___", body);
  2325. }
  2326. }
  2327. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2328. Server svr;
  2329. auto port_str = std::to_string(PORT);
  2330. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2331. auto expected_host = "[::1]:" + port_str;
  2332. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2333. res.set_content("___", "text/plain");
  2334. // res.set_redirect("/2");
  2335. res.set_redirect(redirect_url);
  2336. });
  2337. svr.Get("/2", [&](const Request &req, Response &res) {
  2338. auto host_header = req.headers.find("Host");
  2339. ASSERT_TRUE(host_header != req.headers.end());
  2340. EXPECT_EQ(expected_host, host_header->second);
  2341. res.set_content("Hello World!", "text/plain");
  2342. });
  2343. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2344. auto se = detail::scope_exit([&] {
  2345. svr.stop();
  2346. th.join();
  2347. ASSERT_FALSE(svr.is_running());
  2348. });
  2349. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2350. // actually starts anything, so the condition !svr.is_running() will
  2351. // always remain true, and the loop never stops.
  2352. // This basically counts how many milliseconds have passed since the
  2353. // call to svr.listen(), and if after 5 seconds nothing started yet
  2354. // aborts the test.
  2355. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2356. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2357. ASSERT_LT(milliseconds, 5000U);
  2358. }
  2359. {
  2360. Client cli("::1", PORT);
  2361. cli.set_follow_location(true);
  2362. std::string body;
  2363. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2364. body.append(data, data_length);
  2365. return true;
  2366. });
  2367. ASSERT_TRUE(res);
  2368. EXPECT_EQ(StatusCode::OK_200, res->status);
  2369. EXPECT_EQ("Hello World!", body);
  2370. }
  2371. {
  2372. Client cli("::1", PORT);
  2373. std::string body;
  2374. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2375. body.append(data, data_length);
  2376. return true;
  2377. });
  2378. ASSERT_TRUE(res);
  2379. EXPECT_EQ(StatusCode::Found_302, res->status);
  2380. EXPECT_EQ("___", body);
  2381. }
  2382. }
  2383. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2384. Server svr;
  2385. svr.Get("/foo", [](const Request &req, Response &res) {
  2386. auto a = req.params.find("a");
  2387. if (a != req.params.end()) {
  2388. res.set_content((*a).second, "text/plain");
  2389. res.status = StatusCode::OK_200;
  2390. } else {
  2391. res.status = StatusCode::BadRequest_400;
  2392. }
  2393. });
  2394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2395. auto se = detail::scope_exit([&] {
  2396. svr.stop();
  2397. thread.join();
  2398. ASSERT_FALSE(svr.is_running());
  2399. });
  2400. svr.wait_until_ready();
  2401. {
  2402. Client cli(HOST, PORT);
  2403. cli.set_path_encode(false);
  2404. auto res = cli.Get("/foo?a=explicitly+encoded");
  2405. ASSERT_TRUE(res);
  2406. EXPECT_EQ(StatusCode::OK_200, res->status);
  2407. // This expects it back with a space, as the `+` won't have been
  2408. // url-encoded, and server-side the params get decoded turning `+`
  2409. // into spaces.
  2410. EXPECT_EQ("explicitly encoded", res->body);
  2411. }
  2412. }
  2413. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2414. // When path encoding is disabled the client must transmit the supplied
  2415. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2416. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2417. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2418. // than a space (0x20). Assert on the raw wire target to catch this.
  2419. Server svr;
  2420. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2421. svr.Get("/foo", [&](const Request &req, Response &res) {
  2422. EXPECT_EQ(expected_target, req.target);
  2423. res.status = StatusCode::OK_200;
  2424. });
  2425. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2426. auto se = detail::scope_exit([&] {
  2427. svr.stop();
  2428. thread.join();
  2429. ASSERT_FALSE(svr.is_running());
  2430. });
  2431. svr.wait_until_ready();
  2432. {
  2433. Client cli(HOST, PORT);
  2434. cli.set_path_encode(false);
  2435. auto res = cli.Get(expected_target.c_str());
  2436. ASSERT_TRUE(res);
  2437. EXPECT_EQ(StatusCode::OK_200, res->status);
  2438. }
  2439. }
  2440. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2441. Server svr;
  2442. svr.Get("/", [](const Request &req, Response &) {
  2443. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2444. });
  2445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2446. auto se = detail::scope_exit([&] {
  2447. svr.stop();
  2448. thread.join();
  2449. ASSERT_FALSE(svr.is_running());
  2450. });
  2451. svr.wait_until_ready();
  2452. {
  2453. Client cli(HOST, PORT);
  2454. cli.set_path_encode(false);
  2455. auto res = cli.Get("/?something=%0A");
  2456. ASSERT_TRUE(res);
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. }
  2459. }
  2460. TEST(BindServerTest, BindDualStack) {
  2461. Server svr;
  2462. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2463. res.set_content("Hello World!", "text/plain");
  2464. });
  2465. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2466. auto se = detail::scope_exit([&] {
  2467. svr.stop();
  2468. thread.join();
  2469. ASSERT_FALSE(svr.is_running());
  2470. });
  2471. svr.wait_until_ready();
  2472. {
  2473. Client cli("127.0.0.1", PORT);
  2474. auto res = cli.Get("/1");
  2475. ASSERT_TRUE(res);
  2476. EXPECT_EQ(StatusCode::OK_200, res->status);
  2477. EXPECT_EQ("Hello World!", res->body);
  2478. }
  2479. {
  2480. Client cli("::1", PORT);
  2481. auto res = cli.Get("/1");
  2482. ASSERT_TRUE(res);
  2483. EXPECT_EQ(StatusCode::OK_200, res->status);
  2484. EXPECT_EQ("Hello World!", res->body);
  2485. }
  2486. }
  2487. TEST(BindServerTest, BindAndListenSeparately) {
  2488. Server svr;
  2489. int port = svr.bind_to_any_port("0.0.0.0");
  2490. ASSERT_TRUE(svr.is_valid());
  2491. ASSERT_TRUE(port > 0);
  2492. svr.stop();
  2493. }
  2494. #ifdef CPPHTTPLIB_SSL_ENABLED
  2495. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2497. CLIENT_CA_CERT_DIR);
  2498. int port = svr.bind_to_any_port("0.0.0.0");
  2499. ASSERT_TRUE(svr.is_valid());
  2500. ASSERT_TRUE(port > 0);
  2501. svr.stop();
  2502. }
  2503. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2504. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2505. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2506. int port = svr.bind_to_any_port("0.0.0.0");
  2507. ASSERT_TRUE(svr.is_valid());
  2508. ASSERT_TRUE(port > 0);
  2509. svr.stop();
  2510. }
  2511. TEST(BindServerTest, UpdateCertsPem) {
  2512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2513. int port = svr.bind_to_any_port("0.0.0.0");
  2514. ASSERT_TRUE(svr.is_valid());
  2515. ASSERT_TRUE(port > 0);
  2516. // Read PEM files
  2517. std::string cert_pem, key_pem, ca_pem;
  2518. read_file(SERVER_CERT_FILE, cert_pem);
  2519. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2520. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2521. // Update server certificates using PEM API
  2522. ASSERT_TRUE(
  2523. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2524. ASSERT_TRUE(svr.is_valid());
  2525. svr.stop();
  2526. }
  2527. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2528. // Start server with client CA (enables client auth)
  2529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2530. ASSERT_TRUE(svr.is_valid());
  2531. bool handler_called = false;
  2532. svr.Get("/test", [&](const Request &req, Response &res) {
  2533. handler_called = true;
  2534. // Verify client certificate is present
  2535. auto cert = req.peer_cert();
  2536. EXPECT_TRUE(static_cast<bool>(cert));
  2537. res.set_content("ok", "text/plain");
  2538. });
  2539. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2540. auto se = detail::scope_exit([&] {
  2541. svr.stop();
  2542. t.join();
  2543. ASSERT_FALSE(svr.is_running());
  2544. });
  2545. svr.wait_until_ready();
  2546. // Read PEM files
  2547. std::string cert_pem, key_pem, ca_pem;
  2548. read_file(SERVER_CERT_FILE, cert_pem);
  2549. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2550. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2551. // Update server certificates and client CA using PEM API while server running
  2552. ASSERT_TRUE(
  2553. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2554. // Connect with client certificate
  2555. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2556. cli.enable_server_certificate_verification(false);
  2557. cli.set_connection_timeout(30);
  2558. auto res = cli.Get("/test");
  2559. ASSERT_TRUE(res);
  2560. ASSERT_EQ(StatusCode::OK_200, res->status);
  2561. ASSERT_TRUE(handler_called);
  2562. EXPECT_EQ("ok", res->body);
  2563. }
  2564. #endif
  2565. TEST(ErrorHandlerTest, ContentLength) {
  2566. Server svr;
  2567. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2568. res.status = StatusCode::OK_200;
  2569. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2570. "text/html"); // <= Content-Length still 13
  2571. });
  2572. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2573. res.set_content("Hello World!\n", "text/plain");
  2574. res.status = 524;
  2575. });
  2576. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2577. auto se = detail::scope_exit([&] {
  2578. svr.stop();
  2579. thread.join();
  2580. ASSERT_FALSE(svr.is_running());
  2581. });
  2582. svr.wait_until_ready();
  2583. {
  2584. Client cli(HOST, PORT);
  2585. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2586. ASSERT_TRUE(res);
  2587. EXPECT_EQ(StatusCode::OK_200, res->status);
  2588. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2589. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2590. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2591. }
  2592. }
  2593. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2594. TEST(ExceptionTest, WithoutExceptionHandler) {
  2595. Server svr;
  2596. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2597. throw std::runtime_error("exception...");
  2598. });
  2599. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2600. throw std::runtime_error("exception\r\n...");
  2601. });
  2602. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2603. auto se = detail::scope_exit([&] {
  2604. svr.stop();
  2605. listen_thread.join();
  2606. ASSERT_FALSE(svr.is_running());
  2607. });
  2608. svr.wait_until_ready();
  2609. Client cli("localhost", PORT);
  2610. {
  2611. auto res = cli.Get("/exception");
  2612. ASSERT_TRUE(res);
  2613. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2614. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2615. }
  2616. {
  2617. auto res = cli.Get("/unknown");
  2618. ASSERT_TRUE(res);
  2619. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2620. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2621. }
  2622. }
  2623. TEST(ExceptionTest, WithExceptionHandler) {
  2624. Server svr;
  2625. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2626. std::exception_ptr ep) {
  2627. EXPECT_FALSE(ep == nullptr);
  2628. try {
  2629. std::rethrow_exception(ep);
  2630. } catch (std::exception &e) {
  2631. EXPECT_EQ("abc", std::string(e.what()));
  2632. } catch (...) {}
  2633. res.status = StatusCode::InternalServerError_500;
  2634. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2635. "text/html"); // <= Content-Length still 13 at this point
  2636. });
  2637. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2638. res.set_content("Hello World!\n", "text/plain");
  2639. throw std::runtime_error("abc");
  2640. });
  2641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2642. auto se = detail::scope_exit([&] {
  2643. svr.stop();
  2644. thread.join();
  2645. ASSERT_FALSE(svr.is_running());
  2646. });
  2647. svr.wait_until_ready();
  2648. for (size_t i = 0; i < 10; i++) {
  2649. Client cli(HOST, PORT);
  2650. for (size_t j = 0; j < 100; j++) {
  2651. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2652. ASSERT_TRUE(res);
  2653. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2654. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2655. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2656. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2657. }
  2658. cli.set_keep_alive(true);
  2659. for (size_t j = 0; j < 100; j++) {
  2660. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2661. ASSERT_TRUE(res);
  2662. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2663. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2664. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2665. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2666. }
  2667. }
  2668. }
  2669. TEST(ExceptionTest, AndErrorHandler) {
  2670. Server svr;
  2671. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2672. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2673. });
  2674. svr.set_exception_handler(
  2675. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2676. EXPECT_FALSE(ep == nullptr);
  2677. try {
  2678. std::rethrow_exception(ep);
  2679. } catch (std::exception &e) {
  2680. res.set_content(e.what(), "text/html");
  2681. } catch (...) {}
  2682. res.status = StatusCode::InternalServerError_500;
  2683. });
  2684. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2685. throw std::runtime_error("EXCEPTION");
  2686. });
  2687. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2688. res.set_content("ERROR", "text/html");
  2689. res.status = StatusCode::InternalServerError_500;
  2690. });
  2691. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2692. auto se = detail::scope_exit([&] {
  2693. svr.stop();
  2694. thread.join();
  2695. ASSERT_FALSE(svr.is_running());
  2696. });
  2697. svr.wait_until_ready();
  2698. Client cli(HOST, PORT);
  2699. {
  2700. auto res = cli.Get("/exception");
  2701. ASSERT_TRUE(res);
  2702. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2703. EXPECT_EQ("EXCEPTION", res->body);
  2704. }
  2705. {
  2706. auto res = cli.Get("/error");
  2707. ASSERT_TRUE(res);
  2708. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2709. EXPECT_EQ("ERROR", res->body);
  2710. }
  2711. {
  2712. auto res = cli.Get("/invalid");
  2713. ASSERT_TRUE(res);
  2714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2715. EXPECT_EQ("NOT_FOUND", res->body);
  2716. }
  2717. }
  2718. #endif
  2719. TEST(NoContentTest, ContentLength) {
  2720. Server svr;
  2721. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2722. res.status = StatusCode::NoContent_204;
  2723. });
  2724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2725. auto se = detail::scope_exit([&] {
  2726. svr.stop();
  2727. thread.join();
  2728. ASSERT_FALSE(svr.is_running());
  2729. });
  2730. svr.wait_until_ready();
  2731. {
  2732. Client cli(HOST, PORT);
  2733. auto res = cli.Get("/hi");
  2734. ASSERT_TRUE(res);
  2735. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2736. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2737. }
  2738. }
  2739. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2740. #ifdef CPPHTTPLIB_SSL_ENABLED
  2741. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2742. ASSERT_TRUE(svr.is_valid());
  2743. #else
  2744. Server svr;
  2745. #endif
  2746. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2747. if (req.path == "/routing_handler") {
  2748. res.set_header("PRE_ROUTING", "on");
  2749. res.set_content("Routing Handler", "text/plain");
  2750. return httplib::Server::HandlerResponse::Handled;
  2751. }
  2752. return httplib::Server::HandlerResponse::Unhandled;
  2753. });
  2754. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2755. res.set_content("Error", "text/html");
  2756. });
  2757. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2758. if (req.path == "/routing_handler") {
  2759. res.set_header("POST_ROUTING", "on");
  2760. }
  2761. });
  2762. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2763. res.set_content("Hello World!\n", "text/plain");
  2764. });
  2765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2766. auto se = detail::scope_exit([&] {
  2767. svr.stop();
  2768. thread.join();
  2769. ASSERT_FALSE(svr.is_running());
  2770. });
  2771. svr.wait_until_ready();
  2772. {
  2773. #ifdef CPPHTTPLIB_SSL_ENABLED
  2774. SSLClient cli(HOST, PORT);
  2775. cli.enable_server_certificate_verification(false);
  2776. #else
  2777. Client cli(HOST, PORT);
  2778. #endif
  2779. auto res = cli.Get("/routing_handler");
  2780. ASSERT_TRUE(res);
  2781. EXPECT_EQ(StatusCode::OK_200, res->status);
  2782. EXPECT_EQ("Routing Handler", res->body);
  2783. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2784. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2785. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2786. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2787. }
  2788. {
  2789. #ifdef CPPHTTPLIB_SSL_ENABLED
  2790. SSLClient cli(HOST, PORT);
  2791. cli.enable_server_certificate_verification(false);
  2792. #else
  2793. Client cli(HOST, PORT);
  2794. #endif
  2795. auto res = cli.Get("/hi");
  2796. ASSERT_TRUE(res);
  2797. EXPECT_EQ(StatusCode::OK_200, res->status);
  2798. EXPECT_EQ("Hello World!\n", res->body);
  2799. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2800. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2801. }
  2802. {
  2803. #ifdef CPPHTTPLIB_SSL_ENABLED
  2804. SSLClient cli(HOST, PORT);
  2805. cli.enable_server_certificate_verification(false);
  2806. #else
  2807. Client cli(HOST, PORT);
  2808. #endif
  2809. auto res = cli.Get("/aaa");
  2810. ASSERT_TRUE(res);
  2811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2812. EXPECT_EQ("Error", res->body);
  2813. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2814. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2815. }
  2816. }
  2817. TEST(RequestHandlerTest, PreRequestHandler) {
  2818. auto route_path = "/user/:user";
  2819. Server svr;
  2820. svr.Get("/hi", [](const Request &, Response &res) {
  2821. res.set_content("hi", "text/plain");
  2822. });
  2823. svr.Get(route_path, [](const Request &req, Response &res) {
  2824. res.set_content(req.path_params.at("user"), "text/plain");
  2825. });
  2826. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2827. if (req.matched_route == route_path) {
  2828. auto user = req.path_params.at("user");
  2829. if (user != "john") {
  2830. res.status = StatusCode::Forbidden_403;
  2831. res.set_content("error", "text/html");
  2832. return Server::HandlerResponse::Handled;
  2833. }
  2834. }
  2835. return Server::HandlerResponse::Unhandled;
  2836. });
  2837. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2838. auto se = detail::scope_exit([&] {
  2839. svr.stop();
  2840. thread.join();
  2841. ASSERT_FALSE(svr.is_running());
  2842. });
  2843. svr.wait_until_ready();
  2844. Client cli(HOST, PORT);
  2845. {
  2846. auto res = cli.Get("/hi");
  2847. ASSERT_TRUE(res);
  2848. EXPECT_EQ(StatusCode::OK_200, res->status);
  2849. EXPECT_EQ("hi", res->body);
  2850. }
  2851. {
  2852. auto res = cli.Get("/user/john");
  2853. ASSERT_TRUE(res);
  2854. EXPECT_EQ(StatusCode::OK_200, res->status);
  2855. EXPECT_EQ("john", res->body);
  2856. }
  2857. {
  2858. auto res = cli.Get("/user/invalid-user");
  2859. ASSERT_TRUE(res);
  2860. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2861. EXPECT_EQ("error", res->body);
  2862. }
  2863. }
  2864. // The pre-request handler must run before the request body is read, so a
  2865. // rejected request never forces the server to buffer a (potentially large)
  2866. // body. Here the posted body is larger than the payload limit: if the body
  2867. // were read first the server would answer 413, but because the pre-request
  2868. // handler runs first it answers 403 and the body is never read.
  2869. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2870. Server svr;
  2871. svr.set_payload_max_length(8);
  2872. auto handler_ran = false;
  2873. svr.Post("/reject", [&](const Request &req, Response &res) {
  2874. handler_ran = true;
  2875. res.set_content(req.body, "text/plain");
  2876. });
  2877. svr.Post("/accept", [](const Request &req, Response &res) {
  2878. res.set_content(req.body, "text/plain");
  2879. });
  2880. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2881. if (req.matched_route == "/reject") {
  2882. res.status = StatusCode::Forbidden_403;
  2883. res.set_content("denied", "text/plain");
  2884. return Server::HandlerResponse::Handled;
  2885. }
  2886. return Server::HandlerResponse::Unhandled;
  2887. });
  2888. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. thread.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. Client cli(HOST, PORT);
  2896. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2897. // rejects with 403 before the body is read, so 413 is never reached.
  2898. {
  2899. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2900. ASSERT_TRUE(res);
  2901. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2902. EXPECT_EQ("denied", res->body);
  2903. EXPECT_FALSE(handler_ran);
  2904. }
  2905. // An approved route still reads the body and enforces the payload limit.
  2906. {
  2907. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2908. ASSERT_TRUE(res);
  2909. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2910. }
  2911. }
  2912. TEST(UserDataTest, BasicOperations) {
  2913. httplib::UserData ud;
  2914. // Initially empty
  2915. EXPECT_FALSE(ud.has("key"));
  2916. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2917. // set and get
  2918. ud.set("key", 42);
  2919. EXPECT_TRUE(ud.has("key"));
  2920. auto *p = ud.get<int>("key");
  2921. ASSERT_NE(nullptr, p);
  2922. EXPECT_EQ(42, *p);
  2923. // Type mismatch → nullptr
  2924. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2925. // Overwrite with different type
  2926. ud.set("key", std::string("hello"));
  2927. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2928. auto *s = ud.get<std::string>("key");
  2929. ASSERT_NE(nullptr, s);
  2930. EXPECT_EQ("hello", *s);
  2931. // erase
  2932. ud.erase("key");
  2933. EXPECT_FALSE(ud.has("key"));
  2934. // clear
  2935. ud.set("a", 1);
  2936. ud.set("b", 2);
  2937. ud.clear();
  2938. EXPECT_FALSE(ud.has("a"));
  2939. EXPECT_FALSE(ud.has("b"));
  2940. }
  2941. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2942. struct AuthCtx {
  2943. std::string user_id;
  2944. };
  2945. Server svr;
  2946. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2947. res.user_data.set("auth", AuthCtx{"alice"});
  2948. return Server::HandlerResponse::Unhandled;
  2949. });
  2950. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2951. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2952. ASSERT_NE(nullptr, ctx);
  2953. res.set_content("Hello " + ctx->user_id, "text/plain");
  2954. });
  2955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2956. auto se = detail::scope_exit([&] {
  2957. svr.stop();
  2958. thread.join();
  2959. ASSERT_FALSE(svr.is_running());
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, PORT);
  2963. auto res = cli.Get("/me");
  2964. ASSERT_TRUE(res);
  2965. EXPECT_EQ(StatusCode::OK_200, res->status);
  2966. EXPECT_EQ("Hello alice", res->body);
  2967. }
  2968. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2969. struct RoleCtx {
  2970. std::string role;
  2971. };
  2972. Server svr;
  2973. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2974. res.user_data.set("role", RoleCtx{"admin"});
  2975. return Server::HandlerResponse::Unhandled;
  2976. });
  2977. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2978. auto *ctx = res.user_data.get<RoleCtx>("role");
  2979. ASSERT_NE(nullptr, ctx);
  2980. res.set_content(ctx->role, "text/plain");
  2981. });
  2982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2983. auto se = detail::scope_exit([&] {
  2984. svr.stop();
  2985. thread.join();
  2986. ASSERT_FALSE(svr.is_running());
  2987. });
  2988. svr.wait_until_ready();
  2989. Client cli(HOST, PORT);
  2990. auto res = cli.Get("/role");
  2991. ASSERT_TRUE(res);
  2992. EXPECT_EQ(StatusCode::OK_200, res->status);
  2993. EXPECT_EQ("admin", res->body);
  2994. }
  2995. TEST(InvalidFormatTest, StatusCode) {
  2996. Server svr;
  2997. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2998. res.set_content("Hello World!\n", "text/plain");
  2999. res.status = 9999; // Status should be a three-digit code...
  3000. });
  3001. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3002. auto se = detail::scope_exit([&] {
  3003. svr.stop();
  3004. thread.join();
  3005. ASSERT_FALSE(svr.is_running());
  3006. });
  3007. svr.wait_until_ready();
  3008. {
  3009. Client cli(HOST, PORT);
  3010. auto res = cli.Get("/hi");
  3011. ASSERT_FALSE(res);
  3012. }
  3013. }
  3014. TEST(URLFragmentTest, WithFragment) {
  3015. Server svr;
  3016. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3017. EXPECT_TRUE(req.target == "/hi");
  3018. });
  3019. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3020. auto se = detail::scope_exit([&] {
  3021. svr.stop();
  3022. thread.join();
  3023. ASSERT_FALSE(svr.is_running());
  3024. });
  3025. svr.wait_until_ready();
  3026. {
  3027. Client cli(HOST, PORT);
  3028. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3029. EXPECT_TRUE(res);
  3030. EXPECT_EQ(StatusCode::OK_200, res->status);
  3031. res = cli.Get("/hi%23key1=val1=key2=val2");
  3032. EXPECT_TRUE(res);
  3033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3034. }
  3035. }
  3036. TEST(HeaderWriter, SetHeaderWriter) {
  3037. Server svr;
  3038. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3039. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3040. return detail::write_headers(strm, hdrs);
  3041. });
  3042. svr.Get("/hi", [](const Request &req, Response &res) {
  3043. auto it = req.headers.find("CustomClientHeader");
  3044. EXPECT_TRUE(it != req.headers.end());
  3045. EXPECT_EQ(it->second, "CustomClientValue");
  3046. res.set_content("Hello World!\n", "text/plain");
  3047. });
  3048. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3049. auto se = detail::scope_exit([&] {
  3050. svr.stop();
  3051. thread.join();
  3052. ASSERT_FALSE(svr.is_running());
  3053. });
  3054. svr.wait_until_ready();
  3055. {
  3056. Client cli(HOST, PORT);
  3057. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3058. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3059. return detail::write_headers(strm, hdrs);
  3060. });
  3061. auto res = cli.Get("/hi");
  3062. EXPECT_TRUE(res);
  3063. EXPECT_EQ(StatusCode::OK_200, res->status);
  3064. auto it = res->headers.find("CustomServerHeader");
  3065. EXPECT_TRUE(it != res->headers.end());
  3066. EXPECT_EQ(it->second, "CustomServerValue");
  3067. }
  3068. }
  3069. class ServerTest : public ::testing::Test {
  3070. protected:
  3071. ServerTest()
  3072. : cli_(HOST, PORT)
  3073. #ifdef CPPHTTPLIB_SSL_ENABLED
  3074. ,
  3075. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3076. #endif
  3077. {
  3078. #ifdef CPPHTTPLIB_SSL_ENABLED
  3079. cli_.enable_server_certificate_verification(false);
  3080. #endif
  3081. // Allow LARGE_DATA (100MB) responses
  3082. cli_.set_payload_max_length(200 * 1024 * 1024);
  3083. }
  3084. virtual void SetUp() {
  3085. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3086. svr_.set_payload_max_length(200 * 1024 * 1024);
  3087. svr_.set_mount_point("/", "./www");
  3088. svr_.set_mount_point("/mount", "./www2");
  3089. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3090. svr_.Get("/hi",
  3091. [&](const Request & /*req*/, Response &res) {
  3092. res.set_content("Hello World!", "text/plain");
  3093. })
  3094. .Get("/file_content",
  3095. [&](const Request & /*req*/, Response &res) {
  3096. res.set_file_content("./www/dir/test.html");
  3097. })
  3098. .Get("/file_content_with_content_type",
  3099. [&](const Request & /*req*/, Response &res) {
  3100. res.set_file_content("./www/file", "text/plain");
  3101. })
  3102. .Get("/invalid_file_content",
  3103. [&](const Request & /*req*/, Response &res) {
  3104. res.set_file_content("./www/dir/invalid_file_path");
  3105. })
  3106. .Get("/http_response_splitting",
  3107. [&](const Request & /*req*/, Response &res) {
  3108. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3109. EXPECT_EQ(0U, res.headers.size());
  3110. EXPECT_FALSE(res.has_header("a"));
  3111. res.set_header("a", "1\nSet-Cookie: a=1");
  3112. EXPECT_EQ(0U, res.headers.size());
  3113. EXPECT_FALSE(res.has_header("a"));
  3114. res.set_header("a", "1\rSet-Cookie: a=1");
  3115. EXPECT_EQ(0U, res.headers.size());
  3116. EXPECT_FALSE(res.has_header("a"));
  3117. res.set_header("a\r\nb", "0");
  3118. EXPECT_EQ(0U, res.headers.size());
  3119. EXPECT_FALSE(res.has_header("a"));
  3120. res.set_header("a\rb", "0");
  3121. EXPECT_EQ(0U, res.headers.size());
  3122. EXPECT_FALSE(res.has_header("a"));
  3123. res.set_header("a\nb", "0");
  3124. EXPECT_EQ(0U, res.headers.size());
  3125. EXPECT_FALSE(res.has_header("a"));
  3126. res.set_redirect("1\r\nSet-Cookie: a=1");
  3127. EXPECT_EQ(0U, res.headers.size());
  3128. EXPECT_FALSE(res.has_header("Location"));
  3129. })
  3130. .Get("/slow",
  3131. [&](const Request & /*req*/, Response &res) {
  3132. std::this_thread::sleep_for(std::chrono::seconds(4));
  3133. res.set_content("slow", "text/plain");
  3134. })
  3135. #if 0
  3136. .Post("/slowpost",
  3137. [&](const Request & /*req*/, Response &res) {
  3138. std::this_thread::sleep_for(std::chrono::seconds(2));
  3139. res.set_content("slow", "text/plain");
  3140. })
  3141. #endif
  3142. .Get("/remote_addr",
  3143. [&](const Request &req, Response &res) {
  3144. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3145. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3146. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3147. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3148. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3149. #endif
  3150. res.set_content(req.remote_addr, "text/plain");
  3151. })
  3152. .Get("/local_addr",
  3153. [&](const Request &req, Response &res) {
  3154. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3155. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3156. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3157. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3158. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3159. #endif
  3160. auto local_addr = req.local_addr;
  3161. auto local_port = std::to_string(req.local_port);
  3162. res.set_content(local_addr.append(":").append(local_port),
  3163. "text/plain");
  3164. })
  3165. .Get("/endwith%",
  3166. [&](const Request & /*req*/, Response &res) {
  3167. res.set_content("Hello World!", "text/plain");
  3168. })
  3169. .Get("/a\\+\\+b",
  3170. [&](const Request &req, Response &res) {
  3171. ASSERT_TRUE(req.has_param("a +b"));
  3172. auto val = req.get_param_value("a +b");
  3173. res.set_content(val, "text/plain");
  3174. })
  3175. .Get("/", [&](const Request & /*req*/,
  3176. Response &res) { res.set_redirect("/hi"); })
  3177. .Post("/1",
  3178. [](const Request & /*req*/, Response &res) {
  3179. res.set_redirect("/2", StatusCode::SeeOther_303);
  3180. })
  3181. .Get("/2",
  3182. [](const Request & /*req*/, Response &res) {
  3183. res.set_content("redirected.", "text/plain");
  3184. res.status = StatusCode::OK_200;
  3185. })
  3186. .Post("/person",
  3187. [&](const Request &req, Response &res) {
  3188. if (req.has_param("name") && req.has_param("note")) {
  3189. persons_[req.get_param_value("name")] =
  3190. req.get_param_value("note");
  3191. } else {
  3192. res.status = StatusCode::BadRequest_400;
  3193. }
  3194. })
  3195. .Put("/person",
  3196. [&](const Request &req, Response &res) {
  3197. if (req.has_param("name") && req.has_param("note")) {
  3198. persons_[req.get_param_value("name")] =
  3199. req.get_param_value("note");
  3200. } else {
  3201. res.status = StatusCode::BadRequest_400;
  3202. }
  3203. })
  3204. .Get("/person/(.*)",
  3205. [&](const Request &req, Response &res) {
  3206. string name = req.matches[1];
  3207. if (persons_.find(name) != persons_.end()) {
  3208. auto note = persons_[name];
  3209. res.set_content(note, "text/plain");
  3210. } else {
  3211. res.status = StatusCode::NotFound_404;
  3212. }
  3213. })
  3214. .Delete("/person",
  3215. [&](const Request &req, Response &res) {
  3216. if (req.has_param("name")) {
  3217. string name = req.get_param_value("name");
  3218. if (persons_.find(name) != persons_.end()) {
  3219. persons_.erase(name);
  3220. res.set_content("DELETED", "text/plain");
  3221. } else {
  3222. res.status = StatusCode::NotFound_404;
  3223. }
  3224. } else {
  3225. res.status = StatusCode::BadRequest_400;
  3226. }
  3227. })
  3228. .Post("/x-www-form-urlencoded-json",
  3229. [&](const Request &req, Response &res) {
  3230. auto json = req.get_param_value("json");
  3231. ASSERT_EQ(JSON_DATA, json);
  3232. res.set_content(json, "appliation/json");
  3233. res.status = StatusCode::OK_200;
  3234. })
  3235. .Get("/streamed-chunked",
  3236. [&](const Request & /*req*/, Response &res) {
  3237. res.set_chunked_content_provider(
  3238. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3239. sink.os << "123";
  3240. sink.os << "456";
  3241. sink.os << "789";
  3242. sink.done();
  3243. return true;
  3244. });
  3245. })
  3246. .Get("/streamed-chunked-with-prohibited-trailer",
  3247. [&](const Request & /*req*/, Response &res) {
  3248. auto i = new int(0);
  3249. // Declare both a prohibited trailer (Content-Length) and an
  3250. // allowed one
  3251. res.set_header("Trailer", "Content-Length, X-Allowed");
  3252. res.set_chunked_content_provider(
  3253. "text/plain",
  3254. [i](size_t /*offset*/, DataSink &sink) {
  3255. switch (*i) {
  3256. case 0: sink.os << "123"; break;
  3257. case 1: sink.os << "456"; break;
  3258. case 2: sink.os << "789"; break;
  3259. case 3: {
  3260. sink.done_with_trailer(
  3261. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3262. } break;
  3263. }
  3264. (*i)++;
  3265. return true;
  3266. },
  3267. [i](bool success) {
  3268. EXPECT_TRUE(success);
  3269. delete i;
  3270. });
  3271. })
  3272. .Get("/streamed-chunked2",
  3273. [&](const Request & /*req*/, Response &res) {
  3274. auto i = new int(0);
  3275. res.set_chunked_content_provider(
  3276. "text/plain",
  3277. [i](size_t /*offset*/, DataSink &sink) {
  3278. switch (*i) {
  3279. case 0: sink.os << "123"; break;
  3280. case 1: sink.os << "456"; break;
  3281. case 2: sink.os << "789"; break;
  3282. case 3: sink.done(); break;
  3283. }
  3284. (*i)++;
  3285. return true;
  3286. },
  3287. [i](bool success) {
  3288. EXPECT_TRUE(success);
  3289. delete i;
  3290. });
  3291. })
  3292. .Get("/streamed-chunked-with-trailer",
  3293. [&](const Request & /*req*/, Response &res) {
  3294. auto i = new int(0);
  3295. res.set_header("Trailer", "Dummy1, Dummy2");
  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: {
  3304. sink.done_with_trailer(
  3305. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3306. } break;
  3307. }
  3308. (*i)++;
  3309. return true;
  3310. },
  3311. [i](bool success) {
  3312. EXPECT_TRUE(success);
  3313. delete i;
  3314. });
  3315. })
  3316. .Get("/streamed",
  3317. [&](const Request & /*req*/, Response &res) {
  3318. res.set_content_provider(
  3319. 6, "text/plain",
  3320. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3321. sink.os << (offset < 3 ? "a" : "b");
  3322. return true;
  3323. });
  3324. })
  3325. .Get("/streamed-without-length",
  3326. [&](const Request & /*req*/, Response &res) {
  3327. auto data = new std::string("abcdefg");
  3328. res.set_content_provider(
  3329. "text/plain",
  3330. [data](size_t offset, DataSink &sink) {
  3331. if (offset < data->size()) {
  3332. sink.os << data->substr(offset);
  3333. }
  3334. sink.done();
  3335. return true;
  3336. },
  3337. [data](bool success) {
  3338. EXPECT_TRUE(success);
  3339. delete data;
  3340. });
  3341. })
  3342. .Get("/streamed-with-range",
  3343. [&](const Request &req, Response &res) {
  3344. auto data = new std::string("abcdefg");
  3345. res.set_content_provider(
  3346. data->size(), "text/plain",
  3347. [data](size_t offset, size_t length, DataSink &sink) {
  3348. size_t DATA_CHUNK_SIZE = 4;
  3349. const auto &d = *data;
  3350. auto out_len =
  3351. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3352. auto ret =
  3353. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3354. EXPECT_TRUE(ret);
  3355. return true;
  3356. },
  3357. [data, &req](bool success) {
  3358. EXPECT_EQ(success, !req.has_param("error"));
  3359. delete data;
  3360. });
  3361. })
  3362. .Get("/streamed-cancel",
  3363. [&](const Request & /*req*/, Response &res) {
  3364. res.set_content_provider(
  3365. size_t(-1), "text/plain",
  3366. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3367. sink.os << "data_chunk";
  3368. return true;
  3369. });
  3370. })
  3371. .Get("/regex-with-delimiter",
  3372. [&](const Request &req, Response & /*res*/) {
  3373. ASSERT_TRUE(req.has_param("key"));
  3374. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3375. })
  3376. .Get("/with-range",
  3377. [&](const Request & /*req*/, Response &res) {
  3378. res.set_content("abcdefg", "text/plain");
  3379. })
  3380. .Get("/test-start-time",
  3381. [&](const Request &req, Response & /*res*/) {
  3382. EXPECT_NE(req.start_time_,
  3383. std::chrono::steady_clock::time_point::min());
  3384. })
  3385. .Get("/with-range-customized-response",
  3386. [&](const Request & /*req*/, Response &res) {
  3387. res.status = StatusCode::BadRequest_400;
  3388. res.set_content(JSON_DATA, "application/json");
  3389. })
  3390. .Post("/chunked",
  3391. [&](const Request &req, Response & /*res*/) {
  3392. EXPECT_EQ(req.body, "dechunked post body");
  3393. })
  3394. .Post("/large-chunked",
  3395. [&](const Request &req, Response & /*res*/) {
  3396. std::string expected(6 * 30 * 1024u, 'a');
  3397. EXPECT_EQ(req.body, expected);
  3398. })
  3399. .Post("/multipart",
  3400. [&](const Request &req, Response & /*res*/) {
  3401. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3402. req.form.get_field_count("text2") +
  3403. req.form.get_field_count("file3") +
  3404. req.form.get_field_count("file4"));
  3405. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3406. req.form.get_file_count("file2"));
  3407. ASSERT_TRUE(!req.form.has_file("???"));
  3408. ASSERT_TRUE(!req.form.has_field("???"));
  3409. ASSERT_TRUE(req.body.empty());
  3410. {
  3411. const auto &text = req.form.get_field("text1");
  3412. EXPECT_EQ("text default", text);
  3413. }
  3414. {
  3415. const auto &text = req.form.get_field("text2");
  3416. EXPECT_EQ("aωb", text);
  3417. }
  3418. {
  3419. const auto &file = req.form.get_file("file1");
  3420. EXPECT_EQ("hello.txt", file.filename);
  3421. EXPECT_EQ("text/plain", file.content_type);
  3422. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3423. }
  3424. {
  3425. const auto &file = req.form.get_file("file2");
  3426. EXPECT_EQ("world.json", file.filename);
  3427. EXPECT_EQ("application/json", file.content_type);
  3428. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3429. }
  3430. {
  3431. const auto &text = req.form.get_field("file3");
  3432. EXPECT_EQ(0u, text.size());
  3433. }
  3434. {
  3435. const auto &text = req.form.get_field("file4");
  3436. EXPECT_EQ(0u, text.size());
  3437. }
  3438. })
  3439. .Post("/multipart/multi_file_values",
  3440. [&](const Request &req, Response & /*res*/) {
  3441. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3442. req.form.get_field_count("multi_text1"));
  3443. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3444. ASSERT_TRUE(!req.form.has_file("???"));
  3445. ASSERT_TRUE(!req.form.has_field("???"));
  3446. ASSERT_TRUE(req.body.empty());
  3447. {
  3448. const auto &text = req.form.get_field("text");
  3449. EXPECT_EQ("default text", text);
  3450. }
  3451. {
  3452. const auto &text1_values = req.form.get_fields("multi_text1");
  3453. EXPECT_EQ(2u, text1_values.size());
  3454. EXPECT_EQ("aaaaa", text1_values[0]);
  3455. EXPECT_EQ("bbbbb", text1_values[1]);
  3456. }
  3457. {
  3458. const auto &file1_values = req.form.get_files("multi_file1");
  3459. EXPECT_EQ(2u, file1_values.size());
  3460. auto file1 = file1_values[0];
  3461. EXPECT_EQ(file1.filename, "hello.txt");
  3462. EXPECT_EQ(file1.content_type, "text/plain");
  3463. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3464. auto file2 = file1_values[1];
  3465. EXPECT_EQ(file2.filename, "world.json");
  3466. EXPECT_EQ(file2.content_type, "application/json");
  3467. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3468. }
  3469. })
  3470. .Post("/empty",
  3471. [&](const Request &req, Response &res) {
  3472. EXPECT_EQ(req.body, "");
  3473. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3474. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3475. res.set_content("empty", "text/plain");
  3476. })
  3477. .Post("/empty-no-content-type",
  3478. [&](const Request &req, Response &res) {
  3479. EXPECT_EQ(req.body, "");
  3480. EXPECT_FALSE(req.has_header("Content-Type"));
  3481. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3482. res.set_content("empty-no-content-type", "text/plain");
  3483. })
  3484. .Post("/path-only",
  3485. [&](const Request &req, Response &res) {
  3486. EXPECT_EQ(req.body, "");
  3487. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3488. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3489. res.set_content("path-only", "text/plain");
  3490. })
  3491. .Post("/path-headers-only",
  3492. [&](const Request &req, Response &res) {
  3493. EXPECT_EQ(req.body, "");
  3494. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3495. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3496. EXPECT_EQ("world", req.get_header_value("hello"));
  3497. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3498. res.set_content("path-headers-only", "text/plain");
  3499. })
  3500. .Post("/post-large",
  3501. [&](const Request &req, Response &res) {
  3502. EXPECT_EQ(req.body, LARGE_DATA);
  3503. res.set_content(req.body, "text/plain");
  3504. })
  3505. .Post("/post-loopback",
  3506. [&](const Request &, Response &res,
  3507. ContentReader const &content_reader) {
  3508. std::string body;
  3509. content_reader([&](const char *data, size_t data_length) {
  3510. body.append(data, data_length);
  3511. return true;
  3512. });
  3513. res.set_content(body, "text/plain");
  3514. })
  3515. .Put("/put-loopback",
  3516. [&](const Request &, Response &res,
  3517. ContentReader const &content_reader) {
  3518. std::string body;
  3519. content_reader([&](const char *data, size_t data_length) {
  3520. body.append(data, data_length);
  3521. return true;
  3522. });
  3523. res.set_content(body, "text/plain");
  3524. })
  3525. .Patch("/patch-loopback",
  3526. [&](const Request &, Response &res,
  3527. ContentReader const &content_reader) {
  3528. std::string body;
  3529. content_reader([&](const char *data, size_t data_length) {
  3530. body.append(data, data_length);
  3531. return true;
  3532. });
  3533. res.set_content(body, "text/plain");
  3534. })
  3535. .Put("/empty-no-content-type",
  3536. [&](const Request &req, Response &res) {
  3537. EXPECT_EQ(req.body, "");
  3538. EXPECT_FALSE(req.has_header("Content-Type"));
  3539. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3540. res.set_content("empty-no-content-type", "text/plain");
  3541. })
  3542. .Put("/put",
  3543. [&](const Request &req, Response &res) {
  3544. EXPECT_EQ(req.body, "PUT");
  3545. res.set_content(req.body, "text/plain");
  3546. })
  3547. .Put("/put-large",
  3548. [&](const Request &req, Response &res) {
  3549. EXPECT_EQ(req.body, LARGE_DATA);
  3550. res.set_content(req.body, "text/plain");
  3551. })
  3552. .Patch("/patch",
  3553. [&](const Request &req, Response &res) {
  3554. EXPECT_EQ(req.body, "PATCH");
  3555. res.set_content(req.body, "text/plain");
  3556. })
  3557. .Delete("/delete",
  3558. [&](const Request & /*req*/, Response &res) {
  3559. res.set_content("DELETE", "text/plain");
  3560. })
  3561. .Delete("/delete-body",
  3562. [&](const Request &req, Response &res) {
  3563. EXPECT_EQ(req.body, "content");
  3564. res.set_content(req.body, "text/plain");
  3565. })
  3566. .Options(R"(\*)",
  3567. [&](const Request & /*req*/, Response &res) {
  3568. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3569. })
  3570. .Get("/request-target",
  3571. [&](const Request &req, Response & /*res*/) {
  3572. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3573. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3574. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3575. })
  3576. .Get("/long-query-value",
  3577. [&](const Request &req, Response & /*res*/) {
  3578. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3579. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3580. })
  3581. .Get("/too-long-query-value",
  3582. [&](const Request &req, Response & /*res*/) {
  3583. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3584. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3585. })
  3586. .Get("/array-param",
  3587. [&](const Request &req, Response & /*res*/) {
  3588. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3589. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3590. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3591. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3592. })
  3593. .Get("/array-param-values",
  3594. [&](const Request &req, Response & /*res*/) {
  3595. auto values = req.get_param_values("array");
  3596. EXPECT_EQ(3u, values.size());
  3597. EXPECT_EQ("value1", values[0]);
  3598. EXPECT_EQ("value2", values[1]);
  3599. EXPECT_EQ("value3", values[2]);
  3600. auto empty = req.get_param_values("nonexistent");
  3601. EXPECT_TRUE(empty.empty());
  3602. })
  3603. .Post("/validate-no-multiple-headers",
  3604. [&](const Request &req, Response & /*res*/) {
  3605. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3606. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3607. })
  3608. .Post("/content_receiver",
  3609. [&](const Request &req, Response &res,
  3610. const ContentReader &content_reader) {
  3611. if (req.is_multipart_form_data()) {
  3612. std::vector<FormData> items;
  3613. content_reader(
  3614. [&](const FormData &file) {
  3615. items.push_back(file);
  3616. return true;
  3617. },
  3618. [&](const char *data, size_t data_length) {
  3619. items.back().content.append(data, data_length);
  3620. return true;
  3621. });
  3622. EXPECT_EQ(5u, items.size());
  3623. {
  3624. const auto &file = get_file_value(items, "text1");
  3625. EXPECT_TRUE(file.filename.empty());
  3626. EXPECT_EQ("text default", file.content);
  3627. }
  3628. {
  3629. const auto &file = get_file_value(items, "text2");
  3630. EXPECT_TRUE(file.filename.empty());
  3631. EXPECT_EQ("aωb", file.content);
  3632. }
  3633. {
  3634. const auto &file = get_file_value(items, "file1");
  3635. EXPECT_EQ("hello.txt", file.filename);
  3636. EXPECT_EQ("text/plain", file.content_type);
  3637. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3638. }
  3639. {
  3640. const auto &file = get_file_value(items, "file2");
  3641. EXPECT_EQ("world.json", file.filename);
  3642. EXPECT_EQ("application/json", file.content_type);
  3643. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3644. }
  3645. {
  3646. const auto &file = get_file_value(items, "file3");
  3647. EXPECT_TRUE(file.filename.empty());
  3648. EXPECT_EQ("application/octet-stream", file.content_type);
  3649. EXPECT_EQ(0u, file.content.size());
  3650. }
  3651. } else {
  3652. std::string body;
  3653. content_reader([&](const char *data, size_t data_length) {
  3654. EXPECT_EQ(7U, data_length);
  3655. body.append(data, data_length);
  3656. return true;
  3657. });
  3658. EXPECT_EQ(body, "content");
  3659. res.set_content(body, "text/plain");
  3660. }
  3661. })
  3662. .Put("/content_receiver",
  3663. [&](const Request & /*req*/, Response &res,
  3664. const ContentReader &content_reader) {
  3665. std::string body;
  3666. content_reader([&](const char *data, size_t data_length) {
  3667. body.append(data, data_length);
  3668. return true;
  3669. });
  3670. EXPECT_EQ(body, "content");
  3671. res.set_content(body, "text/plain");
  3672. })
  3673. .Patch("/content_receiver",
  3674. [&](const Request & /*req*/, Response &res,
  3675. const ContentReader &content_reader) {
  3676. std::string body;
  3677. content_reader([&](const char *data, size_t data_length) {
  3678. body.append(data, data_length);
  3679. return true;
  3680. });
  3681. EXPECT_EQ(body, "content");
  3682. res.set_content(body, "text/plain");
  3683. })
  3684. .Post("/query-string-and-body",
  3685. [&](const Request &req, Response & /*res*/) {
  3686. ASSERT_TRUE(req.has_param("key"));
  3687. EXPECT_EQ(req.get_param_value("key"), "value");
  3688. EXPECT_EQ(req.body, "content");
  3689. })
  3690. .Get("/last-request",
  3691. [&](const Request &req, Response & /*res*/) {
  3692. EXPECT_EQ("close", req.get_header_value("Connection"));
  3693. })
  3694. .Get(R"(/redirect/(\d+))",
  3695. [&](const Request &req, Response &res) {
  3696. auto num = std::stoi(req.matches[1]) + 1;
  3697. std::string url = "/redirect/" + std::to_string(num);
  3698. res.set_redirect(url);
  3699. })
  3700. .Post("/binary",
  3701. [&](const Request &req, Response &res) {
  3702. EXPECT_EQ(4U, req.body.size());
  3703. EXPECT_EQ("application/octet-stream",
  3704. req.get_header_value("Content-Type"));
  3705. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3706. res.set_content(req.body, "application/octet-stream");
  3707. })
  3708. .Put("/binary",
  3709. [&](const Request &req, Response &res) {
  3710. EXPECT_EQ(4U, req.body.size());
  3711. EXPECT_EQ("application/octet-stream",
  3712. req.get_header_value("Content-Type"));
  3713. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3714. res.set_content(req.body, "application/octet-stream");
  3715. })
  3716. .Patch("/binary",
  3717. [&](const Request &req, Response &res) {
  3718. EXPECT_EQ(4U, req.body.size());
  3719. EXPECT_EQ("application/octet-stream",
  3720. req.get_header_value("Content-Type"));
  3721. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3722. res.set_content(req.body, "application/octet-stream");
  3723. })
  3724. .Delete("/binary",
  3725. [&](const Request &req, Response &res) {
  3726. EXPECT_EQ(4U, req.body.size());
  3727. EXPECT_EQ("application/octet-stream",
  3728. req.get_header_value("Content-Type"));
  3729. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3730. res.set_content(req.body, "application/octet-stream");
  3731. })
  3732. .Get("/issue1772",
  3733. [&](const Request & /*req*/, Response &res) {
  3734. res.status = 401;
  3735. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3736. })
  3737. .Delete("/issue609",
  3738. [](const httplib::Request &, httplib::Response &res,
  3739. const httplib::ContentReader &) {
  3740. res.set_content("ok", "text/plain");
  3741. })
  3742. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3743. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3744. .Get("/compress",
  3745. [&](const Request & /*req*/, Response &res) {
  3746. res.set_content(
  3747. "12345678901234567890123456789012345678901234567890123456789"
  3748. "01234567890123456789012345678901234567890",
  3749. "text/plain");
  3750. })
  3751. .Get("/compress-with-charset",
  3752. [&](const Request & /*req*/, Response &res) {
  3753. res.set_content(
  3754. "12345678901234567890123456789012345678901234567890123456789"
  3755. "01234567890123456789012345678901234567890",
  3756. "application/json; charset=utf-8");
  3757. })
  3758. .Get("/nocompress",
  3759. [&](const Request & /*req*/, Response &res) {
  3760. res.set_content(
  3761. "12345678901234567890123456789012345678901234567890123456789"
  3762. "01234567890123456789012345678901234567890",
  3763. "application/octet-stream");
  3764. })
  3765. .Post("/compress-multipart",
  3766. [&](const Request &req, Response & /*res*/) {
  3767. EXPECT_EQ(2u, req.form.fields.size());
  3768. ASSERT_TRUE(!req.form.has_field("???"));
  3769. {
  3770. const auto &text = req.form.get_field("key1");
  3771. EXPECT_EQ("test", text);
  3772. }
  3773. {
  3774. const auto &text = req.form.get_field("key2");
  3775. EXPECT_EQ("--abcdefg123", text);
  3776. }
  3777. })
  3778. #endif
  3779. ;
  3780. persons_["john"] = "programmer";
  3781. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3782. svr_.wait_until_ready();
  3783. }
  3784. virtual void TearDown() {
  3785. svr_.stop();
  3786. if (!request_threads_.empty()) {
  3787. std::this_thread::sleep_for(std::chrono::seconds(1));
  3788. for (auto &t : request_threads_) {
  3789. t.join();
  3790. }
  3791. }
  3792. t_.join();
  3793. }
  3794. map<string, string> persons_;
  3795. #ifdef CPPHTTPLIB_SSL_ENABLED
  3796. SSLClient cli_;
  3797. SSLServer svr_;
  3798. #else
  3799. Client cli_;
  3800. Server svr_;
  3801. #endif
  3802. thread t_;
  3803. std::vector<thread> request_threads_;
  3804. };
  3805. TEST_F(ServerTest, GetMethod200) {
  3806. auto res = cli_.Get("/hi");
  3807. ASSERT_TRUE(res);
  3808. EXPECT_EQ("HTTP/1.1", res->version);
  3809. EXPECT_EQ(StatusCode::OK_200, res->status);
  3810. EXPECT_EQ("OK", res->reason);
  3811. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3812. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3813. EXPECT_EQ("Hello World!", res->body);
  3814. }
  3815. TEST_F(ServerTest, GetEmptyFile) {
  3816. auto res = cli_.Get("/empty_file");
  3817. ASSERT_TRUE(res);
  3818. EXPECT_EQ(StatusCode::OK_200, res->status);
  3819. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3820. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3821. EXPECT_EQ("", res->body);
  3822. }
  3823. TEST_F(ServerTest, GetFileContent) {
  3824. auto res = cli_.Get("/file_content");
  3825. ASSERT_TRUE(res);
  3826. EXPECT_EQ(StatusCode::OK_200, res->status);
  3827. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3828. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3829. EXPECT_EQ("test.html", res->body);
  3830. }
  3831. TEST_F(ServerTest, GetFileContentWithRange) {
  3832. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3833. ASSERT_TRUE(res);
  3834. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3835. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3836. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3837. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3838. EXPECT_EQ("est", res->body);
  3839. }
  3840. TEST_F(ServerTest, GetFileContentWithContentType) {
  3841. auto res = cli_.Get("/file_content_with_content_type");
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(StatusCode::OK_200, res->status);
  3844. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3845. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3846. EXPECT_EQ("file\n", res->body);
  3847. }
  3848. TEST_F(ServerTest, GetInvalidFileContent) {
  3849. auto res = cli_.Get("/invalid_file_content");
  3850. ASSERT_TRUE(res);
  3851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3852. }
  3853. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3854. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3855. ASSERT_TRUE(res);
  3856. EXPECT_EQ("HTTP/1.1", res->version);
  3857. EXPECT_EQ(StatusCode::OK_200, res->status);
  3858. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3859. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3860. EXPECT_EQ("Hello World!", res->body);
  3861. }
  3862. TEST_F(ServerTest, GetMethod302) {
  3863. auto res = cli_.Get("/");
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ(StatusCode::Found_302, res->status);
  3866. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3867. }
  3868. TEST_F(ServerTest, GetMethod302Redirect) {
  3869. cli_.set_follow_location(true);
  3870. auto res = cli_.Get("/");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(StatusCode::OK_200, res->status);
  3873. EXPECT_EQ("Hello World!", res->body);
  3874. EXPECT_EQ("/hi", res->location);
  3875. }
  3876. TEST_F(ServerTest, GetMethod404) {
  3877. auto res = cli_.Get("/invalid");
  3878. ASSERT_TRUE(res);
  3879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3880. }
  3881. TEST_F(ServerTest, HeadMethod200) {
  3882. auto res = cli_.Head("/hi");
  3883. ASSERT_TRUE(res);
  3884. EXPECT_EQ(StatusCode::OK_200, res->status);
  3885. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3886. EXPECT_TRUE(res->body.empty());
  3887. }
  3888. TEST_F(ServerTest, HeadMethod200Static) {
  3889. auto res = cli_.Head("/mount/dir/index.html");
  3890. ASSERT_TRUE(res);
  3891. EXPECT_EQ(StatusCode::OK_200, res->status);
  3892. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3893. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3894. EXPECT_TRUE(res->body.empty());
  3895. }
  3896. TEST_F(ServerTest, HeadMethod404) {
  3897. auto res = cli_.Head("/invalid");
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3900. EXPECT_TRUE(res->body.empty());
  3901. }
  3902. TEST_F(ServerTest, GetMethodPersonJohn) {
  3903. auto res = cli_.Get("/person/john");
  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_EQ("programmer", res->body);
  3908. }
  3909. TEST_F(ServerTest, PostMethod1) {
  3910. auto res = cli_.Get("/person/john1");
  3911. ASSERT_TRUE(res);
  3912. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3913. res = cli_.Post("/person", "name=john1&note=coder",
  3914. "application/x-www-form-urlencoded");
  3915. ASSERT_TRUE(res);
  3916. ASSERT_EQ(StatusCode::OK_200, res->status);
  3917. res = cli_.Get("/person/john1");
  3918. ASSERT_TRUE(res);
  3919. ASSERT_EQ(StatusCode::OK_200, res->status);
  3920. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3921. ASSERT_EQ("coder", res->body);
  3922. }
  3923. TEST_F(ServerTest, PostMethod2) {
  3924. auto res = cli_.Get("/person/john2");
  3925. ASSERT_TRUE(res);
  3926. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3927. Params params;
  3928. params.emplace("name", "john2");
  3929. params.emplace("note", "coder");
  3930. res = cli_.Post("/person", params);
  3931. ASSERT_TRUE(res);
  3932. ASSERT_EQ(StatusCode::OK_200, res->status);
  3933. res = cli_.Get("/person/john2");
  3934. ASSERT_TRUE(res);
  3935. ASSERT_EQ(StatusCode::OK_200, res->status);
  3936. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3937. ASSERT_EQ("coder", res->body);
  3938. }
  3939. TEST_F(ServerTest, PutMethod3) {
  3940. auto res = cli_.Get("/person/john3");
  3941. ASSERT_TRUE(res);
  3942. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3943. Params params;
  3944. params.emplace("name", "john3");
  3945. params.emplace("note", "coder");
  3946. res = cli_.Put("/person", params);
  3947. ASSERT_TRUE(res);
  3948. ASSERT_EQ(StatusCode::OK_200, res->status);
  3949. res = cli_.Get("/person/john3");
  3950. ASSERT_TRUE(res);
  3951. ASSERT_EQ(StatusCode::OK_200, res->status);
  3952. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3953. ASSERT_EQ("coder", res->body);
  3954. }
  3955. TEST_F(ServerTest, DeleteMethod1) {
  3956. auto res = cli_.Get("/person/john4");
  3957. ASSERT_TRUE(res);
  3958. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3959. Params params;
  3960. params.emplace("name", "john4");
  3961. params.emplace("note", "coder");
  3962. res = cli_.Post("/person", params);
  3963. ASSERT_TRUE(res);
  3964. ASSERT_EQ(StatusCode::OK_200, res->status);
  3965. res = cli_.Get("/person/john4");
  3966. ASSERT_TRUE(res);
  3967. ASSERT_EQ(StatusCode::OK_200, res->status);
  3968. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3969. ASSERT_EQ("coder", res->body);
  3970. Params delete_params;
  3971. delete_params.emplace("name", "john4");
  3972. res = cli_.Delete("/person", delete_params);
  3973. ASSERT_TRUE(res);
  3974. ASSERT_EQ(StatusCode::OK_200, res->status);
  3975. ASSERT_EQ("DELETED", res->body);
  3976. res = cli_.Get("/person/john4");
  3977. ASSERT_TRUE(res);
  3978. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3979. }
  3980. TEST_F(ServerTest, DeleteMethod2) {
  3981. auto res = cli_.Get("/person/john5");
  3982. ASSERT_TRUE(res);
  3983. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3984. Params params;
  3985. params.emplace("name", "john5");
  3986. params.emplace("note", "developer");
  3987. res = cli_.Post("/person", params);
  3988. ASSERT_TRUE(res);
  3989. ASSERT_EQ(StatusCode::OK_200, res->status);
  3990. res = cli_.Get("/person/john5");
  3991. ASSERT_TRUE(res);
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3994. ASSERT_EQ("developer", res->body);
  3995. Params delete_params;
  3996. delete_params.emplace("name", "john5");
  3997. Headers headers;
  3998. headers.emplace("Custom-Header", "test-value");
  3999. res = cli_.Delete("/person", headers, delete_params);
  4000. ASSERT_TRUE(res);
  4001. ASSERT_EQ(StatusCode::OK_200, res->status);
  4002. ASSERT_EQ("DELETED", res->body);
  4003. res = cli_.Get("/person/john5");
  4004. ASSERT_TRUE(res);
  4005. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4006. }
  4007. TEST_F(ServerTest, DeleteMethod3) {
  4008. auto res = cli_.Get("/person/john6");
  4009. ASSERT_TRUE(res);
  4010. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4011. Params params;
  4012. params.emplace("name", "john6");
  4013. params.emplace("note", "tester");
  4014. res = cli_.Post("/person", params);
  4015. ASSERT_TRUE(res);
  4016. ASSERT_EQ(StatusCode::OK_200, res->status);
  4017. res = cli_.Get("/person/john6");
  4018. ASSERT_TRUE(res);
  4019. ASSERT_EQ(StatusCode::OK_200, res->status);
  4020. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4021. ASSERT_EQ("tester", res->body);
  4022. Params delete_params;
  4023. delete_params.emplace("name", "john6");
  4024. Headers headers;
  4025. headers.emplace("Custom-Header", "test-value");
  4026. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4027. ASSERT_TRUE(res);
  4028. ASSERT_EQ(StatusCode::OK_200, res->status);
  4029. ASSERT_EQ("DELETED", res->body);
  4030. res = cli_.Get("/person/john6");
  4031. ASSERT_TRUE(res);
  4032. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4033. }
  4034. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4035. Params params;
  4036. params.emplace("json", JSON_DATA);
  4037. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4038. ASSERT_TRUE(res);
  4039. ASSERT_EQ(StatusCode::OK_200, res->status);
  4040. ASSERT_EQ(JSON_DATA, res->body);
  4041. }
  4042. TEST_F(ServerTest, PostEmptyContent) {
  4043. auto res = cli_.Post("/empty", "", "text/plain");
  4044. ASSERT_TRUE(res);
  4045. ASSERT_EQ(StatusCode::OK_200, res->status);
  4046. ASSERT_EQ("empty", res->body);
  4047. }
  4048. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4049. auto res = cli_.Post("/empty-no-content-type");
  4050. ASSERT_TRUE(res);
  4051. ASSERT_EQ(StatusCode::OK_200, res->status);
  4052. ASSERT_EQ("empty-no-content-type", res->body);
  4053. }
  4054. TEST_F(ServerTest, PostPathOnly) {
  4055. auto res = cli_.Post("/path-only");
  4056. ASSERT_TRUE(res);
  4057. ASSERT_EQ(StatusCode::OK_200, res->status);
  4058. ASSERT_EQ("path-only", res->body);
  4059. }
  4060. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4061. auto res = cli_.Post("/path-headers-only",
  4062. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4063. ASSERT_TRUE(res);
  4064. ASSERT_EQ(StatusCode::OK_200, res->status);
  4065. ASSERT_EQ("path-headers-only", res->body);
  4066. }
  4067. TEST_F(ServerTest, PostLarge) {
  4068. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4069. ASSERT_TRUE(res);
  4070. ASSERT_EQ(StatusCode::OK_200, res->status);
  4071. EXPECT_EQ(LARGE_DATA, res->body);
  4072. }
  4073. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4074. auto res = cli_.Put("/empty-no-content-type");
  4075. ASSERT_TRUE(res);
  4076. ASSERT_EQ(StatusCode::OK_200, res->status);
  4077. ASSERT_EQ("empty-no-content-type", res->body);
  4078. }
  4079. TEST_F(ServerTest, GetMethodDir) {
  4080. auto res = cli_.Get("/dir/");
  4081. ASSERT_TRUE(res);
  4082. EXPECT_EQ(StatusCode::OK_200, res->status);
  4083. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4084. auto body = R"(<html>
  4085. <head>
  4086. </head>
  4087. <body>
  4088. <a href="/dir/test.html">Test</a>
  4089. <a href="/hi">hi</a>
  4090. </body>
  4091. </html>
  4092. )";
  4093. EXPECT_EQ(body, res->body);
  4094. }
  4095. TEST_F(ServerTest, GetMethodDirTest) {
  4096. auto res = cli_.Get("/dir/test.html");
  4097. ASSERT_TRUE(res);
  4098. EXPECT_EQ(StatusCode::OK_200, res->status);
  4099. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4100. EXPECT_EQ("test.html", res->body);
  4101. }
  4102. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4103. auto res = cli_.Get("/dir/../dir/test.html");
  4104. ASSERT_TRUE(res);
  4105. EXPECT_EQ(StatusCode::OK_200, res->status);
  4106. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4107. EXPECT_EQ("test.html", res->body);
  4108. }
  4109. TEST_F(ServerTest, GetMethodInvalidPath) {
  4110. auto res = cli_.Get("/dir/../test.html");
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4113. }
  4114. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4115. auto res = cli_.Get("/../www/dir/test.html");
  4116. ASSERT_TRUE(res);
  4117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4118. }
  4119. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4120. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4121. ASSERT_TRUE(res);
  4122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4123. }
  4124. TEST_F(ServerTest, GetMethodDirMountTest) {
  4125. auto res = cli_.Get("/mount/dir/test.html");
  4126. ASSERT_TRUE(res);
  4127. EXPECT_EQ(StatusCode::OK_200, res->status);
  4128. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4129. EXPECT_EQ("test.html", res->body);
  4130. }
  4131. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4132. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4133. ASSERT_TRUE(res);
  4134. EXPECT_EQ(StatusCode::OK_200, res->status);
  4135. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4136. EXPECT_EQ("test.html", res->body);
  4137. }
  4138. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4139. auto res = cli_.Get("/mount/dir/../test.html");
  4140. ASSERT_TRUE(res);
  4141. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4142. }
  4143. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4144. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4147. }
  4148. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4149. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4150. ASSERT_TRUE(res);
  4151. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4152. }
  4153. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4154. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4155. ASSERT_TRUE(res);
  4156. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4157. }
  4158. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4159. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4162. }
  4163. TEST_F(ServerTest, PostMethod303) {
  4164. auto res = cli_.Post("/1", "body", "text/plain");
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4167. EXPECT_EQ("/2", res->get_header_value("Location"));
  4168. }
  4169. TEST_F(ServerTest, PostMethod303Redirect) {
  4170. cli_.set_follow_location(true);
  4171. auto res = cli_.Post("/1", "body", "text/plain");
  4172. ASSERT_TRUE(res);
  4173. EXPECT_EQ(StatusCode::OK_200, res->status);
  4174. EXPECT_EQ("redirected.", res->body);
  4175. EXPECT_EQ("/2", res->location);
  4176. }
  4177. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4178. auto res = cli_.Get("/dir/test.abcde");
  4179. ASSERT_TRUE(res);
  4180. EXPECT_EQ(StatusCode::OK_200, res->status);
  4181. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4182. EXPECT_EQ("abcde", res->body);
  4183. }
  4184. TEST_F(ServerTest, StaticFileRange) {
  4185. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4188. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4189. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4190. EXPECT_EQ(true, res->has_header("Content-Range"));
  4191. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4192. EXPECT_EQ(std::string("cd"), res->body);
  4193. }
  4194. TEST_F(ServerTest, StaticFileRanges) {
  4195. auto res =
  4196. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  4197. ASSERT_TRUE(res);
  4198. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4199. EXPECT_TRUE(
  4200. res->get_header_value("Content-Type")
  4201. .find(
  4202. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4203. 0);
  4204. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4205. }
  4206. TEST_F(ServerTest, StaticFileRangeHead) {
  4207. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4208. ASSERT_TRUE(res);
  4209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4210. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4211. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4212. EXPECT_EQ(true, res->has_header("Content-Range"));
  4213. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4214. }
  4215. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4216. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4217. ASSERT_TRUE(res);
  4218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4220. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4221. EXPECT_EQ(true, res->has_header("Content-Range"));
  4222. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4223. res->get_header_value("Content-Range"));
  4224. EXPECT_EQ("LAST\n", res->body);
  4225. }
  4226. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4227. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4230. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4231. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4232. EXPECT_EQ(true, res->has_header("Content-Range"));
  4233. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4234. }
  4235. TEST_F(ServerTest, StaticFileBigFile) {
  4236. auto res = cli_.Get("/dir/1MB.txt");
  4237. ASSERT_TRUE(res);
  4238. EXPECT_EQ(StatusCode::OK_200, res->status);
  4239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4240. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4241. }
  4242. TEST_F(ServerTest, InvalidBaseDirMount) {
  4243. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4244. }
  4245. TEST_F(ServerTest, Binary) {
  4246. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4247. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4248. "application/octet-stream");
  4249. ASSERT_TRUE(res);
  4250. ASSERT_EQ(StatusCode::OK_200, res->status);
  4251. ASSERT_EQ(4U, res->body.size());
  4252. res = cli_.Put("/binary", binary.data(), binary.size(),
  4253. "application/octet-stream");
  4254. ASSERT_TRUE(res);
  4255. ASSERT_EQ(StatusCode::OK_200, res->status);
  4256. ASSERT_EQ(4U, res->body.size());
  4257. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4258. "application/octet-stream");
  4259. ASSERT_TRUE(res);
  4260. ASSERT_EQ(StatusCode::OK_200, res->status);
  4261. ASSERT_EQ(4U, res->body.size());
  4262. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4263. "application/octet-stream");
  4264. ASSERT_TRUE(res);
  4265. ASSERT_EQ(StatusCode::OK_200, res->status);
  4266. ASSERT_EQ(4U, res->body.size());
  4267. }
  4268. TEST_F(ServerTest, BinaryString) {
  4269. auto binary = std::string("\x00\x01\x02\x03", 4);
  4270. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4271. ASSERT_TRUE(res);
  4272. ASSERT_EQ(StatusCode::OK_200, res->status);
  4273. ASSERT_EQ(4U, res->body.size());
  4274. res = cli_.Put("/binary", binary, "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, "application/octet-stream");
  4279. ASSERT_TRUE(res);
  4280. ASSERT_EQ(StatusCode::OK_200, res->status);
  4281. ASSERT_EQ(4U, res->body.size());
  4282. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4283. ASSERT_TRUE(res);
  4284. ASSERT_EQ(StatusCode::OK_200, res->status);
  4285. ASSERT_EQ(4U, res->body.size());
  4286. }
  4287. TEST_F(ServerTest, EmptyRequest) {
  4288. auto res = cli_.Get("");
  4289. ASSERT_TRUE(!res);
  4290. EXPECT_EQ(Error::Connection, res.error());
  4291. }
  4292. TEST_F(ServerTest, LongRequest) {
  4293. std::string request;
  4294. for (size_t i = 0; i < 545; i++) {
  4295. request += "/TooLongRequest";
  4296. }
  4297. request += "OK";
  4298. auto res = cli_.Get(request.c_str());
  4299. ASSERT_TRUE(res);
  4300. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4301. }
  4302. TEST_F(ServerTest, TooLongRequest) {
  4303. std::string request;
  4304. for (size_t i = 0; i < 546; i++) {
  4305. request += "/TooLongRequest";
  4306. }
  4307. request += "_NG";
  4308. auto start = std::chrono::high_resolution_clock::now();
  4309. cli_.set_keep_alive(true);
  4310. auto res = cli_.Get(request.c_str());
  4311. auto end = std::chrono::high_resolution_clock::now();
  4312. auto elapsed =
  4313. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4314. .count();
  4315. ASSERT_TRUE(res);
  4316. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4317. EXPECT_LE(elapsed, 1000);
  4318. EXPECT_EQ("close", res->get_header_value("Connection"));
  4319. EXPECT_FALSE(cli_.is_socket_open());
  4320. }
  4321. TEST_F(ServerTest, AlmostTooLongRequest) {
  4322. // test for #2046 - URI length check shouldn't include other content on req
  4323. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4324. // leading /, space, HTTP/1.1)
  4325. std::string request =
  4326. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4327. auto res = cli_.Get(request.c_str());
  4328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4330. }
  4331. TEST_F(ServerTest, LongHeader) {
  4332. Request req;
  4333. req.method = "GET";
  4334. req.path = "/hi";
  4335. std::string host_and_port;
  4336. host_and_port += HOST;
  4337. host_and_port += ":";
  4338. host_and_port += std::to_string(PORT);
  4339. req.headers.emplace("Host", host_and_port.c_str());
  4340. req.headers.emplace("Accept", "*/*");
  4341. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4342. req.headers.emplace(
  4343. "Header-Name",
  4344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4372. "@@@@@@@@@@@@@@@@");
  4373. auto res = std::make_shared<Response>();
  4374. auto error = Error::Success;
  4375. auto ret = cli_.send(req, *res, error);
  4376. ASSERT_TRUE(ret);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. }
  4379. TEST_F(ServerTest, LongQueryValue) {
  4380. auto start = std::chrono::high_resolution_clock::now();
  4381. cli_.set_keep_alive(true);
  4382. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4383. auto end = std::chrono::high_resolution_clock::now();
  4384. auto elapsed =
  4385. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4386. .count();
  4387. ASSERT_TRUE(res);
  4388. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4389. EXPECT_LE(elapsed, 1000);
  4390. EXPECT_EQ("close", res->get_header_value("Connection"));
  4391. EXPECT_FALSE(cli_.is_socket_open());
  4392. }
  4393. TEST_F(ServerTest, TooLongQueryValue) {
  4394. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4395. ASSERT_FALSE(res);
  4396. EXPECT_EQ(Error::Read, res.error());
  4397. }
  4398. TEST_F(ServerTest, TooLongHeader) {
  4399. Request req;
  4400. req.method = "GET";
  4401. req.path = "/hi";
  4402. std::string host_and_port;
  4403. host_and_port += HOST;
  4404. host_and_port += ":";
  4405. host_and_port += std::to_string(PORT);
  4406. req.headers.emplace("Host", host_and_port.c_str());
  4407. req.headers.emplace("Accept", "*/*");
  4408. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4409. req.headers.emplace(
  4410. "Header-Name",
  4411. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4412. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4413. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4414. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4415. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4416. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4419. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4420. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4421. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4422. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4423. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4424. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4425. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4426. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4427. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4428. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4429. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4430. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4431. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4432. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4433. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4439. "@@@@@@@@@@@@@@@@@");
  4440. auto res = std::make_shared<Response>();
  4441. auto error = Error::Success;
  4442. auto ret = cli_.send(req, *res, error);
  4443. ASSERT_TRUE(ret);
  4444. EXPECT_EQ(StatusCode::OK_200, res->status);
  4445. }
  4446. TEST_F(ServerTest, HeaderCountAtLimit) {
  4447. // Test with headers just under the 100 limit
  4448. httplib::Headers headers;
  4449. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4450. // This should keep us just under the 100 header limit
  4451. for (int i = 0; i < 95; i++) {
  4452. std::string name = "X-Test-Header-" + std::to_string(i);
  4453. std::string value = "value" + std::to_string(i);
  4454. headers.emplace(name, value);
  4455. }
  4456. // This should work fine as we're under the limit
  4457. auto res = cli_.Get("/hi", headers);
  4458. EXPECT_TRUE(res);
  4459. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4460. }
  4461. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4462. // Test with many headers to exceed the 100 limit
  4463. httplib::Headers headers;
  4464. // Add 150 headers to definitely exceed the 100 limit
  4465. for (int i = 0; i < 150; i++) {
  4466. std::string name = "X-Test-Header-" + std::to_string(i);
  4467. std::string value = "value" + std::to_string(i);
  4468. headers.emplace(name, value);
  4469. }
  4470. // This should fail due to exceeding header count limit
  4471. cli_.set_keep_alive(true);
  4472. auto res = cli_.Get("/hi", headers);
  4473. // The server should respond with 400 Bad Request
  4474. ASSERT_TRUE(res);
  4475. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4476. EXPECT_EQ("close", res->get_header_value("Connection"));
  4477. EXPECT_FALSE(cli_.is_socket_open());
  4478. }
  4479. TEST_F(ServerTest, PercentEncoding) {
  4480. auto res = cli_.Get("/e%6edwith%");
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. }
  4484. TEST_F(ServerTest, PercentEncodingUnicode) {
  4485. auto res = cli_.Get("/e%u006edwith%");
  4486. ASSERT_TRUE(res);
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. }
  4489. TEST_F(ServerTest, InvalidPercentEncoding) {
  4490. auto res = cli_.Get("/%endwith%");
  4491. ASSERT_TRUE(res);
  4492. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4493. }
  4494. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4495. auto res = cli_.Get("/%uendwith%");
  4496. ASSERT_TRUE(res);
  4497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4498. }
  4499. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4500. auto res = cli_.Get("/hello?aaa=bbb%");
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4503. }
  4504. TEST_F(ServerTest, PlusSignEncoding) {
  4505. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("a +b", res->body);
  4509. }
  4510. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4511. // This test simulates a potential DoS attack using many headers
  4512. // to verify our security fix prevents memory exhaustion
  4513. httplib::Headers attack_headers;
  4514. // Attempt to add many headers like an attacker would (200 headers to far
  4515. // exceed limit)
  4516. for (int i = 0; i < 200; i++) {
  4517. std::string name = "X-Attack-Header-" + std::to_string(i);
  4518. std::string value = "attack_payload_" + std::to_string(i);
  4519. attack_headers.emplace(name, value);
  4520. }
  4521. // Try to POST with excessive headers
  4522. cli_.set_keep_alive(true);
  4523. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4524. // Should either fail or return 400 Bad Request due to security limit
  4525. if (res) {
  4526. // If we get a response, it should be 400 Bad Request
  4527. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4528. EXPECT_EQ("close", res->get_header_value("Connection"));
  4529. }
  4530. EXPECT_FALSE(cli_.is_socket_open());
  4531. }
  4532. TEST_F(ServerTest, MultipartFormData) {
  4533. UploadFormDataItems items = {
  4534. {"text1", "text default", "", ""},
  4535. {"text2", "aωb", "", ""},
  4536. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4537. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4538. {"file3", "", "", "application/octet-stream"},
  4539. {"file4", "", "", " application/json tmp-string "}};
  4540. auto res = cli_.Post("/multipart", items);
  4541. ASSERT_TRUE(res);
  4542. EXPECT_EQ(StatusCode::OK_200, res->status);
  4543. }
  4544. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4545. UploadFormDataItems items = {
  4546. {"text", "default text", "", ""},
  4547. {"multi_text1", "aaaaa", "", ""},
  4548. {"multi_text1", "bbbbb", "", ""},
  4549. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4550. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4551. "application/json"},
  4552. };
  4553. auto res = cli_.Post("/multipart/multi_file_values", items);
  4554. ASSERT_TRUE(res);
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. }
  4557. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4558. auto res = cli_.Get("/hi");
  4559. ASSERT_TRUE(res);
  4560. EXPECT_EQ(StatusCode::OK_200, res->status);
  4561. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4562. EXPECT_EQ("Hello World!", res->body);
  4563. }
  4564. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4565. Request req;
  4566. req.method = "POST";
  4567. req.path = "/chunked";
  4568. std::string host_and_port;
  4569. host_and_port += HOST;
  4570. host_and_port += ":";
  4571. host_and_port += std::to_string(PORT);
  4572. req.headers.emplace("Host", host_and_port.c_str());
  4573. req.headers.emplace("Accept", "*/*");
  4574. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4575. req.headers.emplace("Content-Type", "text/plain");
  4576. req.headers.emplace("Content-Length", "0");
  4577. req.headers.emplace(
  4578. "Transfer-Encoding",
  4579. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4580. // Client does not chunk, so make a chunked body manually.
  4581. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4582. auto res = std::make_shared<Response>();
  4583. auto error = Error::Success;
  4584. auto ret = cli_.send(req, *res, error);
  4585. ASSERT_TRUE(ret);
  4586. EXPECT_EQ(StatusCode::OK_200, res->status);
  4587. }
  4588. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4589. // rather than treat them as valid lengths.
  4590. template <typename ClientT>
  4591. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4592. Request req;
  4593. req.method = "POST";
  4594. req.path = "/chunked";
  4595. std::string host_and_port;
  4596. host_and_port += HOST;
  4597. host_and_port += ":";
  4598. host_and_port += std::to_string(PORT);
  4599. req.headers.emplace("Host", host_and_port.c_str());
  4600. req.headers.emplace("Content-Length", "0");
  4601. req.headers.emplace("Transfer-Encoding", "chunked");
  4602. req.body = body;
  4603. auto res = std::make_shared<Response>();
  4604. auto error = Error::Success;
  4605. ASSERT_TRUE(cli.send(req, *res, error));
  4606. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4607. }
  4608. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4609. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4610. }
  4611. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4612. expect_chunked_body_rejected(
  4613. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4614. }
  4615. TEST_F(ServerTest, GetStreamed2) {
  4616. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4617. ASSERT_TRUE(res);
  4618. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4619. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4620. EXPECT_EQ(true, res->has_header("Content-Range"));
  4621. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4622. EXPECT_EQ(std::string("ab"), res->body);
  4623. }
  4624. TEST_F(ServerTest, GetStreamed) {
  4625. auto res = cli_.Get("/streamed");
  4626. ASSERT_TRUE(res);
  4627. EXPECT_EQ(StatusCode::OK_200, res->status);
  4628. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4629. EXPECT_EQ(std::string("aaabbb"), res->body);
  4630. }
  4631. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4632. auto res =
  4633. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::OK_200, res->status);
  4636. EXPECT_EQ(false, res->has_header("Content-Length"));
  4637. EXPECT_EQ(false, res->has_header("Content-Range"));
  4638. EXPECT_EQ(std::string("abcdefg"), res->body);
  4639. }
  4640. TEST_F(ServerTest, GetStreamedWithRange1) {
  4641. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4642. ASSERT_TRUE(res);
  4643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4644. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4645. EXPECT_EQ(true, res->has_header("Content-Range"));
  4646. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4647. EXPECT_EQ(std::string("def"), res->body);
  4648. }
  4649. TEST_F(ServerTest, GetStreamedWithRange2) {
  4650. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4653. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4654. EXPECT_EQ(true, res->has_header("Content-Range"));
  4655. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4656. EXPECT_EQ(std::string("bcdefg"), res->body);
  4657. }
  4658. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4659. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4660. ASSERT_TRUE(res);
  4661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4662. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4663. EXPECT_EQ(true, res->has_header("Content-Range"));
  4664. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4665. EXPECT_EQ(std::string("efg"), res->body);
  4666. }
  4667. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4668. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4669. ASSERT_TRUE(res);
  4670. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4671. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4672. EXPECT_EQ(false, res->has_header("Content-Range"));
  4673. EXPECT_EQ(0U, res->body.size());
  4674. }
  4675. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4676. auto res = cli_.Get("/streamed-with-range",
  4677. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4678. "92233720368547758079223372036854775807"}});
  4679. ASSERT_TRUE(res);
  4680. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4681. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4682. EXPECT_EQ(false, res->has_header("Content-Range"));
  4683. EXPECT_EQ(0U, res->body.size());
  4684. }
  4685. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4686. auto res = cli_.Get(
  4687. "/with-range",
  4688. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4689. {"Accept-Encoding", ""}});
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4692. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4693. EXPECT_EQ(true, res->has_header("Content-Range"));
  4694. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4695. EXPECT_EQ(std::string("abcdefg"), res->body);
  4696. }
  4697. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4698. auto res = cli_.Get("/with-range", {
  4699. {"Range", "bytes=0-"},
  4700. {"Accept-Encoding", ""},
  4701. });
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4704. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4705. EXPECT_EQ(true, res->has_header("Content-Range"));
  4706. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4707. EXPECT_EQ(std::string("abcdefg"), res->body);
  4708. }
  4709. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4710. auto res =
  4711. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4712. ASSERT_TRUE(res);
  4713. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4714. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4715. EXPECT_EQ(false, res->has_header("Content-Range"));
  4716. EXPECT_EQ(267U, res->body.size());
  4717. // Check that both range contents are present
  4718. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4719. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4720. // Check that Content-Range headers are present for both ranges
  4721. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4722. std::string::npos);
  4723. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4724. std::string::npos);
  4725. }
  4726. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4727. Ranges ranges;
  4728. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4729. ranges.emplace_back(0, -1);
  4730. }
  4731. auto res =
  4732. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4733. ASSERT_TRUE(res);
  4734. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4735. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4736. EXPECT_EQ(false, res->has_header("Content-Range"));
  4737. EXPECT_EQ(0U, res->body.size());
  4738. }
  4739. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4740. auto res =
  4741. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4742. ASSERT_TRUE(res);
  4743. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4744. EXPECT_EQ(5U, res->body.size());
  4745. // Check that overlapping ranges are coalesced into a single range
  4746. EXPECT_EQ("bcdef", res->body);
  4747. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4748. // Should be single range, not multipart
  4749. EXPECT_TRUE(res->has_header("Content-Range"));
  4750. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4751. }
  4752. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4753. auto res =
  4754. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4755. ASSERT_TRUE(res);
  4756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4757. EXPECT_EQ(268U, res->body.size());
  4758. // Check that both range contents are present
  4759. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4760. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4761. // Check that Content-Range headers are present for both ranges
  4762. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4763. std::string::npos);
  4764. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4765. std::string::npos);
  4766. }
  4767. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4768. auto res =
  4769. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4770. ASSERT_TRUE(res);
  4771. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4772. EXPECT_EQ(269U, res->body.size());
  4773. // Check that both duplicate range contents are present
  4774. size_t first_abc = res->body.find("abc\r\n");
  4775. EXPECT_TRUE(first_abc != std::string::npos);
  4776. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4777. EXPECT_TRUE(second_abc != std::string::npos);
  4778. // Check that Content-Range headers are present for both ranges
  4779. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4780. EXPECT_TRUE(first_range != std::string::npos);
  4781. size_t second_range =
  4782. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4783. EXPECT_TRUE(second_range != std::string::npos);
  4784. }
  4785. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4786. auto res = cli_.Get("/streamed-with-range?error",
  4787. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4788. ASSERT_TRUE(res);
  4789. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4790. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4791. EXPECT_EQ(false, res->has_header("Content-Range"));
  4792. EXPECT_EQ(0U, res->body.size());
  4793. }
  4794. TEST_F(ServerTest, GetStreamedEndless) {
  4795. uint64_t offset = 0;
  4796. auto res = cli_.Get("/streamed-cancel",
  4797. [&](const char * /*data*/, uint64_t data_length) {
  4798. if (offset < 100) {
  4799. offset += data_length;
  4800. return true;
  4801. }
  4802. return false;
  4803. });
  4804. ASSERT_TRUE(!res);
  4805. EXPECT_EQ(Error::Canceled, res.error());
  4806. }
  4807. TEST_F(ServerTest, ClientStop) {
  4808. std::atomic_size_t count{4};
  4809. std::vector<std::thread> threads;
  4810. for (auto i = count.load(); i != 0; --i) {
  4811. threads.emplace_back([&]() {
  4812. auto res = cli_.Get("/streamed-cancel",
  4813. [&](const char *, uint64_t) { return true; });
  4814. --count;
  4815. ASSERT_TRUE(!res);
  4816. EXPECT_TRUE(res.error() == Error::Canceled ||
  4817. res.error() == Error::Read || res.error() == Error::Write);
  4818. });
  4819. }
  4820. std::this_thread::sleep_for(std::chrono::seconds(2));
  4821. while (count != 0) {
  4822. cli_.stop();
  4823. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4824. }
  4825. for (auto &t : threads) {
  4826. t.join();
  4827. }
  4828. }
  4829. TEST_F(ServerTest, GetWithRange1) {
  4830. auto res = cli_.Get("/with-range", {
  4831. make_range_header({{3, 5}}),
  4832. {"Accept-Encoding", ""},
  4833. });
  4834. ASSERT_TRUE(res);
  4835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4836. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4837. EXPECT_EQ(true, res->has_header("Content-Range"));
  4838. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4839. EXPECT_EQ(std::string("def"), res->body);
  4840. }
  4841. TEST_F(ServerTest, GetWithRange2) {
  4842. auto res = cli_.Get("/with-range", {
  4843. make_range_header({{1, -1}}),
  4844. {"Accept-Encoding", ""},
  4845. });
  4846. ASSERT_TRUE(res);
  4847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4848. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4849. EXPECT_EQ(true, res->has_header("Content-Range"));
  4850. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4851. EXPECT_EQ(std::string("bcdefg"), res->body);
  4852. }
  4853. TEST_F(ServerTest, GetWithRange3) {
  4854. auto res = cli_.Get("/with-range", {
  4855. make_range_header({{0, 0}}),
  4856. {"Accept-Encoding", ""},
  4857. });
  4858. ASSERT_TRUE(res);
  4859. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4860. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4861. EXPECT_EQ(true, res->has_header("Content-Range"));
  4862. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4863. EXPECT_EQ(std::string("a"), res->body);
  4864. }
  4865. TEST_F(ServerTest, GetWithRange4) {
  4866. auto res = cli_.Get("/with-range", {
  4867. make_range_header({{-1, 2}}),
  4868. {"Accept-Encoding", ""},
  4869. });
  4870. ASSERT_TRUE(res);
  4871. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4872. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4873. EXPECT_EQ(true, res->has_header("Content-Range"));
  4874. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4875. EXPECT_EQ(std::string("fg"), res->body);
  4876. }
  4877. TEST_F(ServerTest, GetWithRange5) {
  4878. auto res = cli_.Get("/with-range", {
  4879. make_range_header({{0, 5}}),
  4880. {"Accept-Encoding", ""},
  4881. });
  4882. ASSERT_TRUE(res);
  4883. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4884. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4885. EXPECT_EQ(true, res->has_header("Content-Range"));
  4886. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4887. EXPECT_EQ(std::string("abcdef"), res->body);
  4888. }
  4889. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4890. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4891. ASSERT_TRUE(res);
  4892. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4893. }
  4894. TEST_F(ServerTest, GetWithRangeMultipart) {
  4895. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4896. ASSERT_TRUE(res);
  4897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4898. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4899. EXPECT_EQ(false, res->has_header("Content-Range"));
  4900. EXPECT_EQ(267U, res->body.size());
  4901. }
  4902. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4903. auto res =
  4904. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4905. ASSERT_TRUE(res);
  4906. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4907. }
  4908. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4909. auto res = cli_.Get("/with-range-customized-response",
  4910. {{make_range_header({{1, 2}})}});
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4913. EXPECT_EQ(true, res->has_header("Content-Length"));
  4914. EXPECT_EQ(false, res->has_header("Content-Range"));
  4915. EXPECT_EQ(JSON_DATA, res->body);
  4916. }
  4917. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4918. auto res = cli_.Get("/with-range-customized-response",
  4919. {{make_range_header({{1, 2}, {4, 5}})}});
  4920. ASSERT_TRUE(res);
  4921. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4922. EXPECT_EQ(true, res->has_header("Content-Length"));
  4923. EXPECT_EQ(false, res->has_header("Content-Range"));
  4924. EXPECT_EQ(JSON_DATA, res->body);
  4925. }
  4926. TEST_F(ServerTest, Issue1772) {
  4927. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4928. ASSERT_TRUE(res);
  4929. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4930. }
  4931. TEST_F(ServerTest, Issue609) {
  4932. auto res = cli_.Delete("/issue609");
  4933. ASSERT_TRUE(res);
  4934. EXPECT_EQ(StatusCode::OK_200, res->status);
  4935. EXPECT_EQ(std::string("ok"), res->body);
  4936. }
  4937. TEST_F(ServerTest, GetStreamedChunked) {
  4938. auto res = cli_.Get("/streamed-chunked");
  4939. ASSERT_TRUE(res);
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ(std::string("123456789"), res->body);
  4942. }
  4943. TEST_F(ServerTest, GetStreamedChunked2) {
  4944. auto res = cli_.Get("/streamed-chunked2");
  4945. ASSERT_TRUE(res);
  4946. EXPECT_EQ(StatusCode::OK_200, res->status);
  4947. EXPECT_EQ(std::string("123456789"), res->body);
  4948. }
  4949. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4950. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4951. ASSERT_TRUE(res);
  4952. EXPECT_EQ(StatusCode::OK_200, res->status);
  4953. EXPECT_EQ(std::string("123456789"), res->body);
  4954. EXPECT_TRUE(res->has_header("Trailer"));
  4955. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4956. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4957. // Trailers are now stored separately from headers (security fix)
  4958. EXPECT_EQ(2U, res->trailers.size());
  4959. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4960. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4961. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4962. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4963. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4964. // Verify trailers are NOT in headers (security verification)
  4965. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4966. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4967. }
  4968. TEST_F(ServerTest, LargeChunkedPost) {
  4969. Request req;
  4970. req.method = "POST";
  4971. req.path = "/large-chunked";
  4972. std::string host_and_port;
  4973. host_and_port += HOST;
  4974. host_and_port += ":";
  4975. host_and_port += std::to_string(PORT);
  4976. req.headers.emplace("Host", host_and_port.c_str());
  4977. req.headers.emplace("Accept", "*/*");
  4978. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4979. req.headers.emplace("Content-Type", "text/plain");
  4980. req.headers.emplace("Content-Length", "0");
  4981. req.headers.emplace("Transfer-Encoding", "chunked");
  4982. std::string long_string(30 * 1024u, 'a');
  4983. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4984. // Attempt to make a large enough post to exceed OS buffers, to test that
  4985. // the server handles short reads if the full chunk data isn't available.
  4986. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4987. auto res = std::make_shared<Response>();
  4988. auto error = Error::Success;
  4989. auto ret = cli_.send(req, *res, error);
  4990. ASSERT_TRUE(ret);
  4991. EXPECT_EQ(StatusCode::OK_200, res->status);
  4992. }
  4993. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4994. auto res = cli_.Get("/remote_addr");
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4998. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4999. }
  5000. TEST_F(ServerTest, GetMethodLocalAddr) {
  5001. auto res = cli_.Get("/local_addr");
  5002. ASSERT_TRUE(res);
  5003. EXPECT_EQ(StatusCode::OK_200, res->status);
  5004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5005. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5006. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5007. }
  5008. TEST_F(ServerTest, HTTPResponseSplitting) {
  5009. auto res = cli_.Get("/http_response_splitting");
  5010. ASSERT_TRUE(res);
  5011. EXPECT_EQ(StatusCode::OK_200, res->status);
  5012. }
  5013. TEST_F(ServerTest, SlowRequest) {
  5014. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5015. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5016. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5017. }
  5018. #if 0
  5019. TEST_F(ServerTest, SlowPost) {
  5020. char buffer[64 * 1024];
  5021. memset(buffer, 0x42, sizeof(buffer));
  5022. auto res = cli_.Post(
  5023. "/slowpost", 64 * 1024 * 1024,
  5024. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5025. auto ret = sink.write(buffer, sizeof(buffer));
  5026. EXPECT_TRUE(ret);
  5027. return true;
  5028. },
  5029. "text/plain");
  5030. ASSERT_TRUE(res);
  5031. EXPECT_EQ(StatusCode::OK_200, res->status);
  5032. }
  5033. TEST_F(ServerTest, SlowPostFail) {
  5034. char buffer[64 * 1024];
  5035. memset(buffer, 0x42, sizeof(buffer));
  5036. cli_.set_write_timeout(std::chrono::seconds(0));
  5037. auto res = cli_.Post(
  5038. "/slowpost", 64 * 1024 * 1024,
  5039. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5040. sink.write(buffer, sizeof(buffer));
  5041. return true;
  5042. },
  5043. "text/plain");
  5044. ASSERT_TRUE(!res);
  5045. EXPECT_EQ(Error::Write, res.error());
  5046. }
  5047. #endif
  5048. TEST_F(ServerTest, Put) {
  5049. auto res = cli_.Put("/put", "PUT", "text/plain");
  5050. ASSERT_TRUE(res);
  5051. EXPECT_EQ(StatusCode::OK_200, res->status);
  5052. EXPECT_EQ("PUT", res->body);
  5053. }
  5054. TEST_F(ServerTest, PutWithContentProvider) {
  5055. auto res = cli_.Put(
  5056. "/put", 3,
  5057. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5058. sink.os << "PUT";
  5059. return true;
  5060. },
  5061. "text/plain");
  5062. ASSERT_TRUE(res);
  5063. EXPECT_EQ(StatusCode::OK_200, res->status);
  5064. EXPECT_EQ("PUT", res->body);
  5065. }
  5066. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5067. auto res = cli_.Post(
  5068. "/post", 42,
  5069. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5070. return false;
  5071. },
  5072. "text/plain");
  5073. ASSERT_TRUE(!res);
  5074. EXPECT_EQ(Error::Canceled, res.error());
  5075. }
  5076. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5077. auto res = cli_.Put(
  5078. "/put",
  5079. [](size_t /*offset*/, DataSink &sink) {
  5080. sink.os << "PUT";
  5081. sink.done();
  5082. return true;
  5083. },
  5084. "text/plain");
  5085. ASSERT_TRUE(res);
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. EXPECT_EQ("PUT", res->body);
  5088. }
  5089. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5090. auto res = cli_.Post(
  5091. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5092. "text/plain");
  5093. ASSERT_TRUE(!res);
  5094. EXPECT_EQ(Error::Canceled, res.error());
  5095. }
  5096. TEST_F(ServerTest, PostLoopBack) {
  5097. std::string body;
  5098. auto res = cli_.Post(
  5099. "/post-loopback", 9,
  5100. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5101. EXPECT_EQ(9u, length);
  5102. sink.write("123", 3);
  5103. sink.write("456", 3);
  5104. sink.write("789", 3);
  5105. return true;
  5106. },
  5107. "text/plain",
  5108. [&body](const char *data, size_t data_length) {
  5109. body.append(data, data_length);
  5110. return true;
  5111. });
  5112. ASSERT_TRUE(res);
  5113. EXPECT_EQ(StatusCode::OK_200, res->status);
  5114. EXPECT_EQ("123456789", body);
  5115. }
  5116. TEST_F(ServerTest, PutLoopBack) {
  5117. std::string body;
  5118. auto res = cli_.Put(
  5119. "/put-loopback", 9,
  5120. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5121. EXPECT_EQ(9u, length);
  5122. sink.write("123", 3);
  5123. sink.write("456", 3);
  5124. sink.write("789", 3);
  5125. return true;
  5126. },
  5127. "text/plain",
  5128. [&body](const char *data, size_t data_length) {
  5129. body.append(data, data_length);
  5130. return true;
  5131. });
  5132. ASSERT_TRUE(res);
  5133. EXPECT_EQ(StatusCode::OK_200, res->status);
  5134. EXPECT_EQ("123456789", body);
  5135. }
  5136. TEST_F(ServerTest, PatchLoopBack) {
  5137. std::string body;
  5138. auto res = cli_.Patch(
  5139. "/patch-loopback", 9,
  5140. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5141. EXPECT_EQ(9u, length);
  5142. sink.write("123", 3);
  5143. sink.write("456", 3);
  5144. sink.write("789", 3);
  5145. return true;
  5146. },
  5147. "text/plain",
  5148. [&body](const char *data, size_t data_length) {
  5149. body.append(data, data_length);
  5150. return true;
  5151. });
  5152. ASSERT_TRUE(res);
  5153. EXPECT_EQ(StatusCode::OK_200, res->status);
  5154. EXPECT_EQ("123456789", body);
  5155. }
  5156. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5157. std::string body;
  5158. auto res = cli_.Post(
  5159. "/post-loopback",
  5160. [](size_t /*offset*/, DataSink &sink) {
  5161. sink.write("123", 3);
  5162. sink.write("456", 3);
  5163. sink.write("789", 3);
  5164. sink.done();
  5165. return true;
  5166. },
  5167. "text/plain",
  5168. [&body](const char *data, size_t data_length) {
  5169. body.append(data, data_length);
  5170. return true;
  5171. });
  5172. ASSERT_TRUE(res);
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. EXPECT_EQ("123456789", body);
  5175. }
  5176. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5177. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5178. cli_.set_compress(true);
  5179. auto res = cli_.Put(
  5180. "/put", 3,
  5181. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5182. sink.os << "PUT";
  5183. return true;
  5184. },
  5185. "text/plain");
  5186. ASSERT_TRUE(res);
  5187. EXPECT_EQ(StatusCode::OK_200, res->status);
  5188. EXPECT_EQ("PUT", res->body);
  5189. }
  5190. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5191. cli_.set_compress(true);
  5192. auto res = cli_.Post(
  5193. "/post", 42,
  5194. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5195. return false;
  5196. },
  5197. "text/plain");
  5198. ASSERT_TRUE(!res);
  5199. EXPECT_EQ(Error::Canceled, res.error());
  5200. }
  5201. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5202. cli_.set_compress(true);
  5203. auto res = cli_.Put(
  5204. "/put",
  5205. [](size_t /*offset*/, DataSink &sink) {
  5206. sink.os << "PUT";
  5207. sink.done();
  5208. return true;
  5209. },
  5210. "text/plain");
  5211. ASSERT_TRUE(res);
  5212. EXPECT_EQ(StatusCode::OK_200, res->status);
  5213. EXPECT_EQ("PUT", res->body);
  5214. }
  5215. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5216. cli_.set_compress(true);
  5217. auto res = cli_.Post(
  5218. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5219. "text/plain");
  5220. ASSERT_TRUE(!res);
  5221. EXPECT_EQ(Error::Canceled, res.error());
  5222. }
  5223. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5224. cli_.set_compress(true);
  5225. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5226. ASSERT_TRUE(res);
  5227. EXPECT_EQ(StatusCode::OK_200, res->status);
  5228. EXPECT_EQ(LARGE_DATA, res->body);
  5229. }
  5230. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5231. #ifdef CPPHTTPLIB_SSL_ENABLED
  5232. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5233. Client cli(s.c_str());
  5234. cli.enable_server_certificate_verification(false);
  5235. #else
  5236. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5237. Client cli(s.c_str());
  5238. #endif
  5239. cli.set_compress(true);
  5240. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5241. ASSERT_TRUE(res);
  5242. EXPECT_EQ(StatusCode::OK_200, res->status);
  5243. EXPECT_EQ(LARGE_DATA, res->body);
  5244. // The compressed size should be less than a 10th of the original. May vary
  5245. // depending on the zlib library.
  5246. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5247. static_cast<uint64_t>(10 * 1024 * 1024));
  5248. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5249. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5250. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5251. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5252. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5253. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5254. #endif
  5255. }
  5256. TEST_F(ServerTest, PutContentWithDeflate) {
  5257. cli_.set_compress(false);
  5258. Headers headers;
  5259. headers.emplace("Content-Encoding", "deflate");
  5260. // PUT in deflate format:
  5261. auto res = cli_.Put("/put", headers,
  5262. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5263. ASSERT_TRUE(res);
  5264. EXPECT_EQ(StatusCode::OK_200, res->status);
  5265. EXPECT_EQ("PUT", res->body);
  5266. }
  5267. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "gzip, deflate");
  5270. auto res = cli_.Get("/streamed-chunked", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ(StatusCode::OK_200, res->status);
  5273. EXPECT_EQ(std::string("123456789"), res->body);
  5274. }
  5275. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5276. Headers headers;
  5277. headers.emplace("Accept-Encoding", "gzip, deflate");
  5278. auto res = cli_.Get("/streamed-chunked2", headers);
  5279. ASSERT_TRUE(res);
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. EXPECT_EQ(std::string("123456789"), res->body);
  5282. }
  5283. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5284. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5285. ASSERT_TRUE(res);
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. }
  5288. TEST(GzipDecompressor, ChunkedDecompression) {
  5289. std::string data;
  5290. for (size_t i = 0; i < 32 * 1024; ++i) {
  5291. data.push_back(static_cast<char>('a' + i % 26));
  5292. }
  5293. std::string compressed_data;
  5294. {
  5295. httplib::detail::gzip_compressor compressor;
  5296. bool result = compressor.compress(
  5297. data.data(), data.size(),
  5298. /*last=*/true,
  5299. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5300. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5301. compressed_data_size);
  5302. return true;
  5303. });
  5304. ASSERT_TRUE(result);
  5305. }
  5306. std::string decompressed_data;
  5307. {
  5308. httplib::detail::gzip_decompressor decompressor;
  5309. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5310. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5311. size_t chunk_size = 130;
  5312. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5313. chunk_begin += chunk_size) {
  5314. size_t current_chunk_size =
  5315. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5316. bool result = decompressor.decompress(
  5317. compressed_data.data() + chunk_begin, current_chunk_size,
  5318. [&](const char *decompressed_data_chunk,
  5319. size_t decompressed_data_chunk_size) {
  5320. decompressed_data.insert(decompressed_data.size(),
  5321. decompressed_data_chunk,
  5322. decompressed_data_chunk_size);
  5323. return true;
  5324. });
  5325. ASSERT_TRUE(result);
  5326. }
  5327. }
  5328. ASSERT_EQ(data, decompressed_data);
  5329. }
  5330. TEST(GzipDecompressor, DeflateDecompression) {
  5331. std::string original_text = "Raw deflate without gzip";
  5332. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5333. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5334. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5335. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5336. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5337. std::string decompressed_data;
  5338. {
  5339. httplib::detail::gzip_decompressor decompressor;
  5340. bool result = decompressor.decompress(
  5341. compressed_data.data(), compressed_data.size(),
  5342. [&](const char *decompressed_data_chunk,
  5343. size_t decompressed_data_chunk_size) {
  5344. decompressed_data.insert(decompressed_data.size(),
  5345. decompressed_data_chunk,
  5346. decompressed_data_chunk_size);
  5347. return true;
  5348. });
  5349. ASSERT_TRUE(result);
  5350. }
  5351. ASSERT_EQ(original_text, decompressed_data);
  5352. }
  5353. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5354. std::string original_text = "Raw deflate without gzip";
  5355. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5356. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5357. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5358. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5359. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5360. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5361. std::string decompressed_data;
  5362. {
  5363. httplib::detail::gzip_decompressor decompressor;
  5364. bool result = decompressor.decompress(
  5365. compressed_data.data(), compressed_data.size(),
  5366. [&](const char *decompressed_data_chunk,
  5367. size_t decompressed_data_chunk_size) {
  5368. decompressed_data.insert(decompressed_data.size(),
  5369. decompressed_data_chunk,
  5370. decompressed_data_chunk_size);
  5371. return true;
  5372. });
  5373. ASSERT_TRUE(result);
  5374. }
  5375. ASSERT_EQ(original_text, decompressed_data);
  5376. }
  5377. #endif
  5378. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5379. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5380. Headers headers;
  5381. headers.emplace("Accept-Encoding", "br");
  5382. auto res = cli_.Get("/streamed-chunked", headers);
  5383. ASSERT_TRUE(res);
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. EXPECT_EQ(std::string("123456789"), res->body);
  5386. }
  5387. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5388. Headers headers;
  5389. headers.emplace("Accept-Encoding", "br");
  5390. auto res = cli_.Get("/streamed-chunked2", headers);
  5391. ASSERT_TRUE(res);
  5392. EXPECT_EQ(StatusCode::OK_200, res->status);
  5393. EXPECT_EQ(std::string("123456789"), res->body);
  5394. }
  5395. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5396. cli_.set_compress(true);
  5397. auto res = cli_.Put(
  5398. "/put", 3,
  5399. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5400. sink.os << "PUT";
  5401. return true;
  5402. },
  5403. "text/plain");
  5404. ASSERT_TRUE(res);
  5405. EXPECT_EQ(StatusCode::OK_200, res->status);
  5406. EXPECT_EQ("PUT", res->body);
  5407. }
  5408. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5409. cli_.set_compress(true);
  5410. auto res = cli_.Put(
  5411. "/put",
  5412. [](size_t /*offset*/, DataSink &sink) {
  5413. sink.os << "PUT";
  5414. sink.done();
  5415. return true;
  5416. },
  5417. "text/plain");
  5418. ASSERT_TRUE(res);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. EXPECT_EQ("PUT", res->body);
  5421. }
  5422. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5423. cli_.set_compress(true);
  5424. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5425. ASSERT_TRUE(res);
  5426. EXPECT_EQ(StatusCode::OK_200, res->status);
  5427. EXPECT_EQ(LARGE_DATA, res->body);
  5428. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5429. }
  5430. #endif
  5431. TEST_F(ServerTest, Patch) {
  5432. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5433. ASSERT_TRUE(res);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. EXPECT_EQ("PATCH", res->body);
  5436. }
  5437. TEST_F(ServerTest, Delete) {
  5438. auto res = cli_.Delete("/delete");
  5439. ASSERT_TRUE(res);
  5440. EXPECT_EQ(StatusCode::OK_200, res->status);
  5441. EXPECT_EQ("DELETE", res->body);
  5442. }
  5443. TEST_F(ServerTest, DeleteContentReceiver) {
  5444. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5445. ASSERT_TRUE(res);
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. EXPECT_EQ("content", res->body);
  5448. }
  5449. TEST_F(ServerTest, Options) {
  5450. auto res = cli_.Options("*");
  5451. ASSERT_TRUE(res);
  5452. EXPECT_EQ(StatusCode::OK_200, res->status);
  5453. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5454. EXPECT_TRUE(res->body.empty());
  5455. }
  5456. TEST_F(ServerTest, URL) {
  5457. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5458. ASSERT_TRUE(res);
  5459. EXPECT_EQ(StatusCode::OK_200, res->status);
  5460. }
  5461. TEST_F(ServerTest, ArrayParam) {
  5462. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5463. ASSERT_TRUE(res);
  5464. EXPECT_EQ(StatusCode::OK_200, res->status);
  5465. }
  5466. TEST_F(ServerTest, ArrayParamValues) {
  5467. auto res =
  5468. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5469. ASSERT_TRUE(res);
  5470. EXPECT_EQ(StatusCode::OK_200, res->status);
  5471. }
  5472. TEST_F(ServerTest, NoMultipleHeaders) {
  5473. Headers headers = {{"Content-Length", "5"}};
  5474. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5475. "text/plain");
  5476. ASSERT_TRUE(res);
  5477. EXPECT_EQ(StatusCode::OK_200, res->status);
  5478. }
  5479. TEST_F(ServerTest, PostContentReceiver) {
  5480. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5481. ASSERT_TRUE(res);
  5482. ASSERT_EQ(StatusCode::OK_200, res->status);
  5483. ASSERT_EQ("content", res->body);
  5484. }
  5485. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5486. UploadFormDataItems items = {
  5487. {"text1", "text default", "", ""},
  5488. {"text2", "aωb", "", ""},
  5489. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5490. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5491. {"file3", "", "", "application/octet-stream"},
  5492. };
  5493. auto res = cli_.Post("/content_receiver", items);
  5494. ASSERT_TRUE(res);
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. }
  5497. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5498. UploadFormDataItems items = {
  5499. {"text1", "text default", "", ""},
  5500. {"text2", "aωb", "", ""},
  5501. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5502. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5503. {"file3", "", "", "application/octet-stream"},
  5504. };
  5505. auto boundary = std::string("+++++");
  5506. std::string body;
  5507. for (const auto &item : items) {
  5508. body += "--" + boundary + "\r\n";
  5509. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5510. if (!item.filename.empty()) {
  5511. body += "; filename=\"" + item.filename + "\"";
  5512. }
  5513. body += "\r\n";
  5514. if (!item.content_type.empty()) {
  5515. body += "Content-Type: " + item.content_type + "\r\n";
  5516. }
  5517. body += "\r\n";
  5518. body += item.content + "\r\n";
  5519. }
  5520. body += "--" + boundary + "--\r\n";
  5521. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5522. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5523. ASSERT_TRUE(res);
  5524. EXPECT_EQ(StatusCode::OK_200, res->status);
  5525. }
  5526. TEST(MultipartFormDataTest, FieldEscaping) {
  5527. Server svr;
  5528. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5529. const ContentReader &content_reader) {
  5530. ASSERT_TRUE(req.is_multipart_form_data());
  5531. std::vector<FormData> received;
  5532. content_reader(
  5533. [&](const FormData &file) {
  5534. received.push_back(file);
  5535. return true;
  5536. },
  5537. [&](const char *data, size_t data_length) {
  5538. received.back().content.append(data, data_length);
  5539. return true;
  5540. });
  5541. // '"', CR and LF in names and filenames are escaped following the
  5542. // WHATWG HTML standard, so each part still parses as a single part
  5543. // with no injected headers. Content types get CR/LF escaped too,
  5544. // while '"' (legal there, e.g. quoted charset) is preserved.
  5545. ASSERT_EQ(4U, received.size());
  5546. EXPECT_EQ("na%22me", received[0].name);
  5547. EXPECT_EQ("quoted name", received[0].content);
  5548. EXPECT_EQ("file", received[1].name);
  5549. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5550. received[1].filename);
  5551. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5552. EXPECT_EQ("injected", received[1].content);
  5553. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5554. EXPECT_EQ("my%22file.txt", received[2].filename);
  5555. EXPECT_EQ("cr lf name", received[2].content);
  5556. EXPECT_EQ("typed", received[3].name);
  5557. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5558. received[3].content_type);
  5559. EXPECT_EQ("typed content", received[3].content);
  5560. });
  5561. auto port = svr.bind_to_any_port("localhost");
  5562. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5563. auto se = detail::scope_exit([&] {
  5564. svr.stop();
  5565. t.join();
  5566. ASSERT_FALSE(svr.is_running());
  5567. });
  5568. svr.wait_until_ready();
  5569. Client cli("localhost", port);
  5570. UploadFormDataItems items = {
  5571. {"na\"me", "quoted name", "", ""},
  5572. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5573. "application/octet-stream"},
  5574. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5575. {"typed", "typed content", "",
  5576. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5577. };
  5578. auto res = cli.Post("/post", items);
  5579. ASSERT_TRUE(res);
  5580. EXPECT_EQ(StatusCode::OK_200, res->status);
  5581. }
  5582. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5583. const UploadFormDataItems items = {
  5584. {"name1", "Content 1", "", ""},
  5585. {"name2", "Content 2", "file2.txt", "text/plain"},
  5586. };
  5587. Server svr;
  5588. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5589. const ContentReader &content_reader) {
  5590. ASSERT_TRUE(req.is_multipart_form_data());
  5591. std::vector<FormData> received;
  5592. content_reader(
  5593. [&](const FormData &file) {
  5594. received.push_back(file);
  5595. return true;
  5596. },
  5597. [&](const char *data, size_t data_length) {
  5598. received.back().content.append(data, data_length);
  5599. return true;
  5600. });
  5601. ASSERT_EQ(2U, received.size());
  5602. EXPECT_EQ("name1", received[0].name);
  5603. EXPECT_EQ("Content 1", received[0].content);
  5604. EXPECT_EQ("name2", received[1].name);
  5605. EXPECT_EQ("Content 2", received[1].content);
  5606. EXPECT_EQ("file2.txt", received[1].filename);
  5607. EXPECT_EQ("text/plain", received[1].content_type);
  5608. });
  5609. auto port = svr.bind_to_any_port("localhost");
  5610. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5611. auto se = detail::scope_exit([&] {
  5612. svr.stop();
  5613. t.join();
  5614. ASSERT_FALSE(svr.is_running());
  5615. });
  5616. svr.wait_until_ready();
  5617. Client cli("localhost", port);
  5618. // Whole-body serialization with a generated boundary
  5619. {
  5620. MultipartFormDataWriter writer;
  5621. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5622. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5623. writer.content_type());
  5624. auto body = writer.serialize(items);
  5625. EXPECT_EQ(body.size(), writer.content_length(items));
  5626. auto res = cli.Post("/post", body, writer.content_type());
  5627. ASSERT_TRUE(res);
  5628. EXPECT_EQ(StatusCode::OK_200, res->status);
  5629. }
  5630. // Per-part framing with a custom boundary via a content provider
  5631. {
  5632. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5633. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5634. MultipartFormDataWriter writer("custom-boundary_123");
  5635. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5636. std::string body;
  5637. for (const auto &item : items) {
  5638. body += writer.item_begin(item);
  5639. body += item.content;
  5640. body += MultipartFormDataWriter::item_end();
  5641. }
  5642. body += writer.finish();
  5643. EXPECT_EQ(body.size(), writer.content_length(items));
  5644. auto res = cli.Post(
  5645. "/post", body.size(),
  5646. [&](size_t offset, size_t length, DataSink &sink) {
  5647. sink.write(body.data() + offset, length);
  5648. return true;
  5649. },
  5650. writer.content_type());
  5651. ASSERT_TRUE(res);
  5652. EXPECT_EQ(StatusCode::OK_200, res->status);
  5653. }
  5654. }
  5655. TEST_F(ServerTest, PostContentReceiverGzip) {
  5656. cli_.set_compress(true);
  5657. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5658. ASSERT_TRUE(res);
  5659. ASSERT_EQ(StatusCode::OK_200, res->status);
  5660. ASSERT_EQ("content", res->body);
  5661. }
  5662. TEST_F(ServerTest, PutContentReceiver) {
  5663. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5664. ASSERT_TRUE(res);
  5665. ASSERT_EQ(StatusCode::OK_200, res->status);
  5666. ASSERT_EQ("content", res->body);
  5667. }
  5668. TEST_F(ServerTest, PatchContentReceiver) {
  5669. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5670. ASSERT_TRUE(res);
  5671. ASSERT_EQ(StatusCode::OK_200, res->status);
  5672. ASSERT_EQ("content", res->body);
  5673. }
  5674. template <typename ClientType>
  5675. void TestWithHeadersAndContentReceiver(
  5676. ClientType &cli,
  5677. std::function<Result(ClientType &, const std::string &, const Headers &,
  5678. const std::string &, const std::string &,
  5679. ContentReceiver, DownloadProgress)>
  5680. request_func) {
  5681. Headers headers;
  5682. headers.emplace("X-Custom-Header", "test-value");
  5683. std::string received_body;
  5684. auto res = request_func(
  5685. cli, "/content_receiver", headers, "content", "application/json",
  5686. [&](const char *data, size_t data_length) {
  5687. received_body.append(data, data_length);
  5688. return true;
  5689. },
  5690. nullptr);
  5691. ASSERT_TRUE(res);
  5692. EXPECT_EQ(StatusCode::OK_200, res->status);
  5693. EXPECT_EQ("content", received_body);
  5694. }
  5695. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5696. #ifdef CPPHTTPLIB_SSL_ENABLED
  5697. using ClientT = SSLClient;
  5698. #else
  5699. using ClientT = Client;
  5700. #endif
  5701. TestWithHeadersAndContentReceiver<ClientT>(
  5702. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5703. const std::string &body, const std::string &content_type,
  5704. ContentReceiver receiver, DownloadProgress progress) {
  5705. return cli.Post(path, headers, body, content_type, receiver, progress);
  5706. });
  5707. }
  5708. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5709. #ifdef CPPHTTPLIB_SSL_ENABLED
  5710. using ClientT = SSLClient;
  5711. #else
  5712. using ClientT = Client;
  5713. #endif
  5714. TestWithHeadersAndContentReceiver<ClientT>(
  5715. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5716. const std::string &body, const std::string &content_type,
  5717. ContentReceiver receiver, DownloadProgress progress) {
  5718. return cli.Put(path, headers, body, content_type, receiver, progress);
  5719. });
  5720. }
  5721. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5722. #ifdef CPPHTTPLIB_SSL_ENABLED
  5723. using ClientT = SSLClient;
  5724. #else
  5725. using ClientT = Client;
  5726. #endif
  5727. TestWithHeadersAndContentReceiver<ClientT>(
  5728. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5729. const std::string &body, const std::string &content_type,
  5730. ContentReceiver receiver, DownloadProgress progress) {
  5731. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5732. });
  5733. }
  5734. template <typename ClientType>
  5735. void TestWithHeadersAndContentReceiverWithProgress(
  5736. ClientType &cli,
  5737. std::function<Result(ClientType &, const std::string &, const Headers &,
  5738. const std::string &, const std::string &,
  5739. ContentReceiver, DownloadProgress)>
  5740. request_func) {
  5741. Headers headers;
  5742. headers.emplace("X-Test-Header", "progress-test");
  5743. std::string received_body;
  5744. auto progress_called = false;
  5745. auto res = request_func(
  5746. cli, "/content_receiver", headers, "content", "text/plain",
  5747. [&](const char *data, size_t data_length) {
  5748. received_body.append(data, data_length);
  5749. return true;
  5750. },
  5751. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5752. progress_called = true;
  5753. return true;
  5754. });
  5755. ASSERT_TRUE(res);
  5756. EXPECT_EQ(StatusCode::OK_200, res->status);
  5757. EXPECT_EQ("content", received_body);
  5758. EXPECT_TRUE(progress_called);
  5759. }
  5760. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5761. #ifdef CPPHTTPLIB_SSL_ENABLED
  5762. using ClientT = SSLClient;
  5763. #else
  5764. using ClientT = Client;
  5765. #endif
  5766. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5767. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5768. const std::string &body, const std::string &content_type,
  5769. ContentReceiver receiver, DownloadProgress progress) {
  5770. return cli.Post(path, headers, body, content_type, receiver, progress);
  5771. });
  5772. }
  5773. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5774. #ifdef CPPHTTPLIB_SSL_ENABLED
  5775. using ClientT = SSLClient;
  5776. #else
  5777. using ClientT = Client;
  5778. #endif
  5779. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5780. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5781. const std::string &body, const std::string &content_type,
  5782. ContentReceiver receiver, DownloadProgress progress) {
  5783. return cli.Put(path, headers, body, content_type, receiver, progress);
  5784. });
  5785. }
  5786. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5787. #ifdef CPPHTTPLIB_SSL_ENABLED
  5788. using ClientT = SSLClient;
  5789. #else
  5790. using ClientT = Client;
  5791. #endif
  5792. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5793. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5794. const std::string &body, const std::string &content_type,
  5795. ContentReceiver receiver, DownloadProgress progress) {
  5796. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5797. });
  5798. }
  5799. template <typename ClientType>
  5800. void TestWithHeadersAndContentReceiverError(
  5801. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5802. const Headers &, const std::string &,
  5803. const std::string &, ContentReceiver)>
  5804. request_func) {
  5805. Headers headers;
  5806. headers.emplace("X-Error-Test", "true");
  5807. std::string received_body;
  5808. auto receiver_failed = false;
  5809. auto res =
  5810. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5811. [&](const char *data, size_t data_length) {
  5812. received_body.append(data, data_length);
  5813. receiver_failed = true;
  5814. return false;
  5815. });
  5816. ASSERT_FALSE(res);
  5817. EXPECT_TRUE(receiver_failed);
  5818. }
  5819. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5820. #ifdef CPPHTTPLIB_SSL_ENABLED
  5821. using ClientT = SSLClient;
  5822. #else
  5823. using ClientT = Client;
  5824. #endif
  5825. TestWithHeadersAndContentReceiverError<ClientT>(
  5826. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5827. const std::string &body, const std::string &content_type,
  5828. ContentReceiver receiver) {
  5829. return cli.Post(path, headers, body, content_type, receiver);
  5830. });
  5831. }
  5832. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5833. #ifdef CPPHTTPLIB_SSL_ENABLED
  5834. using ClientT = SSLClient;
  5835. #else
  5836. using ClientT = Client;
  5837. #endif
  5838. TestWithHeadersAndContentReceiverError<ClientT>(
  5839. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5840. const std::string &body, const std::string &content_type,
  5841. ContentReceiver receiver) {
  5842. return cli.Put(path, headers, body, content_type, receiver);
  5843. });
  5844. }
  5845. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5846. #ifdef CPPHTTPLIB_SSL_ENABLED
  5847. using ClientT = SSLClient;
  5848. #else
  5849. using ClientT = Client;
  5850. #endif
  5851. TestWithHeadersAndContentReceiverError<ClientT>(
  5852. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5853. const std::string &body, const std::string &content_type,
  5854. ContentReceiver receiver) {
  5855. return cli.Patch(path, headers, body, content_type, receiver);
  5856. });
  5857. }
  5858. TEST_F(ServerTest, PostQueryStringAndBody) {
  5859. auto res =
  5860. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5861. ASSERT_TRUE(res);
  5862. ASSERT_EQ(StatusCode::OK_200, res->status);
  5863. }
  5864. TEST_F(ServerTest, HTTP2Magic) {
  5865. Request req;
  5866. req.method = "PRI";
  5867. req.path = "*";
  5868. req.body = "SM";
  5869. auto res = std::make_shared<Response>();
  5870. auto error = Error::Success;
  5871. auto ret = cli_.send(req, *res, error);
  5872. ASSERT_TRUE(ret);
  5873. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5874. }
  5875. TEST_F(ServerTest, KeepAlive) {
  5876. auto res = cli_.Get("/hi");
  5877. ASSERT_TRUE(res);
  5878. EXPECT_EQ(StatusCode::OK_200, res->status);
  5879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5880. EXPECT_EQ("Hello World!", res->body);
  5881. res = cli_.Get("/hi");
  5882. ASSERT_TRUE(res);
  5883. EXPECT_EQ(StatusCode::OK_200, res->status);
  5884. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5885. EXPECT_EQ("Hello World!", res->body);
  5886. res = cli_.Get("/hi");
  5887. ASSERT_TRUE(res);
  5888. EXPECT_EQ(StatusCode::OK_200, res->status);
  5889. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5890. EXPECT_EQ("Hello World!", res->body);
  5891. res = cli_.Get("/not-exist");
  5892. ASSERT_TRUE(res);
  5893. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5894. res = cli_.Post("/empty", "", "text/plain");
  5895. ASSERT_TRUE(res);
  5896. EXPECT_EQ(StatusCode::OK_200, res->status);
  5897. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5898. EXPECT_EQ("empty", res->body);
  5899. EXPECT_EQ("close", res->get_header_value("Connection"));
  5900. res = cli_.Post(
  5901. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5902. "text/plain");
  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("empty", res->body);
  5907. cli_.set_keep_alive(false);
  5908. res = cli_.Get("/last-request");
  5909. ASSERT_TRUE(res);
  5910. EXPECT_EQ(StatusCode::OK_200, res->status);
  5911. EXPECT_EQ("close", res->get_header_value("Connection"));
  5912. }
  5913. TEST_F(ServerTest, TooManyRedirect) {
  5914. cli_.set_follow_location(true);
  5915. auto res = cli_.Get("/redirect/0");
  5916. ASSERT_TRUE(!res);
  5917. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5918. }
  5919. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5920. Request req;
  5921. req.method = "FOOBAR";
  5922. req.path = "/hi";
  5923. cli_.set_keep_alive(true);
  5924. auto res = cli_.send(req);
  5925. ASSERT_TRUE(res);
  5926. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5927. EXPECT_EQ("close", res->get_header_value("Connection"));
  5928. EXPECT_FALSE(cli_.is_socket_open());
  5929. }
  5930. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5931. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5932. TEST_F(ServerTest, Gzip) {
  5933. Headers headers;
  5934. headers.emplace("Accept-Encoding", "gzip, deflate");
  5935. auto res = cli_.Get("/compress", headers);
  5936. ASSERT_TRUE(res);
  5937. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5938. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5939. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5940. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5941. "7890123456789012345678901234567890",
  5942. res->body);
  5943. EXPECT_EQ(StatusCode::OK_200, res->status);
  5944. }
  5945. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5946. Headers headers;
  5947. headers.emplace("Accept-Encoding", "gzip, deflate");
  5948. auto res = cli_.Get("/compress-with-charset", headers);
  5949. ASSERT_TRUE(res);
  5950. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5951. EXPECT_EQ("application/json; charset=utf-8",
  5952. res->get_header_value("Content-Type"));
  5953. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5954. "7890123456789012345678901234567890",
  5955. res->body);
  5956. EXPECT_EQ(StatusCode::OK_200, res->status);
  5957. }
  5958. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5959. Headers headers;
  5960. headers.emplace("Accept-Encoding", "");
  5961. auto res = cli_.Get("/compress", headers);
  5962. ASSERT_TRUE(res);
  5963. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5965. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5966. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5967. "7890123456789012345678901234567890",
  5968. res->body);
  5969. EXPECT_EQ(StatusCode::OK_200, res->status);
  5970. }
  5971. TEST_F(ServerTest, GzipWithContentReceiver) {
  5972. Headers headers;
  5973. headers.emplace("Accept-Encoding", "gzip, deflate");
  5974. std::string body;
  5975. auto res = cli_.Get("/compress", headers,
  5976. [&](const char *data, uint64_t data_length) {
  5977. EXPECT_EQ(100U, data_length);
  5978. body.append(data, data_length);
  5979. return true;
  5980. });
  5981. ASSERT_TRUE(res);
  5982. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5983. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5984. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5985. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5986. "7890123456789012345678901234567890",
  5987. body);
  5988. EXPECT_EQ(StatusCode::OK_200, res->status);
  5989. }
  5990. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5991. Headers headers;
  5992. headers.emplace("Accept-Encoding", "gzip, deflate");
  5993. cli_.set_decompress(false);
  5994. auto res = cli_.Get("/compress", headers);
  5995. ASSERT_TRUE(res);
  5996. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5998. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5999. EXPECT_EQ(33U, res->body.size());
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. }
  6002. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6003. Headers headers;
  6004. headers.emplace("Accept-Encoding", "");
  6005. std::string body;
  6006. auto res = cli_.Get("/compress", headers,
  6007. [&](const char *data, uint64_t data_length) {
  6008. EXPECT_EQ(100U, data_length);
  6009. body.append(data, data_length);
  6010. return true;
  6011. });
  6012. ASSERT_TRUE(res);
  6013. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6015. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6016. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6017. "7890123456789012345678901234567890",
  6018. body);
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. }
  6021. TEST_F(ServerTest, NoGzip) {
  6022. Headers headers;
  6023. headers.emplace("Accept-Encoding", "gzip, deflate");
  6024. auto res = cli_.Get("/nocompress", headers);
  6025. ASSERT_TRUE(res);
  6026. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6027. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6029. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6030. "7890123456789012345678901234567890",
  6031. res->body);
  6032. EXPECT_EQ(StatusCode::OK_200, res->status);
  6033. }
  6034. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6035. Headers headers;
  6036. headers.emplace("Accept-Encoding", "gzip, deflate");
  6037. std::string body;
  6038. auto res = cli_.Get("/nocompress", headers,
  6039. [&](const char *data, uint64_t data_length) {
  6040. EXPECT_EQ(100U, data_length);
  6041. body.append(data, data_length);
  6042. return true;
  6043. });
  6044. ASSERT_TRUE(res);
  6045. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6046. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6047. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6048. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6049. "7890123456789012345678901234567890",
  6050. body);
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. }
  6053. TEST_F(ServerTest, MultipartFormDataGzip) {
  6054. UploadFormDataItems items = {
  6055. {"key1", "test", "", ""},
  6056. {"key2", "--abcdefg123", "", ""},
  6057. };
  6058. cli_.set_compress(true);
  6059. auto res = cli_.Post("/compress-multipart", items);
  6060. ASSERT_TRUE(res);
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. }
  6063. #endif
  6064. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6065. TEST_F(ServerTest, Brotli) {
  6066. Headers headers;
  6067. headers.emplace("Accept-Encoding", "br");
  6068. auto res = cli_.Get("/compress", headers);
  6069. ASSERT_TRUE(res);
  6070. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6071. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6072. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6073. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6074. "7890123456789012345678901234567890",
  6075. res->body);
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. }
  6078. #endif
  6079. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6080. TEST_F(ServerTest, Zstd) {
  6081. Headers headers;
  6082. headers.emplace("Accept-Encoding", "zstd");
  6083. auto res = cli_.Get("/compress", headers);
  6084. ASSERT_TRUE(res);
  6085. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6087. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6088. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6089. "7890123456789012345678901234567890",
  6090. res->body);
  6091. EXPECT_EQ(StatusCode::OK_200, res->status);
  6092. }
  6093. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6094. Headers headers;
  6095. headers.emplace("Accept-Encoding", "");
  6096. auto res = cli_.Get("/compress", headers);
  6097. ASSERT_TRUE(res);
  6098. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6100. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6101. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6102. "7890123456789012345678901234567890",
  6103. res->body);
  6104. EXPECT_EQ(StatusCode::OK_200, res->status);
  6105. }
  6106. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6107. Headers headers;
  6108. headers.emplace("Accept-Encoding", "zstd");
  6109. std::string body;
  6110. auto res = cli_.Get("/compress", headers,
  6111. [&](const char *data, uint64_t data_length) {
  6112. EXPECT_EQ(100U, data_length);
  6113. body.append(data, data_length);
  6114. return true;
  6115. });
  6116. ASSERT_TRUE(res);
  6117. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6118. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6119. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6120. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6121. "7890123456789012345678901234567890",
  6122. body);
  6123. EXPECT_EQ(StatusCode::OK_200, res->status);
  6124. }
  6125. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6126. Headers headers;
  6127. headers.emplace("Accept-Encoding", "zstd");
  6128. cli_.set_decompress(false);
  6129. auto res = cli_.Get("/compress", headers);
  6130. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6131. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6132. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6133. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6134. ASSERT_TRUE(res);
  6135. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6138. EXPECT_EQ(StatusCode::OK_200, res->status);
  6139. ASSERT_EQ(26U, res->body.size());
  6140. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6141. 0);
  6142. }
  6143. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6144. Headers headers;
  6145. headers.emplace("Accept-Encoding", "");
  6146. std::string body;
  6147. auto res = cli_.Get("/compress", headers,
  6148. [&](const char *data, uint64_t data_length) {
  6149. EXPECT_EQ(100U, data_length);
  6150. body.append(data, data_length);
  6151. return true;
  6152. });
  6153. ASSERT_TRUE(res);
  6154. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6155. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6156. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6157. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6158. "7890123456789012345678901234567890",
  6159. body);
  6160. EXPECT_EQ(StatusCode::OK_200, res->status);
  6161. }
  6162. TEST_F(ServerTest, NoZstd) {
  6163. Headers headers;
  6164. headers.emplace("Accept-Encoding", "zstd");
  6165. auto res = cli_.Get("/nocompress", headers);
  6166. ASSERT_TRUE(res);
  6167. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6168. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6169. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6170. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6171. "7890123456789012345678901234567890",
  6172. res->body);
  6173. EXPECT_EQ(StatusCode::OK_200, res->status);
  6174. }
  6175. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6176. Headers headers;
  6177. headers.emplace("Accept-Encoding", "zstd");
  6178. std::string body;
  6179. auto res = cli_.Get("/nocompress", headers,
  6180. [&](const char *data, uint64_t data_length) {
  6181. EXPECT_EQ(100U, data_length);
  6182. body.append(data, data_length);
  6183. return true;
  6184. });
  6185. ASSERT_TRUE(res);
  6186. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6187. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6188. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6189. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6190. "7890123456789012345678901234567890",
  6191. body);
  6192. EXPECT_EQ(StatusCode::OK_200, res->status);
  6193. }
  6194. // TODO: How to enable zstd ??
  6195. TEST_F(ServerTest, MultipartFormDataZstd) {
  6196. UploadFormDataItems items = {
  6197. {"key1", "test", "", ""},
  6198. {"key2", "--abcdefg123", "", ""},
  6199. };
  6200. Headers headers;
  6201. headers.emplace("Accept-Encoding", "zstd");
  6202. cli_.set_compress(true);
  6203. auto res = cli_.Post("/compress-multipart", headers, items);
  6204. ASSERT_TRUE(res);
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. }
  6207. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6208. Headers headers;
  6209. headers.emplace("Accept-Encoding", "zstd");
  6210. cli_.set_compress(true);
  6211. auto res = cli_.Put(
  6212. "/put", headers, 3,
  6213. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6214. sink.os << "PUT";
  6215. return true;
  6216. },
  6217. "text/plain");
  6218. ASSERT_TRUE(res);
  6219. EXPECT_EQ(StatusCode::OK_200, res->status);
  6220. EXPECT_EQ("PUT", res->body);
  6221. }
  6222. // Pre-compression logging tests
  6223. TEST_F(ServerTest, PreCompressionLogging) {
  6224. // Test data for compression (matches the actual /compress endpoint content)
  6225. const std::string test_content =
  6226. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6227. "3456789012345678901234567890";
  6228. // Variables to capture logging data
  6229. std::string pre_compression_body;
  6230. std::string pre_compression_content_type;
  6231. std::string pre_compression_content_encoding;
  6232. std::string post_compression_body;
  6233. std::string post_compression_content_type;
  6234. std::string post_compression_content_encoding;
  6235. // Set up pre-compression logger
  6236. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6237. const Response &res) {
  6238. pre_compression_body = res.body;
  6239. pre_compression_content_type = res.get_header_value("Content-Type");
  6240. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6241. });
  6242. // Set up post-compression logger
  6243. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6244. post_compression_body = res.body;
  6245. post_compression_content_type = res.get_header_value("Content-Type");
  6246. post_compression_content_encoding =
  6247. res.get_header_value("Content-Encoding");
  6248. });
  6249. // Test with gzip compression
  6250. Headers headers;
  6251. headers.emplace("Accept-Encoding", "gzip");
  6252. auto res = cli_.Get("/compress", headers);
  6253. // Verify response was compressed
  6254. ASSERT_TRUE(res);
  6255. EXPECT_EQ(StatusCode::OK_200, res->status);
  6256. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6257. // Verify pre-compression logger captured uncompressed content
  6258. EXPECT_EQ(test_content, pre_compression_body);
  6259. EXPECT_EQ("text/plain", pre_compression_content_type);
  6260. EXPECT_TRUE(pre_compression_content_encoding
  6261. .empty()); // No encoding header before compression
  6262. // Verify post-compression logger captured compressed content
  6263. EXPECT_NE(test_content,
  6264. post_compression_body); // Should be different after compression
  6265. EXPECT_EQ("text/plain", post_compression_content_type);
  6266. EXPECT_EQ("gzip", post_compression_content_encoding);
  6267. // Verify compressed content is smaller
  6268. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6269. }
  6270. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6271. const std::string test_content =
  6272. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6273. "3456789012345678901234567890";
  6274. std::string pre_compression_body;
  6275. std::string post_compression_body;
  6276. svr_.set_pre_compression_logger(
  6277. [&](const Request & /*req*/, const Response &res) {
  6278. pre_compression_body = res.body;
  6279. });
  6280. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6281. post_compression_body = res.body;
  6282. });
  6283. Headers headers;
  6284. headers.emplace("Accept-Encoding", "br");
  6285. auto res = cli_.Get("/compress", headers);
  6286. ASSERT_TRUE(res);
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6289. // Verify pre-compression content is uncompressed
  6290. EXPECT_EQ(test_content, pre_compression_body);
  6291. // Verify post-compression content is compressed
  6292. EXPECT_NE(test_content, post_compression_body);
  6293. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6294. }
  6295. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6296. const std::string test_content =
  6297. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6298. "3456789012345678901234567890";
  6299. std::string pre_compression_body;
  6300. std::string post_compression_body;
  6301. svr_.set_pre_compression_logger(
  6302. [&](const Request & /*req*/, const Response &res) {
  6303. pre_compression_body = res.body;
  6304. });
  6305. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6306. post_compression_body = res.body;
  6307. });
  6308. // Request without compression (use /nocompress endpoint)
  6309. Headers headers;
  6310. auto res = cli_.Get("/nocompress", headers);
  6311. ASSERT_TRUE(res);
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6314. // Pre-compression logger should not be called when no compression is applied
  6315. EXPECT_TRUE(
  6316. pre_compression_body.empty()); // Pre-compression logger not called
  6317. EXPECT_EQ(
  6318. test_content,
  6319. post_compression_body); // Post-compression logger captures final content
  6320. }
  6321. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6322. const std::string test_content =
  6323. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6324. "3456789012345678901234567890";
  6325. std::string pre_compression_body;
  6326. bool pre_logger_called = false;
  6327. // Set only pre-compression logger
  6328. svr_.set_pre_compression_logger(
  6329. [&](const Request & /*req*/, const Response &res) {
  6330. pre_compression_body = res.body;
  6331. pre_logger_called = true;
  6332. });
  6333. Headers headers;
  6334. headers.emplace("Accept-Encoding", "gzip");
  6335. auto res = cli_.Get("/compress", headers);
  6336. ASSERT_TRUE(res);
  6337. EXPECT_EQ(StatusCode::OK_200, res->status);
  6338. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6339. // Verify pre-compression logger was called
  6340. EXPECT_TRUE(pre_logger_called);
  6341. EXPECT_EQ(test_content, pre_compression_body);
  6342. }
  6343. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6344. {
  6345. // Test with Expect: 100-continue header - success case
  6346. // Server returns 100 Continue, client sends body, server returns 200 OK
  6347. Request req;
  6348. req.method = "POST";
  6349. req.path = "/post-large";
  6350. req.set_header("Expect", "100-continue");
  6351. req.body = LARGE_DATA;
  6352. Response res;
  6353. auto error = Error::Success;
  6354. cli_.set_keep_alive(true);
  6355. auto ret = cli_.send(req, res, error);
  6356. EXPECT_TRUE(ret);
  6357. EXPECT_EQ(StatusCode::OK_200, res.status);
  6358. EXPECT_EQ(LARGE_DATA, res.body);
  6359. }
  6360. {
  6361. // Test with Expect: 100-continue header - error case
  6362. // Client should not send the body when server returns an error
  6363. Request req;
  6364. req.method = "POST";
  6365. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6366. req.set_header("Expect", "100-continue");
  6367. req.body = LARGE_DATA;
  6368. Response res;
  6369. auto error = Error::Success;
  6370. auto start = std::chrono::high_resolution_clock::now();
  6371. cli_.set_keep_alive(true);
  6372. auto ret = cli_.send(req, res, error);
  6373. auto end = std::chrono::high_resolution_clock::now();
  6374. auto elapsed =
  6375. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6376. .count();
  6377. // With Expect: 100-continue, request completes successfully but with error
  6378. EXPECT_TRUE(ret);
  6379. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6380. EXPECT_EQ("close", res.get_header_value("Connection"));
  6381. EXPECT_FALSE(cli_.is_socket_open());
  6382. EXPECT_LE(elapsed, 2000);
  6383. }
  6384. {
  6385. // Send an extra GET request to ensure error recovery without hanging
  6386. Request req;
  6387. req.method = "GET";
  6388. req.path = "/hi";
  6389. auto start = std::chrono::high_resolution_clock::now();
  6390. auto res = cli_.send(req);
  6391. auto end = std::chrono::high_resolution_clock::now();
  6392. auto elapsed =
  6393. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6394. .count();
  6395. ASSERT_TRUE(res);
  6396. EXPECT_EQ(StatusCode::OK_200, res->status);
  6397. EXPECT_EQ("Hello World!", res->body);
  6398. EXPECT_LE(elapsed, 500);
  6399. }
  6400. }
  6401. TEST(ZstdDecompressor, ChunkedDecompression) {
  6402. std::string data;
  6403. for (size_t i = 0; i < 32 * 1024; ++i) {
  6404. data.push_back(static_cast<char>('a' + i % 26));
  6405. }
  6406. std::string compressed_data;
  6407. {
  6408. httplib::detail::zstd_compressor compressor;
  6409. bool result = compressor.compress(
  6410. data.data(), data.size(),
  6411. /*last=*/true,
  6412. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6413. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6414. compressed_data_size);
  6415. return true;
  6416. });
  6417. ASSERT_TRUE(result);
  6418. }
  6419. std::string decompressed_data;
  6420. {
  6421. httplib::detail::zstd_decompressor decompressor;
  6422. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6423. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6424. size_t chunk_size = 130;
  6425. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6426. chunk_begin += chunk_size) {
  6427. size_t current_chunk_size =
  6428. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6429. bool result = decompressor.decompress(
  6430. compressed_data.data() + chunk_begin, current_chunk_size,
  6431. [&](const char *decompressed_data_chunk,
  6432. size_t decompressed_data_chunk_size) {
  6433. decompressed_data.insert(decompressed_data.size(),
  6434. decompressed_data_chunk,
  6435. decompressed_data_chunk_size);
  6436. return true;
  6437. });
  6438. ASSERT_TRUE(result);
  6439. }
  6440. }
  6441. ASSERT_EQ(data, decompressed_data);
  6442. }
  6443. TEST(ZstdDecompressor, Decompress) {
  6444. std::string original_text = "Compressed with ZSTD";
  6445. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6446. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6447. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6448. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6449. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6450. std::string decompressed_data;
  6451. {
  6452. httplib::detail::zstd_decompressor decompressor;
  6453. bool result = decompressor.decompress(
  6454. compressed_data.data(), compressed_data.size(),
  6455. [&](const char *decompressed_data_chunk,
  6456. size_t decompressed_data_chunk_size) {
  6457. decompressed_data.insert(decompressed_data.size(),
  6458. decompressed_data_chunk,
  6459. decompressed_data_chunk_size);
  6460. return true;
  6461. });
  6462. ASSERT_TRUE(result);
  6463. }
  6464. ASSERT_EQ(original_text, decompressed_data);
  6465. }
  6466. #endif
  6467. // Sends a raw request to a server listening at HOST:PORT.
  6468. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6469. std::string *resp = nullptr) {
  6470. auto error = Error::Success;
  6471. auto client_sock = detail::create_client_socket(
  6472. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6473. /*connection_timeout_sec=*/5, 0,
  6474. /*read_timeout_sec=*/5, 0,
  6475. /*write_timeout_sec=*/5, 0, std::string(), error);
  6476. if (client_sock == INVALID_SOCKET) { return false; }
  6477. auto ret = detail::process_client_socket(
  6478. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6479. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6480. if (req.size() !=
  6481. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6482. return false;
  6483. }
  6484. char buf[512];
  6485. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6486. while (line_reader.getline()) {
  6487. if (resp) { *resp += line_reader.ptr(); }
  6488. }
  6489. return true;
  6490. });
  6491. detail::close_socket(client_sock);
  6492. return ret;
  6493. }
  6494. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6495. Server svr;
  6496. std::string header_value;
  6497. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6498. header_value = req.get_header_value("foo");
  6499. res.set_content("ok", "text/plain");
  6500. });
  6501. thread t = thread([&] { svr.listen(HOST, PORT); });
  6502. auto se = detail::scope_exit([&] {
  6503. svr.stop();
  6504. t.join();
  6505. ASSERT_FALSE(svr.is_running());
  6506. });
  6507. svr.wait_until_ready();
  6508. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6509. // like characters are not treated the same - use vertical tab and escape.
  6510. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6511. "foo: \t \v bar \x1B\t \r\n"
  6512. "Connection: close\r\n"
  6513. "\r\n";
  6514. std::string res;
  6515. ASSERT_TRUE(send_request(5, req, &res));
  6516. EXPECT_EQ(header_value, "");
  6517. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6518. }
  6519. // Sends a raw request and verifies that there isn't a crash or exception.
  6520. static void test_raw_request(const std::string &req,
  6521. std::string *out = nullptr) {
  6522. Server svr;
  6523. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6524. res.set_content("ok", "text/plain");
  6525. });
  6526. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6527. res.set_content("ok", "text/plain");
  6528. });
  6529. svr.Get("/header_field_value_check",
  6530. [&](const Request & /*req*/, Response &res) {
  6531. res.set_content("ok", "text/plain");
  6532. });
  6533. // Server read timeout must be longer than the client read timeout for the
  6534. // bug to reproduce, probably to force the server to process a request
  6535. // without a trailing blank line.
  6536. const time_t client_read_timeout_sec = 1;
  6537. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6538. bool listen_thread_ok = false;
  6539. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6540. auto se = detail::scope_exit([&] {
  6541. svr.stop();
  6542. t.join();
  6543. ASSERT_FALSE(svr.is_running());
  6544. EXPECT_TRUE(listen_thread_ok);
  6545. });
  6546. svr.wait_until_ready();
  6547. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6548. }
  6549. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6550. // A certain header line causes an exception if the header property is parsed
  6551. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6552. test_raw_request(
  6553. "GET /hi HTTP/1.1\r\n"
  6554. " : "
  6555. " "
  6556. " ");
  6557. }
  6558. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6559. // A certain header line causes an exception if the header property *name* is
  6560. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6561. // greedy matcher and requires backtracking when there are a lot of ":"
  6562. // characters.
  6563. // This occurs with libc++ but not libstdc++.
  6564. test_raw_request(
  6565. "GET /hi HTTP/1.1\r\n"
  6566. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6567. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6568. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6569. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6570. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6571. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6572. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6573. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6574. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6575. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6576. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6577. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6578. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6579. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6580. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6581. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6582. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6583. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6584. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6585. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6586. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6587. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6588. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6589. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6590. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6591. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6592. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6593. "&&&%%%");
  6594. }
  6595. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6596. // Make sure this doesn't crash the server.
  6597. // In a previous version of the header line regex, the "\r" rendered the line
  6598. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6599. // a new position where the leading white space ended and the field value
  6600. // began.
  6601. // The crash occurs with libc++ but not libstdc++.
  6602. test_raw_request("GET /hi HTTP/1.1\r\n"
  6603. "a:" +
  6604. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6605. "\r\n"
  6606. "\r\n");
  6607. }
  6608. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6609. std::string out;
  6610. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6611. "Content-Type: text/plain\r\n"
  6612. "Transfer-Encoding: chunked\r\n"
  6613. "\r\n"
  6614. "nothex\r\n",
  6615. &out);
  6616. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6617. }
  6618. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6619. std::string out;
  6620. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6621. "Content-Type: text/plain\r\n"
  6622. "Transfer-Encoding: chunked\r\n"
  6623. "\r\n"
  6624. "3\r\n"
  6625. "xyz\r\n"
  6626. "NaN\r\n",
  6627. &out);
  6628. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6629. }
  6630. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6631. std::string out;
  6632. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6633. "Content-Type: text/plain\r\n"
  6634. "Transfer-Encoding: chunked\r\n"
  6635. "\r\n"
  6636. // Length is too large for 64 bits.
  6637. "1ffffffffffffffff\r\n"
  6638. "xyz\r\n",
  6639. &out);
  6640. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6641. }
  6642. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6643. test_raw_request("GET /hi HTTP/1.1\r\n"
  6644. "Content-Type: text/plain\r\n\r");
  6645. }
  6646. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6647. std::string out;
  6648. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6649. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6650. }
  6651. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6652. Server svr;
  6653. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6654. EXPECT_TRUE(!req.remote_addr.empty());
  6655. });
  6656. thread t = thread([&] { svr.listen(HOST, PORT); });
  6657. auto se = detail::scope_exit([&] {
  6658. svr.stop();
  6659. t.join();
  6660. ASSERT_FALSE(svr.is_running());
  6661. });
  6662. svr.wait_until_ready();
  6663. // Send an invalid request line to trigger Bad Request
  6664. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6665. std::string out;
  6666. ASSERT_TRUE(send_request(5, bad_req, &out));
  6667. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6668. }
  6669. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6670. std::string out;
  6671. std::string request(
  6672. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6673. test_raw_request(request, &out);
  6674. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6675. }
  6676. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6677. std::string out;
  6678. std::string request(
  6679. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6680. test_raw_request(request, &out);
  6681. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6682. }
  6683. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6684. std::string out;
  6685. std::string request(
  6686. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6687. test_raw_request(request, &out);
  6688. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6689. }
  6690. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6691. std::string out;
  6692. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6693. "Test: \r\n\r\n",
  6694. &out);
  6695. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6696. }
  6697. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6698. Server svr;
  6699. std::string x_custom;
  6700. std::string cookie;
  6701. std::string xff;
  6702. std::string x_unicode;
  6703. std::string x_iis;
  6704. svr.Get("/check", [&](const Request &req, Response &res) {
  6705. x_custom = req.get_header_value("X-Custom");
  6706. cookie = req.get_header_value("Cookie");
  6707. xff = req.get_header_value("X-Forwarded-For");
  6708. x_unicode = req.get_header_value("X-Unicode");
  6709. x_iis = req.get_header_value("X-IIS");
  6710. res.set_content("ok", "text/plain");
  6711. });
  6712. thread t = thread([&] { svr.listen(HOST, PORT); });
  6713. auto se = detail::scope_exit([&] {
  6714. svr.stop();
  6715. t.join();
  6716. ASSERT_FALSE(svr.is_running());
  6717. });
  6718. svr.wait_until_ready();
  6719. const std::string req = "GET /check HTTP/1.1\r\n"
  6720. "Host: localhost\r\n"
  6721. "X-Custom: a%0D%0AInjected: b\r\n"
  6722. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6723. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6724. "X-Unicode: %E3%81%82\r\n"
  6725. "X-IIS: %u00E9\r\n"
  6726. "Connection: close\r\n"
  6727. "\r\n";
  6728. std::string res;
  6729. ASSERT_TRUE(send_request(5, req, &res));
  6730. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6731. // Every value must be returned verbatim (wire form), with no decoding.
  6732. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6733. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6734. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6735. EXPECT_EQ("%E3%81%82", x_unicode);
  6736. EXPECT_EQ("%u00E9", x_iis);
  6737. }
  6738. // Applications that previously relied on automatic percent-decoding can
  6739. // reproduce the old behavior by explicitly calling decode_path_component()
  6740. // or, for RFC 3986 conformance, decode_uri_component().
  6741. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6742. Server svr;
  6743. std::string decoded;
  6744. svr.Get("/check", [&](const Request &req, Response &res) {
  6745. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6746. res.set_content("ok", "text/plain");
  6747. });
  6748. thread t = thread([&] { svr.listen(HOST, PORT); });
  6749. auto se = detail::scope_exit([&] {
  6750. svr.stop();
  6751. t.join();
  6752. ASSERT_FALSE(svr.is_running());
  6753. });
  6754. svr.wait_until_ready();
  6755. const std::string req = "GET /check HTTP/1.1\r\n"
  6756. "Host: localhost\r\n"
  6757. "X-Custom: hello%20world\r\n"
  6758. "Connection: close\r\n"
  6759. "\r\n";
  6760. std::string res;
  6761. ASSERT_TRUE(send_request(5, req, &res));
  6762. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6763. EXPECT_EQ("hello world", decoded);
  6764. }
  6765. // Regression test for #2033. Browsers send Referer values that include
  6766. // percent-encoded characters such as %0A inside the URL. Decoding the
  6767. // header value would either trip the post-decode CR/LF/NUL guard (the
  6768. // original bug, returning 400) or, after that guard was relaxed, silently
  6769. // store a literal LF — both unacceptable. The wire form must round-trip.
  6770. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6771. Server svr;
  6772. std::string referer;
  6773. svr.Get("/check", [&](const Request &req, Response &res) {
  6774. referer = req.get_header_value("Referer");
  6775. res.set_content("ok", "text/plain");
  6776. });
  6777. thread t = thread([&] { svr.listen(HOST, PORT); });
  6778. auto se = detail::scope_exit([&] {
  6779. svr.stop();
  6780. t.join();
  6781. ASSERT_FALSE(svr.is_running());
  6782. });
  6783. svr.wait_until_ready();
  6784. const std::string req = "GET /check HTTP/1.1\r\n"
  6785. "Host: localhost\r\n"
  6786. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6787. "Connection: close\r\n"
  6788. "\r\n";
  6789. std::string res;
  6790. ASSERT_TRUE(send_request(5, req, &res));
  6791. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6792. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6793. }
  6794. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6795. Server svr;
  6796. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6797. res.set_header("Cache-Control", "no-cache");
  6798. res.set_chunked_content_provider(
  6799. "text/event-stream", [](size_t offset, DataSink &sink) {
  6800. std::string s = "data:";
  6801. s += std::to_string(offset);
  6802. s += "\n\n";
  6803. auto ret = sink.write(s.data(), s.size());
  6804. EXPECT_TRUE(ret);
  6805. std::this_thread::sleep_for(std::chrono::seconds(1));
  6806. return true;
  6807. });
  6808. });
  6809. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6810. svr.wait_until_ready();
  6811. Client client(HOST, PORT);
  6812. const Headers headers = {{"Accept", "text/event-stream"}};
  6813. auto get_thread = std::thread([&client, &headers]() {
  6814. auto res = client.Get(
  6815. "/events", headers,
  6816. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6817. });
  6818. auto se = detail::scope_exit([&] {
  6819. svr.stop();
  6820. get_thread.join();
  6821. listen_thread.join();
  6822. ASSERT_FALSE(svr.is_running());
  6823. });
  6824. // Give GET time to get a few messages.
  6825. std::this_thread::sleep_for(std::chrono::seconds(2));
  6826. }
  6827. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6828. httplib::Server svr;
  6829. svr.Post("/hi",
  6830. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6831. res.status = StatusCode::OK_200;
  6832. });
  6833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6834. svr.wait_until_ready();
  6835. Client cli(HOST, PORT);
  6836. auto res = cli.Post("/hi", "data", "text/plain");
  6837. ASSERT_TRUE(res);
  6838. EXPECT_EQ(StatusCode::OK_200, res->status);
  6839. svr.stop();
  6840. thread.join();
  6841. ASSERT_FALSE(svr.is_running());
  6842. res = cli.Post("/hi", "data", "text/plain");
  6843. ASSERT_FALSE(res);
  6844. }
  6845. TEST(ServerStopTest, ListenFailure) {
  6846. Server svr;
  6847. auto t = thread([&]() {
  6848. auto ret = svr.listen("????", PORT);
  6849. EXPECT_FALSE(ret);
  6850. });
  6851. svr.wait_until_ready();
  6852. svr.stop();
  6853. t.join();
  6854. }
  6855. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6856. TEST(ServerStopTest, Decommision) {
  6857. Server svr;
  6858. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6859. for (int i = 0; i < 4; i++) {
  6860. auto is_even = !(i % 2);
  6861. std::thread t{[&] {
  6862. try {
  6863. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6864. if (is_even) {
  6865. throw std::runtime_error("Some thing that happens to go wrong.");
  6866. }
  6867. svr.listen(HOST, PORT);
  6868. } catch (...) { svr.decommission(); }
  6869. }};
  6870. svr.wait_until_ready();
  6871. // Server is up
  6872. {
  6873. Client cli(HOST, PORT);
  6874. auto res = cli.Get("/hi");
  6875. if (is_even) {
  6876. EXPECT_FALSE(res);
  6877. } else {
  6878. EXPECT_TRUE(res);
  6879. EXPECT_EQ("hi...", res->body);
  6880. }
  6881. }
  6882. svr.stop();
  6883. t.join();
  6884. // Server is down...
  6885. {
  6886. Client cli(HOST, PORT);
  6887. auto res = cli.Get("/hi");
  6888. EXPECT_FALSE(res);
  6889. }
  6890. }
  6891. }
  6892. #endif
  6893. // Helper function for string body upload progress tests
  6894. template <typename SetupHandler, typename ClientCall>
  6895. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6896. ClientCall &&client_call,
  6897. const string &body) {
  6898. Server svr;
  6899. setup_handler(svr);
  6900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6901. auto se = detail::scope_exit([&] {
  6902. svr.stop();
  6903. t.join();
  6904. });
  6905. svr.wait_until_ready();
  6906. Client cli(HOST, PORT);
  6907. vector<uint64_t> progress_values;
  6908. bool progress_called = false;
  6909. auto res =
  6910. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6911. progress_values.push_back(current);
  6912. progress_called = true;
  6913. return true;
  6914. });
  6915. ASSERT_TRUE(res);
  6916. EXPECT_EQ(200, res->status);
  6917. EXPECT_TRUE(progress_called);
  6918. }
  6919. TEST(UploadProgressTest, PostStringBodyBasic) {
  6920. TestStringBodyUploadProgress(
  6921. [](Server &svr) {
  6922. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6923. res.set_content("received", "text/plain");
  6924. });
  6925. },
  6926. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6927. return cli.Post("/test", body, "text/plain", progress_callback);
  6928. },
  6929. "test data for upload progress");
  6930. }
  6931. TEST(UploadProgressTest, PutStringBodyBasic) {
  6932. TestStringBodyUploadProgress(
  6933. [](Server &svr) {
  6934. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6935. res.set_content("put received", "text/plain");
  6936. });
  6937. },
  6938. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6939. return cli.Put("/test", body, "text/plain", progress_callback);
  6940. },
  6941. "put test data for upload progress");
  6942. }
  6943. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6944. TestStringBodyUploadProgress(
  6945. [](Server &svr) {
  6946. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6947. res.set_content("patch received", "text/plain");
  6948. });
  6949. },
  6950. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6951. return cli.Patch("/test", body, "text/plain", progress_callback);
  6952. },
  6953. "patch test data for upload progress");
  6954. }
  6955. // Helper function for content provider upload progress tests
  6956. template <typename SetupHandler, typename ClientCall>
  6957. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6958. ClientCall &&client_call) {
  6959. Server svr;
  6960. setup_handler(svr);
  6961. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6962. auto se = detail::scope_exit([&] {
  6963. svr.stop();
  6964. t.join();
  6965. });
  6966. svr.wait_until_ready();
  6967. Client cli(HOST, PORT);
  6968. vector<uint64_t> progress_values;
  6969. auto res =
  6970. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6971. progress_values.push_back(current);
  6972. return true;
  6973. });
  6974. ASSERT_TRUE(res);
  6975. EXPECT_EQ(200, res->status);
  6976. EXPECT_FALSE(progress_values.empty());
  6977. }
  6978. TEST(UploadProgressTest, PostContentProviderProgress) {
  6979. TestContentProviderUploadProgress(
  6980. [](Server &svr) {
  6981. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6982. res.set_content("provider received", "text/plain");
  6983. });
  6984. },
  6985. [](Client &cli, UploadProgress progress_callback) {
  6986. return cli.Post(
  6987. "/test", 10,
  6988. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6989. sink.os << "test data";
  6990. return true;
  6991. },
  6992. "text/plain", progress_callback);
  6993. });
  6994. }
  6995. // Helper function for multipart upload progress tests
  6996. template <typename SetupHandler, typename ClientCall>
  6997. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6998. ClientCall &&client_call,
  6999. const string &endpoint) {
  7000. Server svr;
  7001. setup_handler(svr);
  7002. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7003. auto se = detail::scope_exit([&] {
  7004. svr.stop();
  7005. t.join();
  7006. });
  7007. svr.wait_until_ready();
  7008. Client cli(HOST, PORT);
  7009. vector<uint64_t> progress_values;
  7010. UploadFormDataItems items = {
  7011. {"field1", "value1", "", ""},
  7012. {"field2", "longer value for progress tracking test", "", ""},
  7013. {"file1", "file content data for upload progress", "test.txt",
  7014. "text/plain"}};
  7015. auto res = client_call(cli, endpoint, items,
  7016. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7017. progress_values.push_back(current);
  7018. return true;
  7019. });
  7020. ASSERT_TRUE(res);
  7021. EXPECT_EQ(200, res->status);
  7022. EXPECT_FALSE(progress_values.empty());
  7023. }
  7024. TEST(UploadProgressTest, PostMultipartProgress) {
  7025. TestMultipartUploadProgress(
  7026. [](Server &svr) {
  7027. svr.Post("/multipart", [](const Request &req, Response &res) {
  7028. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7029. res.set_content("multipart received", "text/plain");
  7030. });
  7031. },
  7032. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7033. UploadProgress progress_callback) {
  7034. return cli.Post(endpoint, items, progress_callback);
  7035. },
  7036. "/multipart");
  7037. }
  7038. // Helper function for basic download progress tests
  7039. template <typename SetupHandler, typename ClientCall>
  7040. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7041. ClientCall &&client_call, const string &endpoint,
  7042. size_t expected_content_size) {
  7043. Server svr;
  7044. setup_handler(svr);
  7045. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7046. auto se = detail::scope_exit([&] {
  7047. svr.stop();
  7048. t.join();
  7049. });
  7050. svr.wait_until_ready();
  7051. Client cli(HOST, PORT);
  7052. vector<uint64_t> progress_values;
  7053. auto res = client_call(cli, endpoint,
  7054. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7055. progress_values.push_back(current);
  7056. return true;
  7057. });
  7058. ASSERT_TRUE(res);
  7059. EXPECT_EQ(200, res->status);
  7060. EXPECT_FALSE(progress_values.empty());
  7061. EXPECT_EQ(expected_content_size, res->body.size());
  7062. }
  7063. TEST(DownloadProgressTest, GetBasic) {
  7064. TestBasicDownloadProgress(
  7065. [](Server &svr) {
  7066. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7067. string content(1000, 'D');
  7068. res.set_content(content, "text/plain");
  7069. });
  7070. },
  7071. [](Client &cli, const string &endpoint,
  7072. DownloadProgress progress_callback) {
  7073. return cli.Get(endpoint, progress_callback);
  7074. },
  7075. "/download", 1000u);
  7076. }
  7077. // Helper function for content receiver download progress tests
  7078. template <typename SetupHandler, typename ClientCall>
  7079. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7080. ClientCall &&client_call,
  7081. const string &endpoint,
  7082. size_t expected_content_size) {
  7083. Server svr;
  7084. setup_handler(svr);
  7085. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7086. auto se = detail::scope_exit([&] {
  7087. svr.stop();
  7088. t.join();
  7089. });
  7090. svr.wait_until_ready();
  7091. Client cli(HOST, PORT);
  7092. vector<uint64_t> progress_values;
  7093. string received_body;
  7094. auto res = client_call(
  7095. cli, endpoint,
  7096. [&](const char *data, size_t data_length) -> bool {
  7097. received_body.append(data, data_length);
  7098. return true;
  7099. },
  7100. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7101. progress_values.push_back(current);
  7102. return true;
  7103. });
  7104. ASSERT_TRUE(res);
  7105. EXPECT_EQ(200, res->status);
  7106. EXPECT_FALSE(progress_values.empty());
  7107. EXPECT_EQ(expected_content_size, received_body.size());
  7108. EXPECT_TRUE(res->body.empty());
  7109. }
  7110. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7111. TestContentReceiverDownloadProgress(
  7112. [](Server &svr) {
  7113. svr.Get("/download-receiver",
  7114. [](const Request & /*req*/, Response &res) {
  7115. string content(2000, 'R');
  7116. res.set_content(content, "text/plain");
  7117. });
  7118. },
  7119. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7120. DownloadProgress progress_callback) {
  7121. return cli.Get(endpoint, content_receiver, progress_callback);
  7122. },
  7123. "/download-receiver", 2000u);
  7124. }
  7125. TEST(StreamingTest, NoContentLengthStreaming) {
  7126. Server svr;
  7127. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7128. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7129. if (offset < 6) {
  7130. sink.os << (offset < 3 ? "a" : "b");
  7131. } else {
  7132. sink.done();
  7133. }
  7134. return true;
  7135. });
  7136. });
  7137. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7138. auto listen_se = detail::scope_exit([&] {
  7139. svr.stop();
  7140. listen_thread.join();
  7141. ASSERT_FALSE(svr.is_running());
  7142. });
  7143. svr.wait_until_ready();
  7144. Client client(HOST, PORT);
  7145. auto get_thread = std::thread([&client]() {
  7146. std::string s;
  7147. auto res =
  7148. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7149. s += std::string(data, len);
  7150. return true;
  7151. });
  7152. ASSERT_TRUE(res);
  7153. EXPECT_EQ(StatusCode::OK_200, res->status);
  7154. EXPECT_EQ("aaabbb", s);
  7155. });
  7156. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7157. // Give GET time to get a few messages.
  7158. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7159. }
  7160. TEST(MountTest, Unmount) {
  7161. Server svr;
  7162. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7163. auto se = detail::scope_exit([&] {
  7164. svr.stop();
  7165. listen_thread.join();
  7166. ASSERT_FALSE(svr.is_running());
  7167. });
  7168. svr.wait_until_ready();
  7169. Client cli("localhost", PORT);
  7170. svr.set_mount_point("/mount2", "./www2");
  7171. auto res = cli.Get("/");
  7172. ASSERT_TRUE(res);
  7173. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7174. res = cli.Get("/mount2/dir/test.html");
  7175. ASSERT_TRUE(res);
  7176. EXPECT_EQ(StatusCode::OK_200, res->status);
  7177. svr.set_mount_point("/", "./www");
  7178. res = cli.Get("/dir/");
  7179. ASSERT_TRUE(res);
  7180. EXPECT_EQ(StatusCode::OK_200, res->status);
  7181. svr.remove_mount_point("/");
  7182. res = cli.Get("/dir/");
  7183. ASSERT_TRUE(res);
  7184. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7185. svr.remove_mount_point("/mount2");
  7186. res = cli.Get("/mount2/dir/test.html");
  7187. ASSERT_TRUE(res);
  7188. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7189. }
  7190. TEST(MountTest, Redicect) {
  7191. Server svr;
  7192. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7193. auto se = detail::scope_exit([&] {
  7194. svr.stop();
  7195. listen_thread.join();
  7196. ASSERT_FALSE(svr.is_running());
  7197. });
  7198. svr.set_mount_point("/", "./www");
  7199. svr.wait_until_ready();
  7200. Client cli("localhost", PORT);
  7201. auto res = cli.Get("/dir/");
  7202. ASSERT_TRUE(res);
  7203. EXPECT_EQ(StatusCode::OK_200, res->status);
  7204. res = cli.Get("/dir");
  7205. ASSERT_TRUE(res);
  7206. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7207. res = cli.Get("/file");
  7208. ASSERT_TRUE(res);
  7209. EXPECT_EQ(StatusCode::OK_200, res->status);
  7210. res = cli.Get("/file/");
  7211. ASSERT_TRUE(res);
  7212. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7213. cli.set_follow_location(true);
  7214. res = cli.Get("/dir");
  7215. ASSERT_TRUE(res);
  7216. EXPECT_EQ(StatusCode::OK_200, res->status);
  7217. }
  7218. TEST(MountTest, MultibytesPathName) {
  7219. Server svr;
  7220. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7221. auto se = detail::scope_exit([&] {
  7222. svr.stop();
  7223. listen_thread.join();
  7224. ASSERT_FALSE(svr.is_running());
  7225. });
  7226. svr.set_mount_point("/", "./www");
  7227. svr.wait_until_ready();
  7228. Client cli("localhost", PORT);
  7229. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7230. ASSERT_TRUE(res);
  7231. EXPECT_EQ(StatusCode::OK_200, res->status);
  7232. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7233. }
  7234. #ifdef _WIN32
  7235. // Issue #2435: mmap::open() must succeed even when another handle holds
  7236. // the file open for writing (e.g. an active log file).
  7237. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7238. const char *path = "mmap_concurrent_writer_test.txt";
  7239. const char *content = "hello";
  7240. {
  7241. std::ofstream f(path, std::ios::binary);
  7242. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7243. }
  7244. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7245. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7246. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7247. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7248. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7249. detail::mmap m(path);
  7250. ASSERT_TRUE(m.is_open());
  7251. EXPECT_EQ(strlen(content), m.size());
  7252. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7253. }
  7254. #endif
  7255. TEST(KeepAliveTest, ReadTimeout) {
  7256. Server svr;
  7257. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7258. std::this_thread::sleep_for(std::chrono::seconds(2));
  7259. res.set_content("a", "text/plain");
  7260. });
  7261. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7262. res.set_content("b", "text/plain");
  7263. });
  7264. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7265. auto se = detail::scope_exit([&] {
  7266. svr.stop();
  7267. listen_thread.join();
  7268. ASSERT_FALSE(svr.is_running());
  7269. });
  7270. svr.wait_until_ready();
  7271. Client cli("localhost", PORT);
  7272. cli.set_keep_alive(true);
  7273. cli.set_read_timeout(std::chrono::seconds(1));
  7274. auto resa = cli.Get("/a");
  7275. ASSERT_FALSE(resa);
  7276. EXPECT_EQ(Error::Read, resa.error());
  7277. auto resb = cli.Get("/b");
  7278. ASSERT_TRUE(resb);
  7279. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7280. EXPECT_EQ("b", resb->body);
  7281. }
  7282. TEST(KeepAliveTest, MaxCount) {
  7283. size_t keep_alive_max_count = 3;
  7284. Server svr;
  7285. svr.set_keep_alive_max_count(keep_alive_max_count);
  7286. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7287. res.set_content("Hello World!", "text/plain");
  7288. });
  7289. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7290. auto se = detail::scope_exit([&] {
  7291. svr.stop();
  7292. listen_thread.join();
  7293. ASSERT_FALSE(svr.is_running());
  7294. });
  7295. svr.wait_until_ready();
  7296. Client cli(HOST, PORT);
  7297. cli.set_keep_alive(true);
  7298. for (size_t i = 0; i < 5; i++) {
  7299. auto result = cli.Get("/hi");
  7300. ASSERT_TRUE(result);
  7301. EXPECT_EQ(StatusCode::OK_200, result->status);
  7302. if (i == keep_alive_max_count - 1) {
  7303. EXPECT_EQ("close", result->get_header_value("Connection"));
  7304. } else {
  7305. EXPECT_FALSE(result->has_header("Connection"));
  7306. }
  7307. }
  7308. }
  7309. TEST(KeepAliveTest, Issue1041) {
  7310. Server svr;
  7311. svr.set_keep_alive_timeout(3);
  7312. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7313. res.set_content("Hello World!", "text/plain");
  7314. });
  7315. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7316. auto se = detail::scope_exit([&] {
  7317. svr.stop();
  7318. listen_thread.join();
  7319. ASSERT_FALSE(svr.is_running());
  7320. });
  7321. svr.wait_until_ready();
  7322. Client cli(HOST, PORT);
  7323. cli.set_keep_alive(true);
  7324. auto result = cli.Get("/hi");
  7325. ASSERT_TRUE(result);
  7326. EXPECT_EQ(StatusCode::OK_200, result->status);
  7327. std::this_thread::sleep_for(std::chrono::seconds(5));
  7328. result = cli.Get("/hi");
  7329. ASSERT_TRUE(result);
  7330. EXPECT_EQ(StatusCode::OK_200, result->status);
  7331. }
  7332. TEST(KeepAliveTest, Issue1959) {
  7333. Server svr;
  7334. svr.set_keep_alive_timeout(5);
  7335. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7336. res.set_content("a", "text/plain");
  7337. });
  7338. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7339. auto se = detail::scope_exit([&] {
  7340. if (!svr.is_running()) return;
  7341. svr.stop();
  7342. listen_thread.join();
  7343. ASSERT_FALSE(svr.is_running());
  7344. });
  7345. svr.wait_until_ready();
  7346. Client cli("localhost", PORT);
  7347. cli.set_keep_alive(true);
  7348. using namespace std::chrono;
  7349. auto start = steady_clock::now();
  7350. cli.Get("/a");
  7351. svr.stop();
  7352. listen_thread.join();
  7353. auto end = steady_clock::now();
  7354. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7355. EXPECT_LT(elapsed, 5000);
  7356. }
  7357. #ifdef CPPHTTPLIB_SSL_ENABLED
  7358. TEST(KeepAliveTest, SSLClientReconnection) {
  7359. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7360. ASSERT_TRUE(svr.is_valid());
  7361. svr.set_keep_alive_timeout(1);
  7362. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7363. res.set_content("Hello World!", "text/plain");
  7364. });
  7365. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7366. auto se = detail::scope_exit([&] {
  7367. svr.stop();
  7368. listen_thread.join();
  7369. ASSERT_FALSE(svr.is_running());
  7370. });
  7371. svr.wait_until_ready();
  7372. SSLClient cli(HOST, PORT);
  7373. cli.enable_server_certificate_verification(false);
  7374. cli.set_keep_alive(true);
  7375. auto result = cli.Get("/hi");
  7376. ASSERT_TRUE(result);
  7377. EXPECT_EQ(StatusCode::OK_200, result->status);
  7378. result = cli.Get("/hi");
  7379. ASSERT_TRUE(result);
  7380. EXPECT_EQ(StatusCode::OK_200, result->status);
  7381. std::this_thread::sleep_for(std::chrono::seconds(2));
  7382. // Recoonect
  7383. result = cli.Get("/hi");
  7384. ASSERT_TRUE(result);
  7385. EXPECT_EQ(StatusCode::OK_200, result->status);
  7386. result = cli.Get("/hi");
  7387. ASSERT_TRUE(result);
  7388. EXPECT_EQ(StatusCode::OK_200, result->status);
  7389. }
  7390. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7392. ASSERT_TRUE(svr.is_valid());
  7393. svr.set_keep_alive_timeout(1);
  7394. std::string content = "reconnect";
  7395. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7396. res.set_content("Hello World!", "text/plain");
  7397. });
  7398. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7399. auto se = detail::scope_exit([&] {
  7400. svr.stop();
  7401. listen_thread.join();
  7402. ASSERT_FALSE(svr.is_running());
  7403. });
  7404. svr.wait_until_ready();
  7405. SSLClient cli(HOST, PORT);
  7406. cli.enable_server_certificate_verification(false);
  7407. cli.set_keep_alive(true);
  7408. auto result = cli.Post(
  7409. "/hi", content.size(),
  7410. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7411. sink.write(content.c_str(), content.size());
  7412. return true;
  7413. },
  7414. "text/plain");
  7415. ASSERT_TRUE(result);
  7416. EXPECT_EQ(200, result->status);
  7417. std::this_thread::sleep_for(std::chrono::seconds(2));
  7418. // Recoonect
  7419. result = cli.Post(
  7420. "/hi", content.size(),
  7421. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7422. sink.write(content.c_str(), content.size());
  7423. return true;
  7424. },
  7425. "text/plain");
  7426. ASSERT_TRUE(result);
  7427. EXPECT_EQ(200, result->status);
  7428. result = cli.Post(
  7429. "/hi", content.size(),
  7430. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7431. sink.write(content.c_str(), content.size());
  7432. return true;
  7433. },
  7434. "text/plain");
  7435. ASSERT_TRUE(result);
  7436. EXPECT_EQ(200, result->status);
  7437. }
  7438. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7439. using namespace httplib::tls;
  7440. {
  7441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7442. ASSERT_TRUE(svr.is_valid());
  7443. svr.Get("/sni", [&](const Request &req, Response &res) {
  7444. std::string expected = req.sni();
  7445. EXPECT_EQ(expected, req.get_param_value("expected"));
  7446. res.set_content("ok", "text/plain");
  7447. });
  7448. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7449. auto se = detail::scope_exit([&] {
  7450. svr.stop();
  7451. listen_thread.join();
  7452. ASSERT_FALSE(svr.is_running());
  7453. });
  7454. svr.wait_until_ready();
  7455. {
  7456. SSLClient cli("localhost", PORT);
  7457. cli.enable_server_certificate_verification(false);
  7458. auto res = cli.Get("/sni?expected=localhost");
  7459. ASSERT_TRUE(res);
  7460. }
  7461. {
  7462. SSLClient cli("::1", PORT);
  7463. cli.enable_server_certificate_verification(false);
  7464. auto res = cli.Get("/sni?expected=");
  7465. // NOTE: This may fail if the server is listening on IPv4 only
  7466. // (e.g., when localhost resolves to 127.0.0.1 only)
  7467. if (res) {
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. } else {
  7470. EXPECT_EQ(Error::Connection, res.error());
  7471. }
  7472. }
  7473. }
  7474. }
  7475. #endif
  7476. TEST(ClientProblemDetectionTest, ContentProvider) {
  7477. Server svr;
  7478. size_t content_length = 1024 * 1024;
  7479. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7480. res.set_content_provider(
  7481. content_length, "text/plain",
  7482. [&](size_t offset, size_t length, DataSink &sink) {
  7483. auto out_len = std::min(length, static_cast<size_t>(1024));
  7484. std::string out(out_len, '@');
  7485. sink.write(out.data(), out_len);
  7486. return offset < 4096;
  7487. },
  7488. [](bool success) { ASSERT_FALSE(success); });
  7489. });
  7490. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7491. res.set_content_provider(
  7492. 0, "text/plain",
  7493. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7494. EXPECT_TRUE(false);
  7495. return true;
  7496. },
  7497. [](bool success) { ASSERT_FALSE(success); });
  7498. });
  7499. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7500. auto se = detail::scope_exit([&] {
  7501. svr.stop();
  7502. listen_thread.join();
  7503. ASSERT_FALSE(svr.is_running());
  7504. });
  7505. svr.wait_until_ready();
  7506. Client cli("localhost", PORT);
  7507. {
  7508. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7509. size_t /*data_length*/) { return false; });
  7510. ASSERT_FALSE(res);
  7511. }
  7512. {
  7513. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7514. size_t /*data_length*/) { return false; });
  7515. ASSERT_TRUE(res);
  7516. }
  7517. }
  7518. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7519. Server svr;
  7520. svr.set_error_handler([](Request const &, Response &res) -> void {
  7521. res.set_chunked_content_provider(
  7522. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7523. sink.os << "hello";
  7524. sink.os << "world";
  7525. sink.done();
  7526. return true;
  7527. });
  7528. });
  7529. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7530. auto se = detail::scope_exit([&] {
  7531. svr.stop();
  7532. listen_thread.join();
  7533. ASSERT_FALSE(svr.is_running());
  7534. });
  7535. svr.wait_until_ready();
  7536. Client cli("localhost", PORT);
  7537. auto res = cli.Get("/");
  7538. ASSERT_TRUE(res);
  7539. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7540. EXPECT_EQ("helloworld", res->body);
  7541. }
  7542. TEST(LongPollingTest, ClientCloseDetection) {
  7543. Server svr;
  7544. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7545. res.set_chunked_content_provider(
  7546. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7547. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7548. sink.os << "hello";
  7549. auto count = 10;
  7550. while (count > 0 && sink.is_writable()) {
  7551. this_thread::sleep_for(chrono::milliseconds(10));
  7552. count--;
  7553. }
  7554. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7555. return true;
  7556. });
  7557. });
  7558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7559. auto se = detail::scope_exit([&] {
  7560. svr.stop();
  7561. listen_thread.join();
  7562. ASSERT_FALSE(svr.is_running());
  7563. });
  7564. svr.wait_until_ready();
  7565. Client cli("localhost", PORT);
  7566. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7567. EXPECT_EQ("hello", string(data, data_length));
  7568. return false; // close the socket immediately.
  7569. });
  7570. ASSERT_FALSE(res);
  7571. }
  7572. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7573. Server svr;
  7574. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7575. res.set_chunked_content_provider(
  7576. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7577. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7578. sink.os << "hello";
  7579. EXPECT_TRUE(sink.os.good());
  7580. // Wait for the client to close the connection
  7581. auto count = 10;
  7582. while (count > 0 && sink.is_writable()) {
  7583. this_thread::sleep_for(chrono::milliseconds(10));
  7584. count--;
  7585. }
  7586. // After client disconnect, write repeatedly until the socket
  7587. // write actually fails (small writes may be absorbed by the
  7588. // kernel buffer)
  7589. std::string chunk(1024, 'x');
  7590. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7591. sink.os << chunk;
  7592. }
  7593. EXPECT_TRUE(sink.os.fail());
  7594. return true;
  7595. });
  7596. });
  7597. auto port = svr.bind_to_any_port("localhost");
  7598. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7599. auto se = detail::scope_exit([&] {
  7600. svr.stop();
  7601. listen_thread.join();
  7602. ASSERT_FALSE(svr.is_running());
  7603. });
  7604. svr.wait_until_ready();
  7605. Client cli("localhost", port);
  7606. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7607. EXPECT_EQ("hello", string(data, data_length));
  7608. return false; // close the socket immediately.
  7609. });
  7610. ASSERT_FALSE(res);
  7611. }
  7612. TEST(GetWithParametersTest, GetWithParameters) {
  7613. Server svr;
  7614. svr.Get("/", [&](const Request &req, Response &) {
  7615. EXPECT_EQ("world", req.get_param_value("hello"));
  7616. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7617. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7618. });
  7619. svr.Get("/params", [&](const Request &req, Response &) {
  7620. EXPECT_EQ("world", req.get_param_value("hello"));
  7621. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7622. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7623. });
  7624. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7625. EXPECT_EQ("resource-id", req.matches[1]);
  7626. EXPECT_EQ("foo", req.get_param_value("param1"));
  7627. EXPECT_EQ("bar", req.get_param_value("param2"));
  7628. });
  7629. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7630. EXPECT_EQ("user-id", req.path_params.at("id"));
  7631. EXPECT_EQ("foo", req.get_param_value("param1"));
  7632. EXPECT_EQ("bar", req.get_param_value("param2"));
  7633. });
  7634. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7635. auto se = detail::scope_exit([&] {
  7636. svr.stop();
  7637. listen_thread.join();
  7638. ASSERT_FALSE(svr.is_running());
  7639. });
  7640. svr.wait_until_ready();
  7641. {
  7642. Client cli(HOST, PORT);
  7643. Params params;
  7644. params.emplace("hello", "world");
  7645. params.emplace("hello2", "world2");
  7646. params.emplace("hello3", "world3");
  7647. auto res = cli.Get("/", params, Headers{});
  7648. ASSERT_TRUE(res);
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. {
  7652. Client cli(HOST, PORT);
  7653. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7654. ASSERT_TRUE(res);
  7655. EXPECT_EQ(StatusCode::OK_200, res->status);
  7656. }
  7657. {
  7658. Client cli(HOST, PORT);
  7659. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7660. ASSERT_TRUE(res);
  7661. EXPECT_EQ(StatusCode::OK_200, res->status);
  7662. }
  7663. {
  7664. Client cli(HOST, PORT);
  7665. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7666. ASSERT_TRUE(res);
  7667. EXPECT_EQ(StatusCode::OK_200, res->status);
  7668. }
  7669. }
  7670. TEST(GetWithParametersTest, GetWithParameters2) {
  7671. Server svr;
  7672. svr.Get("/", [&](const Request &req, Response &res) {
  7673. auto text = req.get_param_value("hello");
  7674. res.set_content(text, "text/plain");
  7675. });
  7676. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7677. auto se = detail::scope_exit([&] {
  7678. svr.stop();
  7679. listen_thread.join();
  7680. ASSERT_FALSE(svr.is_running());
  7681. });
  7682. svr.wait_until_ready();
  7683. Client cli("localhost", PORT);
  7684. Params params;
  7685. params.emplace("hello", "world");
  7686. std::string body;
  7687. auto res = cli.Get("/", params, Headers{},
  7688. [&](const char *data, size_t data_length) {
  7689. body.append(data, data_length);
  7690. return true;
  7691. });
  7692. ASSERT_TRUE(res);
  7693. EXPECT_EQ(StatusCode::OK_200, res->status);
  7694. EXPECT_EQ("world", body);
  7695. }
  7696. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7697. auto host = "httpbingo.org";
  7698. auto path = std::string{"/range/32"};
  7699. #ifdef CPPHTTPLIB_SSL_ENABLED
  7700. SSLClient cli(host);
  7701. #else
  7702. Client cli(host);
  7703. #endif
  7704. cli.set_default_headers({make_range_header({{1, 10}})});
  7705. cli.set_connection_timeout(5);
  7706. {
  7707. auto res = cli.Get(path);
  7708. ASSERT_TRUE(res);
  7709. EXPECT_EQ("bcdefghijk", res->body);
  7710. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7711. }
  7712. {
  7713. auto res = cli.Get(path);
  7714. ASSERT_TRUE(res);
  7715. EXPECT_EQ("bcdefghijk", res->body);
  7716. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7717. }
  7718. }
  7719. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7720. Server svr;
  7721. svr.set_default_headers({{"Hello", "World"}});
  7722. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7723. res.set_content("ok", "text/plain");
  7724. });
  7725. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7726. auto se = detail::scope_exit([&] {
  7727. svr.stop();
  7728. listen_thread.join();
  7729. ASSERT_FALSE(svr.is_running());
  7730. });
  7731. svr.wait_until_ready();
  7732. Client cli("localhost", PORT);
  7733. auto res = cli.Get("/");
  7734. ASSERT_TRUE(res);
  7735. EXPECT_EQ(StatusCode::OK_200, res->status);
  7736. EXPECT_EQ("ok", res->body);
  7737. EXPECT_EQ("World", res->get_header_value("Hello"));
  7738. }
  7739. #ifdef CPPHTTPLIB_SSL_ENABLED
  7740. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7741. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7742. ASSERT_TRUE(svr.is_valid());
  7743. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7744. std::this_thread::sleep_for(std::chrono::seconds(2));
  7745. res.set_content("a", "text/plain");
  7746. });
  7747. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7748. res.set_content("b", "text/plain");
  7749. });
  7750. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7751. auto se = detail::scope_exit([&] {
  7752. svr.stop();
  7753. listen_thread.join();
  7754. ASSERT_FALSE(svr.is_running());
  7755. });
  7756. svr.wait_until_ready();
  7757. SSLClient cli("localhost", PORT);
  7758. cli.enable_server_certificate_verification(false);
  7759. cli.set_keep_alive(true);
  7760. cli.set_read_timeout(std::chrono::seconds(1));
  7761. auto resa = cli.Get("/a");
  7762. ASSERT_TRUE(!resa);
  7763. EXPECT_EQ(Error::Read, resa.error());
  7764. auto resb = cli.Get("/b");
  7765. ASSERT_TRUE(resb);
  7766. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7767. EXPECT_EQ("b", resb->body);
  7768. }
  7769. #endif
  7770. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7771. protected:
  7772. ServerTestWithAI_PASSIVE()
  7773. : cli_(HOST, PORT)
  7774. #ifdef CPPHTTPLIB_SSL_ENABLED
  7775. ,
  7776. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7777. #endif
  7778. {
  7779. #ifdef CPPHTTPLIB_SSL_ENABLED
  7780. cli_.enable_server_certificate_verification(false);
  7781. #endif
  7782. }
  7783. virtual void SetUp() {
  7784. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7785. res.set_content("Hello World!", "text/plain");
  7786. });
  7787. t_ = thread(
  7788. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7789. svr_.wait_until_ready();
  7790. }
  7791. virtual void TearDown() {
  7792. svr_.stop();
  7793. t_.join();
  7794. }
  7795. #ifdef CPPHTTPLIB_SSL_ENABLED
  7796. SSLClient cli_;
  7797. SSLServer svr_;
  7798. #else
  7799. Client cli_;
  7800. Server svr_;
  7801. #endif
  7802. thread t_;
  7803. };
  7804. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7805. auto res = cli_.Get("/hi");
  7806. ASSERT_TRUE(res);
  7807. EXPECT_EQ(StatusCode::OK_200, res->status);
  7808. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7809. EXPECT_EQ("Hello World!", res->body);
  7810. }
  7811. class ServerUpDownTest : public ::testing::Test {
  7812. protected:
  7813. ServerUpDownTest() : cli_(HOST, PORT) {}
  7814. virtual void SetUp() {
  7815. t_ = thread([&]() {
  7816. svr_.bind_to_any_port(HOST);
  7817. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7818. ASSERT_TRUE(svr_.listen_after_bind());
  7819. });
  7820. svr_.wait_until_ready();
  7821. }
  7822. virtual void TearDown() {
  7823. svr_.stop();
  7824. t_.join();
  7825. }
  7826. Client cli_;
  7827. Server svr_;
  7828. thread t_;
  7829. };
  7830. TEST_F(ServerUpDownTest, QuickStartStop) {
  7831. // Should not crash, especially when run with
  7832. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7833. }
  7834. class PayloadMaxLengthTest : public ::testing::Test {
  7835. protected:
  7836. PayloadMaxLengthTest()
  7837. : cli_(HOST, PORT)
  7838. #ifdef CPPHTTPLIB_SSL_ENABLED
  7839. ,
  7840. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7841. #endif
  7842. {
  7843. #ifdef CPPHTTPLIB_SSL_ENABLED
  7844. cli_.enable_server_certificate_verification(false);
  7845. #endif
  7846. }
  7847. virtual void SetUp() {
  7848. svr_.set_payload_max_length(8);
  7849. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7850. res.set_content("test", "text/plain");
  7851. });
  7852. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7853. svr_.wait_until_ready();
  7854. }
  7855. virtual void TearDown() {
  7856. svr_.stop();
  7857. t_.join();
  7858. }
  7859. #ifdef CPPHTTPLIB_SSL_ENABLED
  7860. SSLClient cli_;
  7861. SSLServer svr_;
  7862. #else
  7863. Client cli_;
  7864. Server svr_;
  7865. #endif
  7866. thread t_;
  7867. };
  7868. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7869. auto res = cli_.Post("/test", "123456789", "text/plain");
  7870. ASSERT_TRUE(res);
  7871. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7872. res = cli_.Post("/test", "12345678", "text/plain");
  7873. ASSERT_TRUE(res);
  7874. EXPECT_EQ(StatusCode::OK_200, res->status);
  7875. }
  7876. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7877. // Test chunked encoding with payload exceeding the 8-byte limit
  7878. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7879. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7880. ASSERT_TRUE(res);
  7881. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7882. }
  7883. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7884. // Test chunked encoding with payload within the 8-byte limit
  7885. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7886. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7887. ASSERT_TRUE(res);
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. }
  7890. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7891. // Test using send_request to send chunked data exceeding payload limit
  7892. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7893. "Host: " +
  7894. std::string(HOST) + ":" + std::to_string(PORT) +
  7895. "\r\n"
  7896. "Transfer-Encoding: chunked\r\n"
  7897. "Connection: close\r\n"
  7898. "\r\n"
  7899. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7900. "0123456789\r\n"
  7901. "0\r\n" // End chunk
  7902. "\r\n";
  7903. std::string response;
  7904. bool result = send_request(1, chunked_request, &response);
  7905. if (!result) {
  7906. // If send_request fails, it might be because the server closed the
  7907. // connection due to payload limit enforcement, which is acceptable
  7908. SUCCEED()
  7909. << "Server rejected oversized chunked request (connection closed)";
  7910. } else {
  7911. // If we got a response, check if it's an error response or connection was
  7912. // closed early Short response length indicates connection was closed due to
  7913. // payload limit
  7914. if (response.length() <= 10) {
  7915. SUCCEED() << "Server closed connection for oversized chunked request";
  7916. } else {
  7917. // Check for error status codes
  7918. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7919. response.find("Payload Too Large") != std::string::npos ||
  7920. response.find("400") != std::string::npos);
  7921. }
  7922. }
  7923. }
  7924. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7925. // Test request without Content-Length header exceeding payload limit
  7926. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7927. "Host: " +
  7928. std::string(HOST) + ":" +
  7929. std::to_string(PORT) +
  7930. "\r\n"
  7931. "Connection: close\r\n"
  7932. "\r\n";
  7933. // Add payload exceeding the 8-byte limit
  7934. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7935. request_without_content_length += large_payload;
  7936. std::string response;
  7937. bool result = send_request(1, request_without_content_length, &response);
  7938. if (!result) {
  7939. // If send_request fails, server likely closed connection due to payload
  7940. // limit
  7941. SUCCEED() << "Server rejected oversized request without Content-Length "
  7942. "(connection closed)";
  7943. } else {
  7944. // Check if server responded with error or closed connection early
  7945. if (response.length() <= 10) {
  7946. SUCCEED() << "Server closed connection for oversized request without "
  7947. "Content-Length";
  7948. } else {
  7949. // Check for error status codes
  7950. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7951. response.find("Payload Too Large") != std::string::npos ||
  7952. response.find("400") != std::string::npos);
  7953. }
  7954. }
  7955. }
  7956. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7957. // Test request without Content-Length header within payload limit
  7958. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7959. "Host: " +
  7960. std::string(HOST) + ":" +
  7961. std::to_string(PORT) +
  7962. "\r\n"
  7963. "Connection: close\r\n"
  7964. "\r\n";
  7965. // Add payload within the 8-byte limit
  7966. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7967. request_without_content_length += small_payload;
  7968. std::string response;
  7969. bool result = send_request(1, request_without_content_length, &response);
  7970. // For requests without Content-Length, the server may have different behavior
  7971. // The key is that it should not reject due to payload limit for small
  7972. // payloads
  7973. if (result) {
  7974. // Check for any HTTP response (success or error, but not connection closed)
  7975. if (response.length() > 10) {
  7976. SUCCEED()
  7977. << "Server processed request without Content-Length within limit";
  7978. } else {
  7979. // Short response might indicate connection closed, which is acceptable
  7980. SUCCEED() << "Server closed connection for request without "
  7981. "Content-Length (acceptable behavior)";
  7982. }
  7983. } else {
  7984. // Connection failure might be due to protocol requirements
  7985. SUCCEED() << "Connection issue with request without Content-Length "
  7986. "(environment-specific)";
  7987. }
  7988. }
  7989. class LargePayloadMaxLengthTest : public ::testing::Test {
  7990. protected:
  7991. LargePayloadMaxLengthTest()
  7992. : cli_(HOST, PORT)
  7993. #ifdef CPPHTTPLIB_SSL_ENABLED
  7994. ,
  7995. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7996. #endif
  7997. {
  7998. #ifdef CPPHTTPLIB_SSL_ENABLED
  7999. cli_.enable_server_certificate_verification(false);
  8000. #endif
  8001. }
  8002. virtual void SetUp() {
  8003. // Set 10MB payload limit
  8004. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8005. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8006. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8007. res.set_content("Large payload test", "text/plain");
  8008. });
  8009. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8010. svr_.wait_until_ready();
  8011. }
  8012. virtual void TearDown() {
  8013. svr_.stop();
  8014. t_.join();
  8015. }
  8016. #ifdef CPPHTTPLIB_SSL_ENABLED
  8017. SSLClient cli_;
  8018. SSLServer svr_;
  8019. #else
  8020. Client cli_;
  8021. Server svr_;
  8022. #endif
  8023. thread t_;
  8024. };
  8025. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8026. // Test chunked encoding with payload within 10MB limit
  8027. std::string medium_payload(5 * 1024 * 1024,
  8028. 'A'); // 5MB payload, within 10MB limit
  8029. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8030. ASSERT_TRUE(res);
  8031. EXPECT_EQ(StatusCode::OK_200, res->status);
  8032. }
  8033. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8034. // Test chunked encoding with payload exceeding 10MB limit
  8035. std::string large_payload(12 * 1024 * 1024,
  8036. 'B'); // 12MB payload, exceeds 10MB limit
  8037. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8038. // Server may either return 413 or close the connection
  8039. if (res) {
  8040. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8041. } else {
  8042. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8043. }
  8044. }
  8045. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8046. // Test request without Content-Length header within 10MB limit
  8047. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8048. "Host: " +
  8049. std::string(HOST) + ":" +
  8050. std::to_string(PORT) +
  8051. "\r\n"
  8052. "Connection: close\r\n"
  8053. "\r\n";
  8054. // Add 1MB payload (within 10MB limit)
  8055. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8056. request_without_content_length += medium_payload;
  8057. std::string response;
  8058. bool result = send_request(5, request_without_content_length, &response);
  8059. if (result) {
  8060. // Should get a proper HTTP response for payloads within limit
  8061. if (response.length() > 10) {
  8062. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8063. "10MB limit";
  8064. } else {
  8065. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8066. "Content-Length)";
  8067. }
  8068. } else {
  8069. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8070. }
  8071. }
  8072. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8073. // Test request without Content-Length header exceeding 10MB limit
  8074. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8075. "Host: " +
  8076. std::string(HOST) + ":" +
  8077. std::to_string(PORT) +
  8078. "\r\n"
  8079. "Connection: close\r\n"
  8080. "\r\n";
  8081. // Add 12MB payload (exceeds 10MB limit)
  8082. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8083. request_without_content_length += large_payload;
  8084. std::string response;
  8085. bool result = send_request(10, request_without_content_length, &response);
  8086. if (!result) {
  8087. // Server should close connection due to payload limit
  8088. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8089. "(connection closed)";
  8090. } else {
  8091. // Check for error response
  8092. if (response.length() <= 10) {
  8093. SUCCEED()
  8094. << "Server closed connection for 12MB request exceeding 10MB limit";
  8095. } else {
  8096. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8097. response.find("Payload Too Large") != std::string::npos ||
  8098. response.find("400") != std::string::npos);
  8099. }
  8100. }
  8101. }
  8102. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8103. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8104. // path.
  8105. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8106. Server svr;
  8107. const size_t LIMIT = 64 * 1024; // 64KB
  8108. svr.set_payload_max_length(LIMIT);
  8109. size_t total = 0;
  8110. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8111. const ContentReader &content_reader) {
  8112. content_reader([&](const char * /*data*/, size_t len) {
  8113. total += len;
  8114. return true;
  8115. });
  8116. res.status = 200;
  8117. res.set_content("stream_ok", "text/plain");
  8118. });
  8119. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8120. auto se = detail::scope_exit([&] {
  8121. svr.stop();
  8122. thread.join();
  8123. ASSERT_FALSE(svr.is_running());
  8124. });
  8125. svr.wait_until_ready();
  8126. // Prepare 256KB raw data and gzip-compress it
  8127. std::string raw(256 * 1024, 'A');
  8128. std::string gz;
  8129. {
  8130. z_stream zs{};
  8131. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8132. Z_DEFAULT_STRATEGY);
  8133. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8134. zs.avail_in = static_cast<uInt>(raw.size());
  8135. char outbuf[4096];
  8136. int ret;
  8137. do {
  8138. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8139. zs.avail_out = sizeof(outbuf);
  8140. ret = deflate(&zs, Z_FINISH);
  8141. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8142. } while (ret != Z_STREAM_END);
  8143. deflateEnd(&zs);
  8144. }
  8145. Client cli(HOST, PORT);
  8146. cli.set_connection_timeout(std::chrono::seconds(5));
  8147. Headers headers = {{"Content-Encoding", "gzip"}};
  8148. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8149. "application/octet-stream");
  8150. ASSERT_TRUE(res);
  8151. // Server must reject oversized decompressed payloads with 413.
  8152. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8153. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8154. EXPECT_LE(total, LIMIT);
  8155. }
  8156. #endif
  8157. // Regression test for DoS vulnerability: a malicious server sending a response
  8158. // without Content-Length header must not cause unbounded memory consumption on
  8159. // the client side. The client should stop reading after a reasonable limit,
  8160. // similar to the server-side set_payload_max_length protection.
  8161. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8162. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8163. #ifndef _WIN32
  8164. signal(SIGPIPE, SIG_IGN);
  8165. #endif
  8166. auto server_thread = std::thread([] {
  8167. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8168. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8169. default_socket_options(srv);
  8170. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8171. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8172. sockaddr_in addr{};
  8173. addr.sin_family = AF_INET;
  8174. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8175. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8176. int opt = 1;
  8177. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8178. #ifdef _WIN32
  8179. reinterpret_cast<const char *>(&opt),
  8180. #else
  8181. &opt,
  8182. #endif
  8183. sizeof(opt));
  8184. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8185. ::listen(srv, 1);
  8186. sockaddr_in cli_addr{};
  8187. socklen_t cli_len = sizeof(cli_addr);
  8188. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8189. if (cli != INVALID_SOCKET) {
  8190. char buf[4096];
  8191. ::recv(cli, buf, sizeof(buf), 0);
  8192. // Malicious response: no Content-Length, no chunked encoding
  8193. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8194. "Connection: close\r\n"
  8195. "\r\n";
  8196. ::send(cli,
  8197. #ifdef _WIN32
  8198. static_cast<const char *>(response_header.c_str()),
  8199. static_cast<int>(response_header.size()),
  8200. #else
  8201. response_header.c_str(), response_header.size(),
  8202. #endif
  8203. 0);
  8204. // Send 10MB of data
  8205. std::string chunk(64 * 1024, 'A');
  8206. size_t total_sent = 0;
  8207. while (total_sent < MALICIOUS_DATA_SIZE) {
  8208. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8209. auto sent = ::send(cli,
  8210. #ifdef _WIN32
  8211. static_cast<const char *>(chunk.c_str()),
  8212. static_cast<int>(to_send),
  8213. #else
  8214. chunk.c_str(), to_send,
  8215. #endif
  8216. 0);
  8217. if (sent <= 0) break;
  8218. total_sent += static_cast<size_t>(sent);
  8219. }
  8220. detail::close_socket(cli);
  8221. }
  8222. detail::close_socket(srv);
  8223. });
  8224. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8225. size_t total_read = 0;
  8226. {
  8227. Client cli("127.0.0.1", PORT + 2);
  8228. cli.set_read_timeout(5, 0);
  8229. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8230. auto stream = cli.open_stream("GET", "/malicious");
  8231. ASSERT_TRUE(stream.is_valid());
  8232. char buffer[64 * 1024];
  8233. ssize_t n;
  8234. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8235. total_read += static_cast<size_t>(n);
  8236. }
  8237. } // StreamHandle and Client destroyed here, closing the socket
  8238. server_thread.join();
  8239. // With set_payload_max_length, the client must stop reading before consuming
  8240. // all 10MB. The read loop should be cut off at or near the configured limit.
  8241. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8242. << "Client read " << total_read << " bytes, exceeding the configured "
  8243. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8244. }
  8245. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8246. // the entire response body without truncation.
  8247. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8248. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8249. #ifndef _WIN32
  8250. signal(SIGPIPE, SIG_IGN);
  8251. #endif
  8252. auto server_thread = std::thread([] {
  8253. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8254. default_socket_options(srv);
  8255. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8256. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8257. sockaddr_in addr{};
  8258. addr.sin_family = AF_INET;
  8259. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8260. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8261. int opt = 1;
  8262. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8263. #ifdef _WIN32
  8264. reinterpret_cast<const char *>(&opt),
  8265. #else
  8266. &opt,
  8267. #endif
  8268. sizeof(opt));
  8269. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8270. ::listen(srv, 1);
  8271. sockaddr_in cli_addr{};
  8272. socklen_t cli_len = sizeof(cli_addr);
  8273. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8274. if (cli != INVALID_SOCKET) {
  8275. char buf[4096];
  8276. ::recv(cli, buf, sizeof(buf), 0);
  8277. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8278. "Connection: close\r\n"
  8279. "\r\n";
  8280. ::send(cli,
  8281. #ifdef _WIN32
  8282. static_cast<const char *>(response_header.c_str()),
  8283. static_cast<int>(response_header.size()),
  8284. #else
  8285. response_header.c_str(), response_header.size(),
  8286. #endif
  8287. 0);
  8288. std::string chunk(64 * 1024, 'A');
  8289. size_t total_sent = 0;
  8290. while (total_sent < DATA_SIZE) {
  8291. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8292. auto sent = ::send(cli,
  8293. #ifdef _WIN32
  8294. static_cast<const char *>(chunk.c_str()),
  8295. static_cast<int>(to_send),
  8296. #else
  8297. chunk.c_str(), to_send,
  8298. #endif
  8299. 0);
  8300. if (sent <= 0) break;
  8301. total_sent += static_cast<size_t>(sent);
  8302. }
  8303. #ifdef _WIN32
  8304. ::shutdown(cli, SD_SEND);
  8305. #else
  8306. ::shutdown(cli, SHUT_WR);
  8307. #endif
  8308. // Drain until the client closes its end, ensuring all data is delivered
  8309. char drain[1024];
  8310. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8311. detail::close_socket(cli);
  8312. }
  8313. detail::close_socket(srv);
  8314. });
  8315. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8316. size_t total_read = 0;
  8317. {
  8318. Client cli("127.0.0.1", PORT + 2);
  8319. cli.set_read_timeout(5, 0);
  8320. cli.set_payload_max_length(0); // 0 means no limit
  8321. auto stream = cli.open_stream("GET", "/data");
  8322. ASSERT_TRUE(stream.is_valid());
  8323. char buffer[64 * 1024];
  8324. ssize_t n;
  8325. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8326. total_read += static_cast<size_t>(n);
  8327. }
  8328. }
  8329. server_thread.join();
  8330. EXPECT_EQ(total_read, DATA_SIZE)
  8331. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8332. << " bytes without truncation, but only read " << total_read << " bytes.";
  8333. }
  8334. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8335. // enormous Content-Length must not cause the client to pre-allocate a huge
  8336. // response body buffer. The reservation is capped at payload_max_length_, and
  8337. // the read itself fails when the body exceeds the limit.
  8338. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8339. #ifndef _WIN32
  8340. signal(SIGPIPE, SIG_IGN);
  8341. #endif
  8342. auto server_thread = std::thread([] {
  8343. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8344. default_socket_options(srv);
  8345. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8346. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8347. sockaddr_in addr{};
  8348. addr.sin_family = AF_INET;
  8349. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8350. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8351. int opt = 1;
  8352. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8353. #ifdef _WIN32
  8354. reinterpret_cast<const char *>(&opt),
  8355. #else
  8356. &opt,
  8357. #endif
  8358. sizeof(opt));
  8359. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8360. ::listen(srv, 1);
  8361. sockaddr_in cli_addr{};
  8362. socklen_t cli_len = sizeof(cli_addr);
  8363. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8364. if (cli != INVALID_SOCKET) {
  8365. char buf[4096];
  8366. ::recv(cli, buf, sizeof(buf), 0);
  8367. // Malicious response: claim a 20GB body but send only a tiny payload.
  8368. std::string response = "HTTP/1.1 200 OK\r\n"
  8369. "Content-Length: 20000000000\r\n"
  8370. "\r\n"
  8371. "abc";
  8372. ::send(cli,
  8373. #ifdef _WIN32
  8374. static_cast<const char *>(response.c_str()),
  8375. static_cast<int>(response.size()),
  8376. #else
  8377. response.c_str(), response.size(),
  8378. #endif
  8379. 0);
  8380. detail::close_socket(cli);
  8381. }
  8382. detail::close_socket(srv);
  8383. });
  8384. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8385. {
  8386. Client cli("127.0.0.1", PORT + 2);
  8387. cli.set_read_timeout(5, 0);
  8388. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8389. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8390. // (server claims more bytes than payload_max_length permits), but it must
  8391. // not exhaust memory before getting there.
  8392. auto res = cli.Get("/malicious");
  8393. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8394. }
  8395. server_thread.join();
  8396. }
  8397. // Verify that content_receiver bypasses the default payload_max_length,
  8398. // allowing streaming downloads larger than 100MB without requiring an explicit
  8399. // set_payload_max_length call.
  8400. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8401. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8402. #ifndef _WIN32
  8403. signal(SIGPIPE, SIG_IGN);
  8404. #endif
  8405. auto server_thread = std::thread([] {
  8406. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8407. default_socket_options(srv);
  8408. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8409. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8410. sockaddr_in addr{};
  8411. addr.sin_family = AF_INET;
  8412. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8413. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8414. int opt = 1;
  8415. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8416. #ifdef _WIN32
  8417. reinterpret_cast<const char *>(&opt),
  8418. #else
  8419. &opt,
  8420. #endif
  8421. sizeof(opt));
  8422. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8423. ::listen(srv, 1);
  8424. sockaddr_in cli_addr{};
  8425. socklen_t cli_len = sizeof(cli_addr);
  8426. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8427. if (cli != INVALID_SOCKET) {
  8428. char buf[4096];
  8429. ::recv(cli, buf, sizeof(buf), 0);
  8430. // Response with Content-Length larger than default 100MB limit
  8431. auto content_length = std::to_string(DATA_SIZE);
  8432. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8433. "Content-Length: " +
  8434. content_length +
  8435. "\r\n"
  8436. "Connection: close\r\n"
  8437. "\r\n";
  8438. ::send(cli,
  8439. #ifdef _WIN32
  8440. static_cast<const char *>(response_header.c_str()),
  8441. static_cast<int>(response_header.size()),
  8442. #else
  8443. response_header.c_str(), response_header.size(),
  8444. #endif
  8445. 0);
  8446. std::string chunk(64 * 1024, 'A');
  8447. size_t total_sent = 0;
  8448. while (total_sent < DATA_SIZE) {
  8449. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8450. auto sent = ::send(cli,
  8451. #ifdef _WIN32
  8452. static_cast<const char *>(chunk.c_str()),
  8453. static_cast<int>(to_send),
  8454. #else
  8455. chunk.c_str(), to_send,
  8456. #endif
  8457. 0);
  8458. if (sent <= 0) break;
  8459. total_sent += static_cast<size_t>(sent);
  8460. }
  8461. detail::close_socket(cli);
  8462. }
  8463. detail::close_socket(srv);
  8464. });
  8465. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8466. size_t total_received = 0;
  8467. {
  8468. Client cli("127.0.0.1", PORT + 2);
  8469. cli.set_read_timeout(10, 0);
  8470. // Do NOT call set_payload_max_length — use the default 100MB limit
  8471. auto res =
  8472. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8473. total_received += data_length;
  8474. return true;
  8475. });
  8476. ASSERT_TRUE(res);
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. server_thread.join();
  8480. EXPECT_EQ(total_received, DATA_SIZE)
  8481. << "With content_receiver, the client should read all " << DATA_SIZE
  8482. << " bytes despite the default 100MB payload_max_length, but only read "
  8483. << total_received << " bytes.";
  8484. }
  8485. // Verify that an explicit set_payload_max_length smaller than the response is
  8486. // enforced even when a content_receiver is used.
  8487. TEST(ClientVulnerabilityTest,
  8488. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8489. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8490. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8491. #ifndef _WIN32
  8492. signal(SIGPIPE, SIG_IGN);
  8493. #endif
  8494. auto server_thread = std::thread([] {
  8495. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8496. default_socket_options(srv);
  8497. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8498. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8499. sockaddr_in addr{};
  8500. addr.sin_family = AF_INET;
  8501. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8502. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8503. int opt = 1;
  8504. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8505. #ifdef _WIN32
  8506. reinterpret_cast<const char *>(&opt),
  8507. #else
  8508. &opt,
  8509. #endif
  8510. sizeof(opt));
  8511. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8512. ::listen(srv, 1);
  8513. sockaddr_in cli_addr{};
  8514. socklen_t cli_len = sizeof(cli_addr);
  8515. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8516. if (cli != INVALID_SOCKET) {
  8517. char buf[4096];
  8518. ::recv(cli, buf, sizeof(buf), 0);
  8519. auto content_length = std::to_string(DATA_SIZE);
  8520. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8521. "Content-Length: " +
  8522. content_length +
  8523. "\r\n"
  8524. "Connection: close\r\n"
  8525. "\r\n";
  8526. ::send(cli,
  8527. #ifdef _WIN32
  8528. static_cast<const char *>(response_header.c_str()),
  8529. static_cast<int>(response_header.size()),
  8530. #else
  8531. response_header.c_str(), response_header.size(),
  8532. #endif
  8533. 0);
  8534. std::string chunk(64 * 1024, 'A');
  8535. size_t total_sent = 0;
  8536. while (total_sent < DATA_SIZE) {
  8537. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8538. auto sent = ::send(cli,
  8539. #ifdef _WIN32
  8540. static_cast<const char *>(chunk.c_str()),
  8541. static_cast<int>(to_send),
  8542. #else
  8543. chunk.c_str(), to_send,
  8544. #endif
  8545. 0);
  8546. if (sent <= 0) break;
  8547. total_sent += static_cast<size_t>(sent);
  8548. }
  8549. detail::close_socket(cli);
  8550. }
  8551. detail::close_socket(srv);
  8552. });
  8553. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8554. size_t total_received = 0;
  8555. {
  8556. Client cli("127.0.0.1", PORT + 2);
  8557. cli.set_read_timeout(10, 0);
  8558. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8559. auto res =
  8560. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8561. total_received += data_length;
  8562. return true;
  8563. });
  8564. // Should fail because 200MB exceeds the explicit 150MB limit
  8565. EXPECT_FALSE(res);
  8566. }
  8567. server_thread.join();
  8568. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8569. << "Client with content_receiver should respect the explicit "
  8570. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8571. << total_received << " bytes.";
  8572. }
  8573. // Verify that an explicit set_payload_max_length larger than the response
  8574. // allows the content_receiver to read all data successfully.
  8575. TEST(ClientVulnerabilityTest,
  8576. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8577. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8578. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8579. #ifndef _WIN32
  8580. signal(SIGPIPE, SIG_IGN);
  8581. #endif
  8582. auto server_thread = std::thread([] {
  8583. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8584. default_socket_options(srv);
  8585. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8586. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8587. sockaddr_in addr{};
  8588. addr.sin_family = AF_INET;
  8589. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8590. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8591. int opt = 1;
  8592. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8593. #ifdef _WIN32
  8594. reinterpret_cast<const char *>(&opt),
  8595. #else
  8596. &opt,
  8597. #endif
  8598. sizeof(opt));
  8599. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8600. ::listen(srv, 1);
  8601. sockaddr_in cli_addr{};
  8602. socklen_t cli_len = sizeof(cli_addr);
  8603. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8604. if (cli != INVALID_SOCKET) {
  8605. char buf[4096];
  8606. ::recv(cli, buf, sizeof(buf), 0);
  8607. auto content_length = std::to_string(DATA_SIZE);
  8608. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8609. "Content-Length: " +
  8610. content_length +
  8611. "\r\n"
  8612. "Connection: close\r\n"
  8613. "\r\n";
  8614. ::send(cli,
  8615. #ifdef _WIN32
  8616. static_cast<const char *>(response_header.c_str()),
  8617. static_cast<int>(response_header.size()),
  8618. #else
  8619. response_header.c_str(), response_header.size(),
  8620. #endif
  8621. 0);
  8622. std::string chunk(64 * 1024, 'A');
  8623. size_t total_sent = 0;
  8624. while (total_sent < DATA_SIZE) {
  8625. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8626. auto sent = ::send(cli,
  8627. #ifdef _WIN32
  8628. static_cast<const char *>(chunk.c_str()),
  8629. static_cast<int>(to_send),
  8630. #else
  8631. chunk.c_str(), to_send,
  8632. #endif
  8633. 0);
  8634. if (sent <= 0) break;
  8635. total_sent += static_cast<size_t>(sent);
  8636. }
  8637. #ifdef _WIN32
  8638. ::shutdown(cli, SD_SEND);
  8639. #else
  8640. ::shutdown(cli, SHUT_WR);
  8641. #endif
  8642. char drain[1024];
  8643. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8644. detail::close_socket(cli);
  8645. }
  8646. detail::close_socket(srv);
  8647. });
  8648. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8649. size_t total_received = 0;
  8650. {
  8651. Client cli("127.0.0.1", PORT + 2);
  8652. cli.set_read_timeout(10, 0);
  8653. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8654. auto res =
  8655. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8656. total_received += data_length;
  8657. return true;
  8658. });
  8659. ASSERT_TRUE(res);
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. }
  8662. server_thread.join();
  8663. EXPECT_EQ(total_received, DATA_SIZE)
  8664. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8665. << " bytes (larger than " << DATA_SIZE
  8666. << " bytes response), content_receiver should read all data, but only "
  8667. "read "
  8668. << total_received << " bytes.";
  8669. }
  8670. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8671. // Regression test for "zip bomb" attack on the client side: a malicious server
  8672. // sends a small gzip-compressed response that decompresses to a huge payload.
  8673. // The client must enforce payload_max_length on the decompressed size.
  8674. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8675. constexpr size_t DECOMPRESSED_SIZE =
  8676. 10 * 1024 * 1024; // 10MB after decompression
  8677. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8678. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8679. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8680. std::string compressed;
  8681. {
  8682. httplib::detail::gzip_compressor compressor;
  8683. bool ok =
  8684. compressor.compress(uncompressed.data(), uncompressed.size(),
  8685. /*last=*/true, [&](const char *buf, size_t len) {
  8686. compressed.append(buf, len);
  8687. return true;
  8688. });
  8689. ASSERT_TRUE(ok);
  8690. }
  8691. // Sanity: compressed data should be much smaller than the decompressed size
  8692. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8693. #ifndef _WIN32
  8694. signal(SIGPIPE, SIG_IGN);
  8695. #endif
  8696. // Set up the listening socket in the main thread so the server is guaranteed
  8697. // to be ready before the client connects (eliminates race condition).
  8698. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8699. default_socket_options(srv);
  8700. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8701. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8702. sockaddr_in addr{};
  8703. addr.sin_family = AF_INET;
  8704. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8705. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8706. int opt = 1;
  8707. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8708. #ifdef _WIN32
  8709. reinterpret_cast<const char *>(&opt),
  8710. #else
  8711. &opt,
  8712. #endif
  8713. sizeof(opt));
  8714. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8715. ASSERT_EQ(0, ::listen(srv, 1));
  8716. auto server_thread = std::thread([&compressed, srv] {
  8717. sockaddr_in cli_addr{};
  8718. socklen_t cli_len = sizeof(cli_addr);
  8719. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8720. if (cli != INVALID_SOCKET) {
  8721. // Read the full HTTP request (until \r\n\r\n)
  8722. char buf[4096];
  8723. size_t total = 0;
  8724. while (total < sizeof(buf)) {
  8725. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8726. if (n <= 0) break;
  8727. total += static_cast<size_t>(n);
  8728. // Check for end of headers
  8729. if (total >= 4) {
  8730. std::string req(buf, total);
  8731. if (req.find("\r\n\r\n") != std::string::npos) break;
  8732. }
  8733. }
  8734. // Malicious response: gzip-compressed body, no Content-Length
  8735. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8736. "Content-Encoding: gzip\r\n"
  8737. "Connection: close\r\n"
  8738. "\r\n";
  8739. ::send(cli,
  8740. #ifdef _WIN32
  8741. static_cast<const char *>(response_header.c_str()),
  8742. static_cast<int>(response_header.size()),
  8743. #else
  8744. response_header.c_str(), response_header.size(),
  8745. #endif
  8746. 0);
  8747. // Send the compressed payload (small on the wire, huge when decompressed)
  8748. size_t total_sent = 0;
  8749. while (total_sent < compressed.size()) {
  8750. auto to_send = std::min(compressed.size() - total_sent,
  8751. static_cast<size_t>(64 * 1024));
  8752. auto sent =
  8753. ::send(cli,
  8754. #ifdef _WIN32
  8755. static_cast<const char *>(compressed.c_str() + total_sent),
  8756. static_cast<int>(to_send),
  8757. #else
  8758. compressed.c_str() + total_sent, to_send,
  8759. #endif
  8760. 0);
  8761. if (sent <= 0) break;
  8762. total_sent += static_cast<size_t>(sent);
  8763. }
  8764. detail::close_socket(cli);
  8765. }
  8766. });
  8767. auto se = detail::scope_exit([&] {
  8768. detail::close_socket(srv);
  8769. server_thread.join();
  8770. });
  8771. size_t total_decompressed = 0;
  8772. {
  8773. Client cli("127.0.0.1", PORT + 3);
  8774. cli.set_read_timeout(5, 0);
  8775. cli.set_decompress(true);
  8776. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8777. auto stream = cli.open_stream("GET", "/zipbomb");
  8778. ASSERT_TRUE(stream.is_valid());
  8779. char buffer[64 * 1024];
  8780. ssize_t n;
  8781. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8782. total_decompressed += static_cast<size_t>(n);
  8783. }
  8784. }
  8785. // The decompressed size must be capped by payload_max_length. Without
  8786. // protection, the client would decompress the full 10MB from a tiny
  8787. // compressed payload, enabling a zip bomb DoS attack.
  8788. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8789. << "Client decompressed " << total_decompressed
  8790. << " bytes from a gzip response. The decompressed size should be "
  8791. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8792. }
  8793. #endif
  8794. TEST(HostAndPortPropertiesTest, NoSSL) {
  8795. httplib::Client cli("www.google.com", 1234);
  8796. ASSERT_EQ("www.google.com", cli.host());
  8797. ASSERT_EQ(1234, cli.port());
  8798. }
  8799. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8800. httplib::Client cli("www.google.com:1234");
  8801. ASSERT_EQ("www.google.com", cli.host());
  8802. ASSERT_EQ(1234, cli.port());
  8803. }
  8804. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8805. // Port number that overflows int — should not crash, client becomes invalid
  8806. httplib::Client cli("http://www.google.com:99999999999999999999");
  8807. ASSERT_FALSE(cli.is_valid());
  8808. }
  8809. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8810. // Port 99999 exceeds valid range (1-65535) — should not crash
  8811. httplib::Client cli("http://www.google.com:99999");
  8812. ASSERT_FALSE(cli.is_valid());
  8813. }
  8814. #ifdef CPPHTTPLIB_SSL_ENABLED
  8815. TEST(HostAndPortPropertiesTest, SSL) {
  8816. httplib::SSLClient cli("www.google.com");
  8817. ASSERT_EQ("www.google.com", cli.host());
  8818. ASSERT_EQ(443, cli.port());
  8819. }
  8820. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8821. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8822. std::string cert;
  8823. read_file(CA_CERT_FILE, cert);
  8824. httplib::SSLClient httplib_client("www.google.com");
  8825. // Load CA store first time
  8826. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8827. // Load CA store second time (update)
  8828. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8829. // Verify client is still valid and can make connections
  8830. httplib_client.enable_server_certificate_verification(true);
  8831. auto res = httplib_client.Get("/");
  8832. ASSERT_TRUE(res);
  8833. // Google may return 200 or 301 depending on various factors
  8834. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8835. res->status == StatusCode::MovedPermanently_301);
  8836. }
  8837. TEST(SSLClientTest, ServerNameIndication_Online) {
  8838. auto host = "httpbingo.org";
  8839. auto path = std::string{"/get"};
  8840. SSLClient cli(host, 443);
  8841. auto res = cli.Get(path);
  8842. ASSERT_TRUE(res);
  8843. ASSERT_EQ(StatusCode::OK_200, res->status);
  8844. }
  8845. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8846. // Use a site that will cause SSL verification failure due to self-signed cert
  8847. SSLClient cli("self-signed.badssl.com", 443);
  8848. cli.enable_server_certificate_verification(true);
  8849. auto res = cli.Get("/");
  8850. ASSERT_TRUE(!res);
  8851. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8852. // Verify backend error is captured for SSLServerVerification
  8853. // This occurs when certificate verification fails
  8854. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8855. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8856. EXPECT_NE(0UL, res.ssl_backend_error());
  8857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8858. // For OpenSSL, ssl_error is 0 for verification errors
  8859. EXPECT_EQ(0, res.ssl_error());
  8860. #if !defined(_WIN32) || \
  8861. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8862. // On non-Windows or when Windows Schannel is disabled, the error comes
  8863. // from OpenSSL's verification
  8864. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8865. res.ssl_backend_error());
  8866. #endif
  8867. #endif
  8868. }
  8869. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8870. // Use a site where hostname doesn't match the certificate
  8871. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8872. SSLClient cli("wrong.host.badssl.com", 443);
  8873. cli.enable_server_certificate_verification(true);
  8874. cli.enable_server_hostname_verification(true);
  8875. auto res = cli.Get("/");
  8876. ASSERT_TRUE(!res);
  8877. // The error type depends on when hostname verification occurs:
  8878. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8879. // - Mbed TLS: SSLServerVerification (during handshake)
  8880. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8881. res.error() == Error::SSLServerVerification);
  8882. // Verify backend error is captured for hostname verification failure
  8883. EXPECT_NE(0UL, res.ssl_backend_error());
  8884. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8885. // For OpenSSL, ssl_error is 0 for verification errors
  8886. EXPECT_EQ(0, res.ssl_error());
  8887. #if !defined(_WIN32) || \
  8888. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8889. // On non-Windows or when Windows Schannel is disabled, the error comes
  8890. // from OpenSSL's hostname verification
  8891. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8892. res.ssl_backend_error());
  8893. #endif
  8894. #endif
  8895. }
  8896. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8897. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8898. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8899. SSLClient cli("www.google.com", 443);
  8900. cli.enable_server_certificate_verification(true);
  8901. auto res = cli.Get("/");
  8902. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8903. }
  8904. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8905. SSLClient cli("www.google.com", 443);
  8906. cli.enable_server_certificate_verification(true);
  8907. cli.enable_windows_certificate_verification(false);
  8908. auto res = cli.Get("/");
  8909. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8910. }
  8911. #endif
  8912. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8913. Client cli("https://google.com");
  8914. auto res = cli.Get("/");
  8915. ASSERT_TRUE(res);
  8916. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8917. }
  8918. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8919. SSLClient cli("google.com");
  8920. cli.set_ca_cert_path(CA_CERT_FILE);
  8921. auto res = cli.Get("/");
  8922. ASSERT_TRUE(res);
  8923. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8924. }
  8925. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8926. SSLClient cli("google.com");
  8927. cli.enable_server_certificate_verification(true);
  8928. cli.set_ca_cert_path("hello");
  8929. auto res = cli.Get("/");
  8930. ASSERT_TRUE(!res);
  8931. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8932. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8933. // should be set
  8934. EXPECT_EQ(0, res.ssl_error());
  8935. // Verify backend error is captured for SSLLoadingCerts
  8936. // This error occurs when loading CA certificates fails
  8937. EXPECT_NE(0UL, res.ssl_backend_error());
  8938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8939. // OpenSSL specific error codes:
  8940. // > openssl errstr 0x80000002
  8941. // error:80000002:system library::No such file or directory
  8942. // > openssl errstr 0xA000126
  8943. // error:0A000126:SSL routines::unexpected eof while reading
  8944. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8945. res.ssl_backend_error() == 0xA000126);
  8946. #endif
  8947. }
  8948. TEST(SSLClientTest, ServerCertificateVerification4) {
  8949. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8950. ASSERT_TRUE(svr.is_valid());
  8951. svr.Get("/test", [&](const Request &, Response &res) {
  8952. res.set_content("test", "text/plain");
  8953. svr.stop();
  8954. ASSERT_TRUE(true);
  8955. });
  8956. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8957. auto se = detail::scope_exit([&] {
  8958. t.join();
  8959. ASSERT_FALSE(svr.is_running());
  8960. });
  8961. svr.wait_until_ready();
  8962. SSLClient cli("127.0.0.1", PORT);
  8963. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8964. cli.enable_server_certificate_verification(true);
  8965. cli.set_connection_timeout(30);
  8966. auto res = cli.Get("/test");
  8967. ASSERT_TRUE(res);
  8968. ASSERT_EQ(StatusCode::OK_200, res->status);
  8969. }
  8970. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8971. std::string cert;
  8972. read_file(CA_CERT_FILE, cert);
  8973. SSLClient cli("google.com");
  8974. cli.load_ca_cert_store(cert.data(), cert.size());
  8975. const auto res = cli.Get("/");
  8976. ASSERT_TRUE(res);
  8977. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8978. }
  8979. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8980. // clang-format off
  8981. static constexpr char cert[] =
  8982. "GlobalSign Root CA\n"
  8983. "==================\n"
  8984. "-----BEGIN CERTIFICATE-----\n"
  8985. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8986. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8987. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8988. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8989. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8990. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8991. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8992. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8993. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8994. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8995. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8996. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8997. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8998. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8999. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9000. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9001. "-----END CERTIFICATE-----\n";
  9002. // clang-format on
  9003. SSLClient cli("google.com");
  9004. cli.load_ca_cert_store(cert, sizeof(cert));
  9005. const auto res = cli.Get("/");
  9006. ASSERT_TRUE(res);
  9007. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9008. }
  9009. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9010. SSLClient cli("www.youtube.com");
  9011. cli.set_ca_cert_path(CA_CERT_FILE);
  9012. cli.enable_server_certificate_verification(true);
  9013. cli.set_follow_location(true);
  9014. auto res = cli.Get("/");
  9015. ASSERT_TRUE(res);
  9016. ASSERT_EQ(StatusCode::OK_200, res->status);
  9017. }
  9018. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9019. SSLClient cli("wWw.YouTube.Com");
  9020. cli.set_ca_cert_path(CA_CERT_FILE);
  9021. cli.enable_server_certificate_verification(true);
  9022. cli.enable_server_hostname_verification(true);
  9023. cli.set_follow_location(true);
  9024. auto res = cli.Get("/");
  9025. ASSERT_TRUE(res);
  9026. ASSERT_EQ(StatusCode::OK_200, res->status);
  9027. }
  9028. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9029. SSLClient cli("gOoGlE.COm");
  9030. cli.enable_server_certificate_verification(true);
  9031. cli.enable_server_hostname_verification(true);
  9032. cli.set_follow_location(true);
  9033. auto res = cli.Get("/");
  9034. ASSERT_TRUE(res);
  9035. ASSERT_EQ(StatusCode::OK_200, res->status);
  9036. }
  9037. TEST(SSLClientTest, Issue2004_Online) {
  9038. Client client("https://google.com");
  9039. client.set_follow_location(true);
  9040. auto res = client.Get("/");
  9041. ASSERT_TRUE(res);
  9042. ASSERT_EQ(StatusCode::OK_200, res->status);
  9043. auto body = res->body;
  9044. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9045. }
  9046. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9047. // Create SSLClient with invalid cert/key to make is_valid() return false
  9048. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9049. "nonexistent_key.pem");
  9050. // is_valid() should be false due to cert loading failure
  9051. ASSERT_FALSE(cli.is_valid());
  9052. auto res = cli.Get("/");
  9053. ASSERT_FALSE(res);
  9054. EXPECT_EQ(Error::SSLConnection, res.error());
  9055. }
  9056. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9057. // Test for Issue #2251: SSL error not properly reported when client cert
  9058. // and key paths are swapped or mismatched
  9059. // This simulates the scenario where user accidentally swaps the cert and key
  9060. // files
  9061. // Using client cert file as private key and vice versa (completely wrong)
  9062. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9063. // Should fail validation due to cert/key mismatch
  9064. ASSERT_FALSE(cli.is_valid());
  9065. // Attempt to make a request should fail with proper error
  9066. auto res = cli.Get("/");
  9067. ASSERT_FALSE(res);
  9068. EXPECT_EQ(Error::SSLConnection, res.error());
  9069. // SSL error should be recorded in the Result object (this is the key fix for
  9070. // Issue #2251)
  9071. auto backend_error = res.ssl_backend_error();
  9072. EXPECT_NE(0u, backend_error);
  9073. }
  9074. // Tests cert/key mismatch detection at the TLS context level
  9075. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9076. // Test that using mismatched cert/key causes connection failure.
  9077. // We verify this at the SSLClient level rather than through internal
  9078. // TLS API functions.
  9079. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9080. cli.enable_server_certificate_verification(false);
  9081. cli.set_connection_timeout(2);
  9082. // The mismatch should cause a connection or handshake error
  9083. auto res = cli.Get("/test");
  9084. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9085. // Either way, the request should fail
  9086. EXPECT_FALSE(res);
  9087. }
  9088. #endif
  9089. #if 0
  9090. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9091. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9092. ASSERT_TRUE(cli != nullptr);
  9093. cli->set_address_family(AF_INET6);
  9094. cli->set_interface("en0");
  9095. auto res = cli->Get("/get");
  9096. ASSERT_TRUE(res);
  9097. ASSERT_EQ(StatusCode::OK_200, res->status);
  9098. }
  9099. #endif
  9100. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9101. #ifdef CPPHTTPLIB_SSL_ENABLED
  9102. void ClientCertPresent(
  9103. const std::string &client_cert_file,
  9104. const std::string &client_private_key_file,
  9105. const std::string &client_encrypted_private_key_pass = std::string()) {
  9106. using namespace httplib::tls;
  9107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9108. CLIENT_CA_CERT_DIR);
  9109. ASSERT_TRUE(svr.is_valid());
  9110. svr.Get("/test", [&](const Request &req, Response &res) {
  9111. res.set_content("test", "text/plain");
  9112. auto cert = req.peer_cert();
  9113. ASSERT_TRUE(static_cast<bool>(cert));
  9114. std::string common_name = cert.subject_cn();
  9115. EXPECT_EQ("Common Name", common_name);
  9116. });
  9117. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9118. auto se = detail::scope_exit([&] {
  9119. svr.stop();
  9120. t.join();
  9121. ASSERT_FALSE(svr.is_running());
  9122. });
  9123. svr.wait_until_ready();
  9124. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9125. client_encrypted_private_key_pass);
  9126. cli.enable_server_certificate_verification(false);
  9127. cli.set_connection_timeout(30);
  9128. auto res = cli.Get("/test");
  9129. ASSERT_TRUE(res);
  9130. ASSERT_EQ(StatusCode::OK_200, res->status);
  9131. }
  9132. TEST(SSLClientServerTest, ClientCertPresent) {
  9133. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9134. }
  9135. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9136. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9137. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9138. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9139. }
  9140. // PEM memory-based constructor tests (works with all TLS backends)
  9141. void PemMemoryClientCertPresent(
  9142. const std::string &client_cert_file,
  9143. const std::string &client_private_key_file,
  9144. const std::string &client_encrypted_private_key_pass = std::string()) {
  9145. // Read PEM files into memory
  9146. std::string server_cert_pem, server_key_pem;
  9147. std::string client_ca_pem;
  9148. std::string client_cert_pem, client_key_pem;
  9149. read_file(SERVER_CERT_FILE, server_cert_pem);
  9150. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9151. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9152. read_file(client_cert_file, client_cert_pem);
  9153. read_file(client_private_key_file, client_key_pem);
  9154. // Create server with PEM memory
  9155. SSLServer::PemMemory server_pem = {
  9156. server_cert_pem.c_str(),
  9157. server_cert_pem.size(),
  9158. server_key_pem.c_str(),
  9159. server_key_pem.size(),
  9160. client_ca_pem.c_str(),
  9161. client_ca_pem.size(),
  9162. nullptr // no password for server key
  9163. };
  9164. SSLServer svr(server_pem);
  9165. ASSERT_TRUE(svr.is_valid());
  9166. svr.Get("/test", [&](const Request &, Response &res) {
  9167. res.set_content("test", "text/plain");
  9168. });
  9169. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9170. auto se = detail::scope_exit([&] {
  9171. svr.stop();
  9172. t.join();
  9173. ASSERT_FALSE(svr.is_running());
  9174. });
  9175. svr.wait_until_ready();
  9176. // Create client with PEM memory
  9177. const char *password = client_encrypted_private_key_pass.empty()
  9178. ? nullptr
  9179. : client_encrypted_private_key_pass.c_str();
  9180. SSLClient::PemMemory client_pem = {
  9181. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9182. client_key_pem.size(), password};
  9183. SSLClient cli(HOST, PORT, client_pem);
  9184. cli.enable_server_certificate_verification(false);
  9185. cli.set_connection_timeout(30);
  9186. auto res = cli.Get("/test");
  9187. ASSERT_TRUE(res);
  9188. ASSERT_EQ(StatusCode::OK_200, res->status);
  9189. }
  9190. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9191. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9192. }
  9193. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9194. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9195. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9196. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9197. }
  9198. TEST(SSLClientServerTest, ClientCertMissing) {
  9199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9200. CLIENT_CA_CERT_DIR);
  9201. ASSERT_TRUE(svr.is_valid());
  9202. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9203. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. t.join();
  9207. ASSERT_FALSE(svr.is_running());
  9208. });
  9209. svr.wait_until_ready();
  9210. SSLClient cli(HOST, PORT);
  9211. cli.set_connection_timeout(30);
  9212. auto res = cli.Get("/test");
  9213. ASSERT_TRUE(!res);
  9214. // When client cert is missing and server requires it, connection fails
  9215. // Error type depends on backend implementation
  9216. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9217. res.error() == Error::SSLConnection);
  9218. // Verify backend error is captured
  9219. // Note: This test may have different error codes depending on the exact
  9220. // verification failure
  9221. EXPECT_NE(0UL, res.ssl_backend_error());
  9222. }
  9223. TEST(SSLClientServerTest, TrustDirOptional) {
  9224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9225. ASSERT_TRUE(svr.is_valid());
  9226. svr.Get("/test", [&](const Request &, Response &res) {
  9227. res.set_content("test", "text/plain");
  9228. });
  9229. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9230. auto se = detail::scope_exit([&] {
  9231. svr.stop();
  9232. t.join();
  9233. ASSERT_FALSE(svr.is_running());
  9234. });
  9235. svr.wait_until_ready();
  9236. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9237. cli.enable_server_certificate_verification(false);
  9238. cli.set_connection_timeout(30);
  9239. auto res = cli.Get("/test");
  9240. ASSERT_TRUE(res);
  9241. ASSERT_EQ(StatusCode::OK_200, res->status);
  9242. }
  9243. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9244. class NoListenSSLServer : public SSLServer {
  9245. public:
  9246. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9247. const char *client_ca_cert_file_path,
  9248. const char *client_ca_cert_dir_path = nullptr)
  9249. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9250. client_ca_cert_dir_path),
  9251. stop_(false) {}
  9252. std::atomic_bool stop_;
  9253. private:
  9254. bool process_and_close_socket(socket_t /*sock*/) override {
  9255. // Don't create SSL context
  9256. while (!stop_.load()) {
  9257. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9258. }
  9259. return true;
  9260. }
  9261. };
  9262. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9263. CLIENT_CA_CERT_FILE);
  9264. ASSERT_TRUE(svr.is_valid());
  9265. svr.Get("/test", [&](const Request &, Response &res) {
  9266. res.set_content("test", "text/plain");
  9267. });
  9268. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9269. auto se = detail::scope_exit([&] {
  9270. svr.stop_ = true;
  9271. svr.stop();
  9272. t.join();
  9273. ASSERT_FALSE(svr.is_running());
  9274. });
  9275. svr.wait_until_ready();
  9276. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9277. cli.enable_server_certificate_verification(false);
  9278. cli.set_connection_timeout(1);
  9279. auto res = cli.Get("/test");
  9280. ASSERT_TRUE(!res);
  9281. EXPECT_EQ(Error::SSLConnection, res.error());
  9282. // Timeout results in WantRead error code (maps to backend-specific value)
  9283. EXPECT_NE(0, res.ssl_error());
  9284. }
  9285. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9286. // Test SSLServer with client certificate verification using the standard
  9287. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9289. CLIENT_CA_CERT_DIR);
  9290. ASSERT_TRUE(svr.is_valid());
  9291. svr.Get("/test", [&](const Request &req, Response &res) {
  9292. res.set_content("test", "text/plain");
  9293. auto cert = req.peer_cert();
  9294. ASSERT_TRUE(static_cast<bool>(cert));
  9295. auto common_name = cert.subject_cn();
  9296. EXPECT_EQ("Common Name", common_name);
  9297. });
  9298. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9299. auto se = detail::scope_exit([&] {
  9300. svr.stop();
  9301. t.join();
  9302. ASSERT_FALSE(svr.is_running());
  9303. });
  9304. svr.wait_until_ready();
  9305. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9306. cli.enable_server_certificate_verification(false);
  9307. cli.set_connection_timeout(30);
  9308. auto res = cli.Get("/test");
  9309. ASSERT_TRUE(res);
  9310. ASSERT_EQ(StatusCode::OK_200, res->status);
  9311. }
  9312. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9313. // Verifies that wildcard matching and exact matching work consistently
  9314. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9315. using namespace httplib::tls;
  9316. // We need a running server to test against
  9317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9318. ASSERT_TRUE(svr.is_valid());
  9319. svr.Get("/test", [](const Request &, Response &res) {
  9320. res.set_content("ok", "text/plain");
  9321. });
  9322. thread t([&]() { svr.listen(HOST, PORT); });
  9323. auto se = detail::scope_exit([&] {
  9324. svr.stop();
  9325. t.join();
  9326. });
  9327. svr.wait_until_ready();
  9328. bool verify_callback_called = false;
  9329. bool verify_result_wrong = false;
  9330. SSLClient cli(HOST, PORT);
  9331. cli.enable_server_certificate_verification(true);
  9332. cli.set_ca_cert_path(CA_CERT_FILE);
  9333. cli.set_connection_timeout(5);
  9334. // Note: Test certificate has CN="Common Name", not "localhost"
  9335. bool verify_result_cn = false;
  9336. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9337. verify_callback_called = true;
  9338. if (!ctx.cert) return false;
  9339. // Test 1: "Common Name" should match (our test server cert CN)
  9340. verify_result_cn = ctx.check_hostname("Common Name");
  9341. // Test 2: wrong hostname should not match
  9342. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9343. return true; // Accept for the purpose of this test
  9344. });
  9345. auto res = cli.Get("/test");
  9346. // The request may succeed or fail depending on cert configuration
  9347. // but the callback should have been called
  9348. ASSERT_TRUE(verify_callback_called)
  9349. << "Verify callback should have been called";
  9350. // CN="Common Name" should match our test certificate
  9351. //
  9352. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9353. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9354. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9355. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9356. // <openssl/base.h>, which is included transitively when
  9357. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9358. #if defined(OPENSSL_IS_BORINGSSL)
  9359. EXPECT_FALSE(verify_result_cn)
  9360. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9361. #else
  9362. EXPECT_TRUE(verify_result_cn)
  9363. << "verify_hostname should match 'Common Name' (certificate CN)";
  9364. #endif
  9365. // Wrong hostname should not match
  9366. EXPECT_FALSE(verify_result_wrong)
  9367. << "verify_hostname should not match 'wronghost.example.com'";
  9368. }
  9369. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9370. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9371. // X509_check_ip behavior and must hold for every backend.
  9372. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9373. using namespace httplib::tls;
  9374. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9375. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9376. ASSERT_TRUE(svr.is_valid());
  9377. svr.Get("/test", [](const Request &, Response &res) {
  9378. res.set_content("ok", "text/plain");
  9379. });
  9380. thread t([&]() { svr.listen(HOST, PORT); });
  9381. auto se = detail::scope_exit([&] {
  9382. svr.stop();
  9383. t.join();
  9384. });
  9385. svr.wait_until_ready();
  9386. bool verify_callback_called = false;
  9387. bool ip_matched_via_cn = true;
  9388. SSLClient cli(HOST, PORT);
  9389. cli.enable_server_certificate_verification(true);
  9390. cli.set_ca_cert_path(CA_CERT_FILE);
  9391. cli.set_connection_timeout(5);
  9392. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9393. verify_callback_called = true;
  9394. if (!ctx.cert) return false;
  9395. // The IP appears only in the CN, so it must NOT be accepted.
  9396. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9397. return true; // Accept for the purpose of this test
  9398. });
  9399. cli.Get("/test");
  9400. ASSERT_TRUE(verify_callback_called)
  9401. << "Verify callback should have been called";
  9402. EXPECT_FALSE(ip_matched_via_cn)
  9403. << "An IP host must not be authenticated via the certificate CN";
  9404. }
  9405. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9406. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9407. using namespace httplib::tls;
  9408. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9409. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9410. ASSERT_TRUE(svr.is_valid());
  9411. svr.Get("/test", [](const Request &, Response &res) {
  9412. res.set_content("ok", "text/plain");
  9413. });
  9414. thread t([&]() { svr.listen(HOST, PORT); });
  9415. auto se = detail::scope_exit([&] {
  9416. svr.stop();
  9417. t.join();
  9418. });
  9419. svr.wait_until_ready();
  9420. bool verify_callback_called = false;
  9421. bool san_matched = false;
  9422. bool wrong_ipv6_matched = true;
  9423. bool cn_ipv6_matched = true;
  9424. SSLClient cli(HOST, PORT);
  9425. cli.enable_server_certificate_verification(true);
  9426. cli.set_ca_cert_path(CA_CERT_FILE);
  9427. cli.set_connection_timeout(5);
  9428. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9429. verify_callback_called = true;
  9430. if (!ctx.cert) return false;
  9431. // Matches the IPv6 iPAddress SAN.
  9432. san_matched = ctx.check_hostname("2001:db8::1");
  9433. // A different IPv6 address must not match.
  9434. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9435. // "::1" lives only in the CN, so it must not be accepted.
  9436. cn_ipv6_matched = ctx.check_hostname("::1");
  9437. return true; // Accept for the purpose of this test
  9438. });
  9439. cli.Get("/test");
  9440. ASSERT_TRUE(verify_callback_called)
  9441. << "Verify callback should have been called";
  9442. EXPECT_TRUE(san_matched)
  9443. << "verify_hostname should match an IPv6 iPAddress SAN";
  9444. EXPECT_FALSE(wrong_ipv6_matched)
  9445. << "verify_hostname should not match a non-matching IPv6 address";
  9446. EXPECT_FALSE(cn_ipv6_matched)
  9447. << "An IPv6 host must not be authenticated via the certificate CN";
  9448. }
  9449. #endif
  9450. // mbedTLS-specific callback constructor test
  9451. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9452. #ifdef CPPHTTPLIB_SSL_ENABLED
  9453. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9455. ASSERT_TRUE(svr.is_valid());
  9456. // Set up a handler to verify client certificate is present
  9457. bool client_cert_verified = false;
  9458. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9459. // Verify that client certificate was provided
  9460. client_cert_verified = true;
  9461. res.set_content("success", "text/plain");
  9462. });
  9463. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9464. auto se = detail::scope_exit([&] {
  9465. svr.stop();
  9466. t.join();
  9467. ASSERT_FALSE(svr.is_running());
  9468. });
  9469. svr.wait_until_ready();
  9470. // Client with certificate
  9471. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9472. cli.enable_server_certificate_verification(false);
  9473. cli.set_connection_timeout(30);
  9474. auto res = cli.Get("/test");
  9475. ASSERT_TRUE(res);
  9476. ASSERT_EQ(StatusCode::OK_200, res->status);
  9477. ASSERT_TRUE(client_cert_verified);
  9478. EXPECT_EQ("success", res->body);
  9479. }
  9480. #endif
  9481. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9482. // backends
  9483. #ifdef CPPHTTPLIB_SSL_ENABLED
  9484. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9485. using namespace httplib::tls;
  9486. // Test that when client CA cert file is provided,
  9487. // the server properly requests and validates client certificates
  9488. // Create a server with client authentication
  9489. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9490. ASSERT_TRUE(svr.is_valid());
  9491. bool handler_called = false;
  9492. svr.Get("/test", [&](const Request &req, Response &res) {
  9493. handler_called = true;
  9494. // Verify that a client certificate was provided
  9495. auto cert = req.peer_cert();
  9496. ASSERT_TRUE(static_cast<bool>(cert));
  9497. // Get the issuer name
  9498. std::string issuer_str = cert.issuer_name();
  9499. ASSERT_FALSE(issuer_str.empty());
  9500. // The client certificate should be issued by our test CA
  9501. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9502. res.set_content("authenticated", "text/plain");
  9503. });
  9504. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9505. auto se = detail::scope_exit([&] {
  9506. svr.stop();
  9507. t.join();
  9508. ASSERT_FALSE(svr.is_running());
  9509. });
  9510. svr.wait_until_ready();
  9511. // Connect with a client certificate issued by the CA
  9512. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9513. cli.enable_server_certificate_verification(false);
  9514. cli.set_connection_timeout(30);
  9515. auto res = cli.Get("/test");
  9516. ASSERT_TRUE(res);
  9517. ASSERT_EQ(StatusCode::OK_200, res->status);
  9518. ASSERT_TRUE(handler_called);
  9519. EXPECT_EQ("authenticated", res->body);
  9520. }
  9521. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9522. using namespace httplib::tls;
  9523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9524. ASSERT_TRUE(svr.is_valid());
  9525. svr.Get("/test", [](const Request &, Response &res) {
  9526. res.set_content("ok", "text/plain");
  9527. });
  9528. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. });
  9533. svr.wait_until_ready();
  9534. SSLClient cli(HOST, PORT);
  9535. cli.enable_server_certificate_verification(false);
  9536. cli.set_connection_timeout(30);
  9537. bool cert_checked = false;
  9538. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9539. if (ctx.cert) {
  9540. auto sans = ctx.sans();
  9541. // Test certificate may or may not have SANs - just verify the API
  9542. // works If SANs exist, verify the types are valid
  9543. for (const auto &san : sans) {
  9544. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9545. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9546. san.type == SanType::OTHER);
  9547. EXPECT_FALSE(san.value.empty());
  9548. }
  9549. cert_checked = true;
  9550. }
  9551. return true;
  9552. });
  9553. auto res = cli.Get("/test");
  9554. ASSERT_TRUE(res);
  9555. EXPECT_TRUE(cert_checked);
  9556. }
  9557. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9558. using namespace httplib::tls;
  9559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9560. ASSERT_TRUE(svr.is_valid());
  9561. svr.Get("/test", [](const Request &, Response &res) {
  9562. res.set_content("ok", "text/plain");
  9563. });
  9564. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9565. auto se = detail::scope_exit([&] {
  9566. svr.stop();
  9567. t.join();
  9568. });
  9569. svr.wait_until_ready();
  9570. SSLClient cli(HOST, PORT);
  9571. cli.enable_server_certificate_verification(false);
  9572. cli.set_connection_timeout(30);
  9573. bool validity_checked = false;
  9574. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9575. if (ctx.cert) {
  9576. time_t not_before = 0, not_after = 0;
  9577. bool result = ctx.validity(not_before, not_after);
  9578. EXPECT_TRUE(result);
  9579. // Verify that not_before < now < not_after for a valid cert
  9580. time_t now = time(nullptr);
  9581. EXPECT_LT(not_before, now);
  9582. EXPECT_GT(not_after, now);
  9583. validity_checked = true;
  9584. }
  9585. return true;
  9586. });
  9587. auto res = cli.Get("/test");
  9588. ASSERT_TRUE(res);
  9589. EXPECT_TRUE(validity_checked);
  9590. }
  9591. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9592. using namespace httplib::tls;
  9593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9594. ASSERT_TRUE(svr.is_valid());
  9595. svr.Get("/test", [](const Request &, Response &res) {
  9596. res.set_content("ok", "text/plain");
  9597. });
  9598. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9599. auto se = detail::scope_exit([&] {
  9600. svr.stop();
  9601. t.join();
  9602. });
  9603. svr.wait_until_ready();
  9604. SSLClient cli(HOST, PORT);
  9605. cli.enable_server_certificate_verification(false);
  9606. cli.set_connection_timeout(30);
  9607. bool serial_checked = false;
  9608. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9609. if (ctx.cert) {
  9610. std::string serial = ctx.serial();
  9611. EXPECT_FALSE(serial.empty());
  9612. // Serial should be a hex string
  9613. for (char c : serial) {
  9614. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9615. (c >= 'a' && c <= 'f'));
  9616. }
  9617. serial_checked = true;
  9618. }
  9619. return true;
  9620. });
  9621. auto res = cli.Get("/test");
  9622. ASSERT_TRUE(res);
  9623. EXPECT_TRUE(serial_checked);
  9624. }
  9625. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9626. // Test 1: Valid CA file - no error should be recorded
  9627. {
  9628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9629. CLIENT_CA_CERT_FILE);
  9630. ASSERT_TRUE(svr.is_valid());
  9631. // With valid setup, last_ssl_error should be 0
  9632. EXPECT_EQ(0, svr.ssl_last_error());
  9633. }
  9634. // Test 2: Invalid CA file content
  9635. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9636. {
  9637. // Create a temporary file with completely invalid content
  9638. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9639. {
  9640. std::ofstream ofs(temp_invalid_ca);
  9641. ofs << "This is not a certificate file at all\n";
  9642. ofs << "Just plain text content\n";
  9643. }
  9644. // Create server with invalid CA file
  9645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9646. // Clean up temporary file
  9647. std::remove(temp_invalid_ca);
  9648. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9649. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9650. // Note: SSL_CTX_load_verify_locations typically fails first,
  9651. // but our error handling code path is still exercised
  9652. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9653. }
  9654. }
  9655. TEST(VerifyCallbackTest, VerifyContextFields) {
  9656. using namespace httplib::tls;
  9657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9658. ASSERT_TRUE(svr.is_valid());
  9659. svr.Get("/test", [](const Request &, Response &res) {
  9660. res.set_content("ok", "text/plain");
  9661. });
  9662. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9663. auto se = detail::scope_exit([&] {
  9664. svr.stop();
  9665. t.join();
  9666. });
  9667. svr.wait_until_ready();
  9668. SSLClient cli(HOST, PORT);
  9669. cli.enable_server_certificate_verification(false);
  9670. cli.set_connection_timeout(30);
  9671. int callback_count = 0;
  9672. bool saw_leaf_cert = false;
  9673. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9674. if (ctx.cert) {
  9675. callback_count++;
  9676. // We should see at least one certificate (the leaf)
  9677. std::string cn = ctx.subject_cn();
  9678. if (!cn.empty()) { saw_leaf_cert = true; }
  9679. // Verify context fields are populated
  9680. EXPECT_NE(ctx.session, nullptr);
  9681. EXPECT_GE(ctx.depth, 0);
  9682. }
  9683. return true;
  9684. });
  9685. auto res = cli.Get("/test");
  9686. ASSERT_TRUE(res);
  9687. EXPECT_GT(callback_count, 0);
  9688. EXPECT_TRUE(saw_leaf_cert);
  9689. }
  9690. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9691. using httplib::tls::TlsError;
  9692. // Test that verify_error_to_string returns empty for success
  9693. std::string success_str = TlsError::verify_error_to_string(0);
  9694. EXPECT_TRUE(success_str.empty());
  9695. // Test that verify_error_to_string returns non-empty for error codes
  9696. // Using a common error code (certificate expired)
  9697. std::string error_str =
  9698. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9699. EXPECT_FALSE(error_str.empty());
  9700. }
  9701. TEST(SessionVerifierTest, CertificateAccepted) {
  9702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9703. ASSERT_TRUE(svr.is_valid());
  9704. svr.Get("/test", [](const Request &, Response &res) {
  9705. res.set_content("ok", "text/plain");
  9706. });
  9707. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9708. auto se = detail::scope_exit([&] {
  9709. svr.stop();
  9710. t.join();
  9711. });
  9712. svr.wait_until_ready();
  9713. SSLClient cli(HOST, PORT);
  9714. cli.enable_server_certificate_verification(false);
  9715. cli.set_connection_timeout(30);
  9716. bool callback_called = false;
  9717. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9718. EXPECT_NE(session, nullptr);
  9719. callback_called = true;
  9720. return SSLVerifierResponse::CertificateAccepted;
  9721. });
  9722. auto res = cli.Get("/test");
  9723. ASSERT_TRUE(res);
  9724. EXPECT_EQ(200, res->status);
  9725. EXPECT_TRUE(callback_called);
  9726. }
  9727. TEST(SessionVerifierTest, CertificateRejected) {
  9728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9729. ASSERT_TRUE(svr.is_valid());
  9730. svr.Get("/test", [](const Request &, Response &res) {
  9731. res.set_content("ok", "text/plain");
  9732. });
  9733. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9734. auto se = detail::scope_exit([&] {
  9735. svr.stop();
  9736. t.join();
  9737. });
  9738. svr.wait_until_ready();
  9739. SSLClient cli(HOST, PORT);
  9740. cli.enable_server_certificate_verification(false);
  9741. cli.set_connection_timeout(30);
  9742. bool callback_called = false;
  9743. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9744. EXPECT_NE(session, nullptr);
  9745. callback_called = true;
  9746. return SSLVerifierResponse::CertificateRejected;
  9747. });
  9748. auto res = cli.Get("/test");
  9749. EXPECT_FALSE(res);
  9750. EXPECT_TRUE(callback_called);
  9751. }
  9752. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9753. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9754. ASSERT_TRUE(svr.is_valid());
  9755. svr.Get("/test", [](const Request &, Response &res) {
  9756. res.set_content("ok", "text/plain");
  9757. });
  9758. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9759. auto se = detail::scope_exit([&] {
  9760. svr.stop();
  9761. t.join();
  9762. });
  9763. svr.wait_until_ready();
  9764. // NoDecisionMade with verification disabled should succeed (no default check)
  9765. SSLClient cli(HOST, PORT);
  9766. cli.enable_server_certificate_verification(false);
  9767. cli.set_connection_timeout(30);
  9768. bool callback_called = false;
  9769. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9770. EXPECT_NE(session, nullptr);
  9771. callback_called = true;
  9772. return SSLVerifierResponse::NoDecisionMade;
  9773. });
  9774. auto res = cli.Get("/test");
  9775. ASSERT_TRUE(res);
  9776. EXPECT_EQ(200, res->status);
  9777. EXPECT_TRUE(callback_called);
  9778. }
  9779. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9781. ASSERT_TRUE(svr.is_valid());
  9782. svr.Get("/test", [](const Request &, Response &res) {
  9783. res.set_content("ok", "text/plain");
  9784. });
  9785. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9786. auto se = detail::scope_exit([&] {
  9787. svr.stop();
  9788. t.join();
  9789. });
  9790. svr.wait_until_ready();
  9791. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9792. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9793. // so we only check that the request fails, not whether the callback was
  9794. // called.
  9795. SSLClient cli(HOST, PORT);
  9796. cli.enable_server_certificate_verification(true);
  9797. cli.set_connection_timeout(30);
  9798. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9799. EXPECT_NE(session, nullptr);
  9800. return SSLVerifierResponse::NoDecisionMade;
  9801. });
  9802. auto res = cli.Get("/test");
  9803. EXPECT_FALSE(res);
  9804. }
  9805. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9806. // Test SSL server using PemMemory constructor with client CA certificates
  9807. // Read PEM files
  9808. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9809. read_file(SERVER_CERT_FILE, server_cert_pem);
  9810. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9811. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9812. // Create SSLServer with PemMemory constructor including client CA
  9813. SSLServer::PemMemory server_pem = {
  9814. server_cert_pem.c_str(),
  9815. server_cert_pem.size(),
  9816. server_key_pem.c_str(),
  9817. server_key_pem.size(),
  9818. client_ca_pem.c_str(),
  9819. client_ca_pem.size(),
  9820. nullptr // no password for server key
  9821. };
  9822. SSLServer svr(server_pem);
  9823. ASSERT_TRUE(svr.is_valid());
  9824. // No SSL error should be recorded for valid setup
  9825. EXPECT_EQ(0, svr.ssl_last_error());
  9826. // Set up server endpoints
  9827. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9828. res.set_content("ok", "text/plain");
  9829. });
  9830. // Start server in a thread
  9831. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9832. svr.wait_until_ready();
  9833. // Connect with client certificate (using constructor with paths)
  9834. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9835. cli.enable_server_certificate_verification(false);
  9836. auto res = cli.Get("/test-pem-ca");
  9837. ASSERT_TRUE(res);
  9838. EXPECT_EQ(200, res->status);
  9839. EXPECT_EQ("ok", res->body);
  9840. svr.stop();
  9841. server_thread.join();
  9842. }
  9843. #endif
  9844. #ifdef _WIN32
  9845. TEST(CleanupTest, WSACleanup) {
  9846. int ret = WSACleanup();
  9847. ASSERT_EQ(0, ret);
  9848. }
  9849. #endif
  9850. #ifndef CPPHTTPLIB_SSL_ENABLED
  9851. TEST(NoSSLSupport, SimpleInterface) {
  9852. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9853. }
  9854. #endif
  9855. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9856. TEST(InvalidScheme, SimpleInterface) {
  9857. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9858. }
  9859. #endif
  9860. TEST(NoScheme, SimpleInterface) {
  9861. Client cli("yahoo.com:80");
  9862. ASSERT_TRUE(cli.is_valid());
  9863. }
  9864. TEST(SendAPI, SimpleInterface_Online) {
  9865. Client cli("http://yahoo.com");
  9866. Request req;
  9867. req.method = "GET";
  9868. req.path = "/";
  9869. auto res = cli.send(req);
  9870. ASSERT_TRUE(res);
  9871. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9872. }
  9873. TEST(SendAPI, WithParamsInRequest) {
  9874. Server svr;
  9875. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9876. EXPECT_TRUE(req.has_param("test"));
  9877. EXPECT_EQ("test_value", req.get_param_value("test"));
  9878. });
  9879. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9880. auto se = detail::scope_exit([&] {
  9881. svr.stop();
  9882. t.join();
  9883. ASSERT_FALSE(svr.is_running());
  9884. });
  9885. svr.wait_until_ready();
  9886. Client cli(HOST, PORT);
  9887. {
  9888. Request req;
  9889. req.method = "GET";
  9890. req.path = "/";
  9891. req.params.emplace("test", "test_value");
  9892. auto res = cli.send(req);
  9893. ASSERT_TRUE(res);
  9894. }
  9895. {
  9896. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9897. ASSERT_TRUE(res);
  9898. }
  9899. }
  9900. TEST(ClientImplMethods, GetSocketTest) {
  9901. httplib::Server svr;
  9902. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9903. res.status = StatusCode::OK_200;
  9904. });
  9905. auto port = svr.bind_to_any_port("127.0.0.1");
  9906. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9907. auto se = detail::scope_exit([&] {
  9908. svr.stop();
  9909. thread.join();
  9910. ASSERT_FALSE(svr.is_running());
  9911. });
  9912. svr.wait_until_ready();
  9913. {
  9914. httplib::Client cli("127.0.0.1", port);
  9915. cli.set_keep_alive(true);
  9916. // Use the behavior of cpp-httplib of opening the connection
  9917. // only when the first request happens. If that changes,
  9918. // this test would be obsolete.
  9919. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9920. // This also implicitly tests the server. But other tests would fail much
  9921. // earlier than this one to be considered.
  9922. auto res = cli.Get("/");
  9923. ASSERT_TRUE(res);
  9924. EXPECT_EQ(StatusCode::OK_200, res->status);
  9925. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9926. }
  9927. }
  9928. #ifdef CPPHTTPLIB_SSL_ENABLED
  9929. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9930. Client cli("http://yahoo.com");
  9931. auto res = cli.Get("/");
  9932. ASSERT_TRUE(res);
  9933. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9934. cli.set_follow_location(true);
  9935. res = cli.Get("/");
  9936. ASSERT_TRUE(res);
  9937. EXPECT_EQ(StatusCode::OK_200, res->status);
  9938. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9939. }
  9940. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9941. Client cli("https://yahoo.com");
  9942. auto res = cli.Get("/");
  9943. ASSERT_TRUE(res);
  9944. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9945. cli.set_follow_location(true);
  9946. res = cli.Get("/");
  9947. ASSERT_TRUE(res);
  9948. EXPECT_EQ(StatusCode::OK_200, res->status);
  9949. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9950. }
  9951. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9952. Client cli("https://yahoo.com");
  9953. auto res = cli.Get("/");
  9954. ASSERT_TRUE(res);
  9955. ASSERT_FALSE(!res);
  9956. ASSERT_TRUE(res);
  9957. ASSERT_FALSE(res == nullptr);
  9958. ASSERT_TRUE(res != nullptr);
  9959. EXPECT_EQ(Error::Success, res.error());
  9960. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9961. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9962. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9963. cli.set_follow_location(true);
  9964. res = cli.Get("/");
  9965. ASSERT_TRUE(res);
  9966. EXPECT_EQ(Error::Success, res.error());
  9967. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9968. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9969. EXPECT_EQ(StatusCode::OK_200, res->status);
  9970. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9971. }
  9972. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9973. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9974. Client cli("https://cdnjs.cloudflare.com");
  9975. auto res =
  9976. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9977. ASSERT_TRUE(res);
  9978. EXPECT_EQ(StatusCode::OK_200, res->status);
  9979. EXPECT_EQ(287630U, res->body.size());
  9980. EXPECT_EQ("application/javascript; charset=utf-8",
  9981. res->get_header_value("Content-Type"));
  9982. }
  9983. #endif
  9984. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9985. #undef REDIR_HOST // Silence compiler warning
  9986. #define REDIR_HOST "https://httpbingo.org"
  9987. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9988. Client cli(REDIR_HOST);
  9989. cli.set_follow_location(true);
  9990. auto res =
  9991. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9992. ASSERT_TRUE(res);
  9993. EXPECT_EQ(StatusCode::OK_200, res->status);
  9994. }
  9995. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9996. Client cli(REDIR_HOST);
  9997. cli.set_follow_location(true);
  9998. Params params;
  9999. params.emplace("url", "http://example.com");
  10000. params.emplace("status_code", "302");
  10001. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10002. ASSERT_TRUE(res);
  10003. EXPECT_EQ(StatusCode::OK_200, res->status);
  10004. }
  10005. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10006. Client cli(REDIR_HOST);
  10007. cli.set_follow_location(true);
  10008. Params params;
  10009. params.emplace("url", "http://example.com");
  10010. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10011. ASSERT_TRUE(res);
  10012. EXPECT_EQ(StatusCode::OK_200, res->status);
  10013. }
  10014. TEST(HttpToHttpsRedirectTest, CertFile) {
  10015. auto ssl_port = PORT + 1;
  10016. Server svr;
  10017. ASSERT_TRUE(svr.is_valid());
  10018. svr.Get("/index", [&](const Request &, Response &res) {
  10019. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10020. "/index");
  10021. svr.stop();
  10022. });
  10023. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10024. ASSERT_TRUE(ssl_svr.is_valid());
  10025. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10026. res.set_content("test", "text/plain");
  10027. ssl_svr.stop();
  10028. });
  10029. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10030. thread t2 =
  10031. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10032. auto se = detail::scope_exit([&] {
  10033. t2.join();
  10034. t.join();
  10035. ASSERT_FALSE(svr.is_running());
  10036. });
  10037. svr.wait_until_ready();
  10038. ssl_svr.wait_until_ready();
  10039. Client cli("127.0.0.1", PORT);
  10040. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10041. cli.enable_server_certificate_verification(true);
  10042. cli.set_follow_location(true);
  10043. cli.set_connection_timeout(30);
  10044. auto res = cli.Get("/index");
  10045. ASSERT_TRUE(res);
  10046. ASSERT_EQ(StatusCode::OK_200, res->status);
  10047. }
  10048. TEST(SSLClientRedirectTest, CertFile) {
  10049. auto ssl_port = PORT + 1;
  10050. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10051. ASSERT_TRUE(ssl_svr1.is_valid());
  10052. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10053. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10054. "/index");
  10055. ssl_svr1.stop();
  10056. });
  10057. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10058. ASSERT_TRUE(ssl_svr2.is_valid());
  10059. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10060. res.set_content("test", "text/plain");
  10061. ssl_svr2.stop();
  10062. });
  10063. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10064. thread t2 =
  10065. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10066. auto se = detail::scope_exit([&] {
  10067. t2.join();
  10068. t.join();
  10069. ASSERT_FALSE(ssl_svr1.is_running());
  10070. });
  10071. ssl_svr1.wait_until_ready();
  10072. ssl_svr2.wait_until_ready();
  10073. SSLClient cli("127.0.0.1", PORT);
  10074. std::string cert;
  10075. read_file(SERVER_CERT2_FILE, cert);
  10076. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10077. cli.enable_server_certificate_verification(true);
  10078. cli.set_follow_location(true);
  10079. cli.set_connection_timeout(30);
  10080. auto res = cli.Get("/index");
  10081. ASSERT_TRUE(res);
  10082. ASSERT_EQ(StatusCode::OK_200, res->status);
  10083. }
  10084. #endif
  10085. #ifdef CPPHTTPLIB_SSL_ENABLED
  10086. // Test that set_ca_cert_store() skips system certs (consistent with
  10087. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10088. // should be trusted - system certs should NOT be loaded.
  10089. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10090. // Load a specific cert that is NOT a system CA cert
  10091. std::string cert;
  10092. read_file(SERVER_CERT2_FILE, cert);
  10093. SSLClient cli("google.com");
  10094. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10095. cli.enable_server_certificate_verification(true);
  10096. // This should FAIL because:
  10097. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10098. // 2. System certs should NOT be loaded when custom store is set
  10099. // If system certs WERE loaded, this would succeed
  10100. auto res = cli.Get("/");
  10101. ASSERT_FALSE(res);
  10102. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10103. }
  10104. // Same as above, but through the native store handle path. Regression test:
  10105. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10106. // merged system certs into the user-provided store.
  10107. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10108. std::string cert;
  10109. read_file(SERVER_CERT2_FILE, cert);
  10110. SSLClient cli("google.com");
  10111. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10112. cli.enable_server_certificate_verification(true);
  10113. auto res = cli.Get("/");
  10114. ASSERT_FALSE(res);
  10115. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10116. }
  10117. // A custom store set via the native handle must still verify a server whose
  10118. // cert it does contain.
  10119. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10120. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10121. ASSERT_TRUE(svr.is_valid());
  10122. svr.Get("/test", [&](const Request &, Response &res) {
  10123. res.set_content("test", "text/plain");
  10124. });
  10125. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10126. auto se = detail::scope_exit([&] {
  10127. svr.stop();
  10128. t.join();
  10129. ASSERT_FALSE(svr.is_running());
  10130. });
  10131. svr.wait_until_ready();
  10132. SSLClient cli("127.0.0.1", PORT);
  10133. std::string cert;
  10134. read_file(SERVER_CERT2_FILE, cert);
  10135. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10136. cli.enable_server_certificate_verification(true);
  10137. cli.set_connection_timeout(30);
  10138. auto res = cli.Get("/test");
  10139. ASSERT_TRUE(res);
  10140. ASSERT_EQ(StatusCode::OK_200, res->status);
  10141. }
  10142. // CA certs loaded through the universal Client must be transferred to the
  10143. // client created internally for following an HTTPS redirect. Regression test:
  10144. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10145. // the CA data for redirect transfer.
  10146. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10147. auto ssl_port = PORT + 1;
  10148. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10149. ASSERT_TRUE(ssl_svr1.is_valid());
  10150. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10151. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10152. "/index");
  10153. });
  10154. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10155. ASSERT_TRUE(ssl_svr2.is_valid());
  10156. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10157. res.set_content("test", "text/plain");
  10158. });
  10159. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10160. thread t2 =
  10161. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10162. auto se = detail::scope_exit([&] {
  10163. ssl_svr2.stop();
  10164. ssl_svr1.stop();
  10165. t2.join();
  10166. t.join();
  10167. ASSERT_FALSE(ssl_svr1.is_running());
  10168. });
  10169. ssl_svr1.wait_until_ready();
  10170. ssl_svr2.wait_until_ready();
  10171. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10172. std::string cert;
  10173. read_file(SERVER_CERT2_FILE, cert);
  10174. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10175. cli.enable_server_certificate_verification(true);
  10176. cli.set_follow_location(true);
  10177. cli.set_connection_timeout(30);
  10178. auto res = cli.Get("/index");
  10179. ASSERT_TRUE(res);
  10180. ASSERT_EQ(StatusCode::OK_200, res->status);
  10181. }
  10182. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10183. // so a host signed by a system CA verifies even though a custom CA is set
  10184. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10185. std::string cert;
  10186. read_file(SERVER_CERT2_FILE, cert);
  10187. SSLClient cli("google.com");
  10188. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10189. cli.enable_system_ca(true);
  10190. cli.enable_server_certificate_verification(true);
  10191. auto res = cli.Get("/");
  10192. ASSERT_TRUE(res);
  10193. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10194. }
  10195. // The custom CA remains effective when combined with the system CA
  10196. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10197. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10198. ASSERT_TRUE(svr.is_valid());
  10199. svr.Get("/test", [&](const Request &, Response &res) {
  10200. res.set_content("test", "text/plain");
  10201. });
  10202. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10203. auto se = detail::scope_exit([&] {
  10204. svr.stop();
  10205. t.join();
  10206. ASSERT_FALSE(svr.is_running());
  10207. });
  10208. svr.wait_until_ready();
  10209. SSLClient cli("127.0.0.1", PORT);
  10210. std::string cert;
  10211. read_file(SERVER_CERT2_FILE, cert);
  10212. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10213. cli.enable_system_ca(true);
  10214. cli.enable_server_certificate_verification(true);
  10215. cli.set_connection_timeout(30);
  10216. auto res = cli.Get("/test");
  10217. ASSERT_TRUE(res);
  10218. ASSERT_EQ(StatusCode::OK_200, res->status);
  10219. }
  10220. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10221. // skip chain verification entirely (only the certificate identity was
  10222. // checked), so a server presenting an untrusted certificate with a matching
  10223. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10224. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10225. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10226. ASSERT_TRUE(svr.is_valid());
  10227. svr.Get("/test", [&](const Request &, Response &res) {
  10228. res.set_content("test", "text/plain");
  10229. });
  10230. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10231. auto se = detail::scope_exit([&] {
  10232. svr.stop();
  10233. t.join();
  10234. ASSERT_FALSE(svr.is_running());
  10235. });
  10236. svr.wait_until_ready();
  10237. SSLClient cli("127.0.0.1", PORT);
  10238. std::string cert;
  10239. // A trusted CA that did not sign the server certificate. The server cert
  10240. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10241. // this connection.
  10242. read_file(CLIENT_CA_CERT_FILE, cert);
  10243. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10244. cli.enable_server_certificate_verification(true);
  10245. cli.set_connection_timeout(30);
  10246. auto res = cli.Get("/test");
  10247. ASSERT_FALSE(res);
  10248. }
  10249. // enable_system_ca(false) prevents system CA loading entirely
  10250. TEST(SSLClientTest, DisableSystemCa_Online) {
  10251. SSLClient cli("google.com");
  10252. cli.enable_system_ca(false);
  10253. cli.enable_server_certificate_verification(true);
  10254. auto res = cli.Get("/");
  10255. ASSERT_FALSE(res);
  10256. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10257. // itself when the CA chain is empty
  10258. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10259. res.error() == Error::SSLConnection);
  10260. }
  10261. // The universal Client forwards enable_system_ca()
  10262. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10263. std::string cert;
  10264. read_file(SERVER_CERT2_FILE, cert);
  10265. Client cli("https://google.com");
  10266. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10267. cli.enable_system_ca(true);
  10268. cli.enable_server_certificate_verification(true);
  10269. auto res = cli.Get("/");
  10270. ASSERT_TRUE(res);
  10271. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10272. }
  10273. // The system CA policy must carry over to the client created internally for
  10274. // following a cross-host HTTPS redirect
  10275. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10276. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10277. ASSERT_TRUE(svr.is_valid());
  10278. svr.Get("/index", [&](const Request &, Response &res) {
  10279. res.set_redirect("https://www.google.com/");
  10280. });
  10281. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10282. auto se = detail::scope_exit([&] {
  10283. svr.stop();
  10284. t.join();
  10285. ASSERT_FALSE(svr.is_running());
  10286. });
  10287. svr.wait_until_ready();
  10288. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10289. std::string cert;
  10290. read_file(SERVER_CERT2_FILE, cert);
  10291. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10292. cli.enable_system_ca(true);
  10293. cli.enable_server_certificate_verification(true);
  10294. cli.set_follow_location(true);
  10295. cli.set_connection_timeout(30);
  10296. // Receiving any response proves the redirect client completed the TLS
  10297. // handshake with a system-CA-signed host
  10298. auto res = cli.Get("/index");
  10299. ASSERT_TRUE(res);
  10300. }
  10301. TEST(MultipartFormDataTest, LargeData) {
  10302. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10303. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10304. const ContentReader &content_reader) {
  10305. if (req.is_multipart_form_data()) {
  10306. std::vector<FormData> items;
  10307. content_reader(
  10308. [&](const FormData &file) {
  10309. items.push_back(file);
  10310. return true;
  10311. },
  10312. [&](const char *data, size_t data_length) {
  10313. items.back().content.append(data, data_length);
  10314. return true;
  10315. });
  10316. EXPECT_TRUE(std::string(items[0].name) == "document");
  10317. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10318. EXPECT_TRUE(items[0].filename == "2MB_data");
  10319. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10320. EXPECT_TRUE(items[1].name == "hello");
  10321. EXPECT_TRUE(items[1].content == "world");
  10322. EXPECT_TRUE(items[1].filename == "");
  10323. EXPECT_TRUE(items[1].content_type == "");
  10324. } else {
  10325. std::string body;
  10326. content_reader([&](const char *data, size_t data_length) {
  10327. body.append(data, data_length);
  10328. return true;
  10329. });
  10330. }
  10331. });
  10332. auto port = svr.bind_to_any_port(HOST);
  10333. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10334. auto se = detail::scope_exit([&] {
  10335. svr.stop();
  10336. t.join();
  10337. ASSERT_FALSE(svr.is_running());
  10338. });
  10339. svr.wait_until_ready();
  10340. {
  10341. std::string data(1024 * 1024 * 2, '.');
  10342. std::stringstream buffer;
  10343. buffer << data;
  10344. SSLClient cli(HOST, port);
  10345. cli.enable_server_certificate_verification(false);
  10346. UploadFormDataItems items{
  10347. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10348. {"hello", "world", "", ""},
  10349. };
  10350. auto res = cli.Post("/post", items);
  10351. ASSERT_TRUE(res);
  10352. ASSERT_EQ(StatusCode::OK_200, res->status);
  10353. }
  10354. }
  10355. TEST(MultipartFormDataTest, DataProviderItems) {
  10356. std::random_device seed_gen;
  10357. std::mt19937 random(seed_gen());
  10358. std::string rand1;
  10359. rand1.resize(1000);
  10360. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10361. std::string rand2;
  10362. rand2.resize(3000);
  10363. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10365. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10366. const ContentReader &content_reader) {
  10367. ASSERT_FALSE(req.is_multipart_form_data());
  10368. std::string body;
  10369. content_reader([&](const char *data, size_t data_length) {
  10370. body.append(data, data_length);
  10371. return true;
  10372. });
  10373. EXPECT_EQ(body, "");
  10374. });
  10375. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10376. const ContentReader &content_reader) {
  10377. ASSERT_TRUE(req.is_multipart_form_data());
  10378. std::vector<FormData> items;
  10379. content_reader(
  10380. [&](const FormData &file) {
  10381. items.push_back(file);
  10382. return true;
  10383. },
  10384. [&](const char *data, size_t data_length) {
  10385. items.back().content.append(data, data_length);
  10386. return true;
  10387. });
  10388. ASSERT_TRUE(items.size() == 2);
  10389. EXPECT_EQ(std::string(items[0].name), "name1");
  10390. EXPECT_EQ(items[0].content, "Testing123");
  10391. EXPECT_EQ(items[0].filename, "filename1");
  10392. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10393. EXPECT_EQ(items[1].name, "name2");
  10394. EXPECT_EQ(items[1].content, "Testing456");
  10395. EXPECT_EQ(items[1].filename, "");
  10396. EXPECT_EQ(items[1].content_type, "");
  10397. });
  10398. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10399. const ContentReader &content_reader) {
  10400. ASSERT_TRUE(req.is_multipart_form_data());
  10401. std::vector<FormData> items;
  10402. content_reader(
  10403. [&](const FormData &file) {
  10404. items.push_back(file);
  10405. return true;
  10406. },
  10407. [&](const char *data, size_t data_length) {
  10408. items.back().content.append(data, data_length);
  10409. return true;
  10410. });
  10411. ASSERT_TRUE(items.size() == 2);
  10412. EXPECT_EQ(items[0].name, "name3");
  10413. EXPECT_EQ(items[0].content, rand1);
  10414. EXPECT_EQ(items[0].filename, "filename3");
  10415. EXPECT_EQ(items[0].content_type, "");
  10416. EXPECT_EQ(items[1].name, "name4");
  10417. EXPECT_EQ(items[1].content, rand2);
  10418. EXPECT_EQ(items[1].filename, "filename4");
  10419. EXPECT_EQ(items[1].content_type, "");
  10420. });
  10421. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10422. const ContentReader &content_reader) {
  10423. ASSERT_TRUE(req.is_multipart_form_data());
  10424. std::vector<FormData> items;
  10425. content_reader(
  10426. [&](const FormData &file) {
  10427. items.push_back(file);
  10428. return true;
  10429. },
  10430. [&](const char *data, size_t data_length) {
  10431. items.back().content.append(data, data_length);
  10432. return true;
  10433. });
  10434. ASSERT_TRUE(items.size() == 4);
  10435. EXPECT_EQ(std::string(items[0].name), "name1");
  10436. EXPECT_EQ(items[0].content, "Testing123");
  10437. EXPECT_EQ(items[0].filename, "filename1");
  10438. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10439. EXPECT_EQ(items[1].name, "name2");
  10440. EXPECT_EQ(items[1].content, "Testing456");
  10441. EXPECT_EQ(items[1].filename, "");
  10442. EXPECT_EQ(items[1].content_type, "");
  10443. EXPECT_EQ(items[2].name, "name3");
  10444. EXPECT_EQ(items[2].content, rand1);
  10445. EXPECT_EQ(items[2].filename, "filename3");
  10446. EXPECT_EQ(items[2].content_type, "");
  10447. EXPECT_EQ(items[3].name, "name4");
  10448. EXPECT_EQ(items[3].content, rand2);
  10449. EXPECT_EQ(items[3].filename, "filename4");
  10450. EXPECT_EQ(items[3].content_type, "");
  10451. });
  10452. auto port = svr.bind_to_any_port("localhost");
  10453. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10454. auto se = detail::scope_exit([&] {
  10455. svr.stop();
  10456. t.join();
  10457. ASSERT_FALSE(svr.is_running());
  10458. });
  10459. svr.wait_until_ready();
  10460. {
  10461. SSLClient cli("localhost", port);
  10462. cli.enable_server_certificate_verification(false);
  10463. UploadFormDataItems items{
  10464. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10465. {"name2", "Testing456", "", ""}, // not a file
  10466. };
  10467. {
  10468. auto res = cli.Post("/post-none", {}, {}, {});
  10469. ASSERT_TRUE(res);
  10470. ASSERT_EQ(StatusCode::OK_200, res->status);
  10471. }
  10472. FormDataProviderItems providers;
  10473. {
  10474. auto res =
  10475. cli.Post("/post-items", {}, items, providers); // empty providers
  10476. ASSERT_TRUE(res);
  10477. ASSERT_EQ(StatusCode::OK_200, res->status);
  10478. }
  10479. providers.push_back({"name3",
  10480. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10481. // test the offset is given correctly at each step
  10482. if (!offset)
  10483. sink.os.write(rand1.data(), 30);
  10484. else if (offset == 30)
  10485. sink.os.write(rand1.data() + 30, 300);
  10486. else if (offset == 330)
  10487. sink.os.write(rand1.data() + 330, 670);
  10488. else if (offset == rand1.size())
  10489. sink.done();
  10490. return true;
  10491. },
  10492. "filename3",
  10493. {}});
  10494. providers.push_back({"name4",
  10495. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10496. // test the offset is given correctly at each step
  10497. if (!offset)
  10498. sink.os.write(rand2.data(), 2000);
  10499. else if (offset == 2000)
  10500. sink.os.write(rand2.data() + 2000, 1);
  10501. else if (offset == 2001)
  10502. sink.os.write(rand2.data() + 2001, 999);
  10503. else if (offset == rand2.size())
  10504. sink.done();
  10505. return true;
  10506. },
  10507. "filename4",
  10508. {}});
  10509. {
  10510. auto res = cli.Post("/post-providers", {}, {}, providers);
  10511. ASSERT_TRUE(res);
  10512. ASSERT_EQ(StatusCode::OK_200, res->status);
  10513. }
  10514. {
  10515. auto res = cli.Post("/post-both", {}, items, providers);
  10516. ASSERT_TRUE(res);
  10517. ASSERT_EQ(StatusCode::OK_200, res->status);
  10518. }
  10519. }
  10520. }
  10521. TEST(MultipartFormDataTest, BadHeader) {
  10522. Server svr;
  10523. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10524. res.set_content("ok", "text/plain");
  10525. });
  10526. thread t = thread([&] { svr.listen(HOST, PORT); });
  10527. auto se = detail::scope_exit([&] {
  10528. svr.stop();
  10529. t.join();
  10530. ASSERT_FALSE(svr.is_running());
  10531. });
  10532. svr.wait_until_ready();
  10533. const std::string body =
  10534. "This is the preamble. It is to be ignored, though it\r\n"
  10535. "is a handy place for composition agents to include an\r\n"
  10536. "explanatory note to non-MIME conformant readers.\r\n"
  10537. "\r\n"
  10538. "\r\n"
  10539. "--simple boundary\r\n"
  10540. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10541. ": BAD...\r\n"
  10542. "\r\n"
  10543. "value1\r\n"
  10544. "--simple boundary\r\n"
  10545. "Content-Disposition: form-data; name=\"field2\"; "
  10546. "filename=\"example.txt\"\r\n"
  10547. "\r\n"
  10548. "value2\r\n"
  10549. "--simple boundary--\r\n"
  10550. "This is the epilogue. It is also to be ignored.\r\n";
  10551. std::string content_type =
  10552. R"(multipart/form-data; boundary="simple boundary")";
  10553. Client cli(HOST, PORT);
  10554. auto res = cli.Post("/post", body, content_type.c_str());
  10555. ASSERT_TRUE(res);
  10556. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10557. }
  10558. TEST(MultipartFormDataTest, WithPreamble) {
  10559. Server svr;
  10560. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10561. res.set_content("ok", "text/plain");
  10562. });
  10563. thread t = thread([&] { svr.listen(HOST, PORT); });
  10564. auto se = detail::scope_exit([&] {
  10565. svr.stop();
  10566. t.join();
  10567. ASSERT_FALSE(svr.is_running());
  10568. });
  10569. svr.wait_until_ready();
  10570. const std::string body =
  10571. "This is the preamble. It is to be ignored, though it\r\n"
  10572. "is a handy place for composition agents to include an\r\n"
  10573. "explanatory note to non-MIME conformant readers.\r\n"
  10574. "\r\n"
  10575. "\r\n"
  10576. "--simple boundary\r\n"
  10577. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10578. "\r\n"
  10579. "value1\r\n"
  10580. "--simple boundary\r\n"
  10581. "Content-Disposition: form-data; name=\"field2\"; "
  10582. "filename=\"example.txt\"\r\n"
  10583. "\r\n"
  10584. "value2\r\n"
  10585. "--simple boundary--\r\n"
  10586. "This is the epilogue. It is also to be ignored.\r\n";
  10587. std::string content_type =
  10588. R"(multipart/form-data; boundary="simple boundary")";
  10589. Client cli(HOST, PORT);
  10590. auto res = cli.Post("/post", body, content_type.c_str());
  10591. ASSERT_TRUE(res);
  10592. EXPECT_EQ(StatusCode::OK_200, res->status);
  10593. }
  10594. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10596. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10597. const ContentReader &content_reader) {
  10598. if (req.is_multipart_form_data()) {
  10599. std::vector<FormData> items;
  10600. content_reader(
  10601. [&](const FormData &file) {
  10602. items.push_back(file);
  10603. return true;
  10604. },
  10605. [&](const char *data, size_t data_length) {
  10606. items.back().content.append(data, data_length);
  10607. return true;
  10608. });
  10609. EXPECT_TRUE(std::string(items[0].name) == "document");
  10610. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10611. EXPECT_TRUE(items[0].filename == "2MB_data");
  10612. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10613. EXPECT_TRUE(items[1].name == "hello");
  10614. EXPECT_TRUE(items[1].content == "world");
  10615. EXPECT_TRUE(items[1].filename == "");
  10616. EXPECT_TRUE(items[1].content_type == "");
  10617. } else {
  10618. std::string body;
  10619. content_reader([&](const char *data, size_t data_length) {
  10620. body.append(data, data_length);
  10621. return true;
  10622. });
  10623. }
  10624. });
  10625. auto port = svr.bind_to_any_port("localhost");
  10626. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10627. auto se = detail::scope_exit([&] {
  10628. svr.stop();
  10629. t.join();
  10630. ASSERT_FALSE(svr.is_running());
  10631. });
  10632. svr.wait_until_ready();
  10633. {
  10634. std::string data(1024 * 1024 * 2, '.');
  10635. std::stringstream buffer;
  10636. buffer << data;
  10637. SSLClient cli("localhost", port);
  10638. cli.enable_server_certificate_verification(false);
  10639. UploadFormDataItems items{
  10640. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10641. {"hello", "world", "", ""},
  10642. };
  10643. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10644. ASSERT_TRUE(res);
  10645. ASSERT_EQ(StatusCode::OK_200, res->status);
  10646. }
  10647. }
  10648. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10649. std::string data(1024 * 1024 * 2, '&');
  10650. std::stringstream buffer;
  10651. buffer << data;
  10652. Client cli("https://localhost:8080");
  10653. UploadFormDataItems items{
  10654. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10655. {"hello", "world", "", ""},
  10656. };
  10657. for (const char &c : " \t\r\n") {
  10658. auto res =
  10659. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10660. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10661. ASSERT_FALSE(res);
  10662. }
  10663. }
  10664. TEST(MultipartFormDataTest, PutFormData) {
  10665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10666. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10667. const ContentReader &content_reader) {
  10668. if (req.is_multipart_form_data()) {
  10669. std::vector<FormData> items;
  10670. content_reader(
  10671. [&](const FormData &file) {
  10672. items.push_back(file);
  10673. return true;
  10674. },
  10675. [&](const char *data, size_t data_length) {
  10676. items.back().content.append(data, data_length);
  10677. return true;
  10678. });
  10679. EXPECT_TRUE(std::string(items[0].name) == "document");
  10680. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10681. EXPECT_TRUE(items[0].filename == "2MB_data");
  10682. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10683. EXPECT_TRUE(items[1].name == "hello");
  10684. EXPECT_TRUE(items[1].content == "world");
  10685. EXPECT_TRUE(items[1].filename == "");
  10686. EXPECT_TRUE(items[1].content_type == "");
  10687. } else {
  10688. std::string body;
  10689. content_reader([&](const char *data, size_t data_length) {
  10690. body.append(data, data_length);
  10691. return true;
  10692. });
  10693. }
  10694. });
  10695. auto port = svr.bind_to_any_port("localhost");
  10696. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10697. auto se = detail::scope_exit([&] {
  10698. svr.stop();
  10699. t.join();
  10700. ASSERT_FALSE(svr.is_running());
  10701. });
  10702. svr.wait_until_ready();
  10703. {
  10704. std::string data(1024 * 1024 * 2, '&');
  10705. std::stringstream buffer;
  10706. buffer << data;
  10707. SSLClient cli("localhost", port);
  10708. cli.enable_server_certificate_verification(false);
  10709. UploadFormDataItems items{
  10710. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10711. {"hello", "world", "", ""},
  10712. };
  10713. auto res = cli.Put("/put", items);
  10714. ASSERT_TRUE(res);
  10715. ASSERT_EQ(StatusCode::OK_200, res->status);
  10716. }
  10717. }
  10718. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10720. svr.Put("/put_customboundary",
  10721. [&](const Request &req, const Response & /*res*/,
  10722. const ContentReader &content_reader) {
  10723. if (req.is_multipart_form_data()) {
  10724. std::vector<FormData> items;
  10725. content_reader(
  10726. [&](const FormData &file) {
  10727. items.push_back(file);
  10728. return true;
  10729. },
  10730. [&](const char *data, size_t data_length) {
  10731. items.back().content.append(data, data_length);
  10732. return true;
  10733. });
  10734. EXPECT_TRUE(std::string(items[0].name) == "document");
  10735. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10736. EXPECT_TRUE(items[0].filename == "2MB_data");
  10737. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10738. EXPECT_TRUE(items[1].name == "hello");
  10739. EXPECT_TRUE(items[1].content == "world");
  10740. EXPECT_TRUE(items[1].filename == "");
  10741. EXPECT_TRUE(items[1].content_type == "");
  10742. } else {
  10743. std::string body;
  10744. content_reader([&](const char *data, size_t data_length) {
  10745. body.append(data, data_length);
  10746. return true;
  10747. });
  10748. }
  10749. });
  10750. auto port = svr.bind_to_any_port("localhost");
  10751. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10752. auto se = detail::scope_exit([&] {
  10753. svr.stop();
  10754. t.join();
  10755. ASSERT_FALSE(svr.is_running());
  10756. });
  10757. svr.wait_until_ready();
  10758. {
  10759. std::string data(1024 * 1024 * 2, '&');
  10760. std::stringstream buffer;
  10761. buffer << data;
  10762. SSLClient cli("localhost", port);
  10763. cli.enable_server_certificate_verification(false);
  10764. UploadFormDataItems items{
  10765. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10766. {"hello", "world", "", ""},
  10767. };
  10768. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10769. ASSERT_TRUE(res);
  10770. ASSERT_EQ(StatusCode::OK_200, res->status);
  10771. }
  10772. }
  10773. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10774. std::string data(1024 * 1024 * 2, '&');
  10775. std::stringstream buffer;
  10776. buffer << data;
  10777. Client cli("https://localhost:8080");
  10778. cli.enable_server_certificate_verification(false);
  10779. UploadFormDataItems items{
  10780. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10781. {"hello", "world", "", ""},
  10782. };
  10783. for (const char &c : " \t\r\n") {
  10784. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10785. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10786. ASSERT_FALSE(res);
  10787. }
  10788. }
  10789. TEST(MultipartFormDataTest, AlternateFilename) {
  10790. auto handled = false;
  10791. Server svr;
  10792. svr.Post("/test", [&](const Request &req, Response &res) {
  10793. ASSERT_EQ(2u, req.form.files.size());
  10794. ASSERT_EQ(1u, req.form.fields.size());
  10795. // Test files
  10796. const auto &file1 = req.form.get_file("file1");
  10797. ASSERT_EQ("file1", file1.name);
  10798. ASSERT_EQ("A.txt", file1.filename);
  10799. ASSERT_EQ("text/plain", file1.content_type);
  10800. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10801. const auto &file2 = req.form.get_file("file2");
  10802. ASSERT_EQ("file2", file2.name);
  10803. ASSERT_EQ("a.html", file2.filename);
  10804. ASSERT_EQ("text/html", file2.content_type);
  10805. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10806. file2.content);
  10807. // Test text field
  10808. const auto &text = req.form.get_field("text");
  10809. ASSERT_EQ("text default", text);
  10810. res.set_content("ok", "text/plain");
  10811. handled = true;
  10812. });
  10813. thread t = thread([&] { svr.listen(HOST, PORT); });
  10814. auto se = detail::scope_exit([&] {
  10815. svr.stop();
  10816. t.join();
  10817. ASSERT_FALSE(svr.is_running());
  10818. ASSERT_TRUE(handled);
  10819. });
  10820. svr.wait_until_ready();
  10821. auto req = "POST /test HTTP/1.1\r\n"
  10822. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10823. "Content-Length: 399\r\n"
  10824. "\r\n"
  10825. "----------\r\n"
  10826. "Content-Disposition: form-data; name=\"text\"\r\n"
  10827. "\r\n"
  10828. "text default\r\n"
  10829. "----------\r\n"
  10830. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10831. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10832. "Content-Type: text/plain\r\n"
  10833. "\r\n"
  10834. "Content of a.txt.\r\n"
  10835. "\r\n"
  10836. "----------\r\n"
  10837. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10838. "\"a.html\"\r\n"
  10839. "Content-Type: text/html\r\n"
  10840. "\r\n"
  10841. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10842. "\r\n"
  10843. "------------\r\n";
  10844. ASSERT_TRUE(send_request(1, req));
  10845. }
  10846. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10847. auto handled = false;
  10848. Server svr;
  10849. svr.Post("/test", [&](const Request &req, Response &res) {
  10850. // Case-insensitive "utf-8''" prefix with a long value
  10851. const auto &file = req.form.get_file("file1");
  10852. ASSERT_EQ("file1", file.name);
  10853. // 8000 chars exercises both the Content-Disposition parser and the
  10854. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10855. // Prior to the fix, std::regex_match on this header would cause O(N)
  10856. // stack recursion in libstdc++, leading to SIGSEGV.
  10857. std::string expected_filename(8000, 'A');
  10858. ASSERT_EQ(expected_filename, file.filename);
  10859. res.set_content("ok", "text/plain");
  10860. handled = true;
  10861. });
  10862. thread t = thread([&] { svr.listen(HOST, PORT); });
  10863. auto se = detail::scope_exit([&] {
  10864. svr.stop();
  10865. t.join();
  10866. ASSERT_FALSE(svr.is_running());
  10867. ASSERT_TRUE(handled);
  10868. });
  10869. svr.wait_until_ready();
  10870. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10871. // Regression test for GHSA-qq6v-r583-3h69
  10872. std::string long_filename(8000, 'A');
  10873. std::string body = "----------\r\n"
  10874. "Content-Disposition: form-data; name=\"file1\"; "
  10875. "filename*=\"Utf-8''" +
  10876. long_filename +
  10877. "\"\r\n"
  10878. "\r\n"
  10879. "hello\r\n"
  10880. "------------\r\n";
  10881. auto req = "POST /test HTTP/1.1\r\n"
  10882. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10883. "Content-Length: " +
  10884. std::to_string(body.size()) + "\r\n\r\n" + body;
  10885. ASSERT_TRUE(send_request(1, req));
  10886. }
  10887. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10888. auto handled = false;
  10889. Server svr;
  10890. svr.Post("/test", [&](const Request &req, Response &) {
  10891. ASSERT_EQ(2u, req.form.fields.size());
  10892. const auto &text1 = req.form.get_field("text1");
  10893. ASSERT_EQ("text1", text1);
  10894. const auto &text2 = req.form.get_field("text2");
  10895. ASSERT_EQ("text2", text2);
  10896. handled = true;
  10897. });
  10898. thread t = thread([&] { svr.listen(HOST, PORT); });
  10899. auto se = detail::scope_exit([&] {
  10900. svr.stop();
  10901. t.join();
  10902. ASSERT_FALSE(svr.is_running());
  10903. ASSERT_TRUE(handled);
  10904. });
  10905. svr.wait_until_ready();
  10906. auto req = "POST /test HTTP/1.1\r\n"
  10907. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10908. "Content-Length: 146\r\n"
  10909. "\r\n----------\r\n"
  10910. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10911. "\r\n"
  10912. "text1"
  10913. "\r\n----------\r\n"
  10914. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10915. "\r\n"
  10916. "text2"
  10917. "\r\n------------";
  10918. std::string response;
  10919. ASSERT_TRUE(send_request(1, req, &response));
  10920. ASSERT_EQ("200", response.substr(9, 3));
  10921. }
  10922. TEST(MultipartFormDataTest, ContentLength) {
  10923. auto handled = false;
  10924. Server svr;
  10925. svr.Post("/test", [&](const Request &req, Response &) {
  10926. ASSERT_EQ(2u, req.form.fields.size());
  10927. const auto &text1 = req.form.get_field("text1");
  10928. ASSERT_EQ("text1", text1);
  10929. const auto &text2 = req.form.get_field("text2");
  10930. ASSERT_EQ("text2", text2);
  10931. handled = true;
  10932. });
  10933. thread t = thread([&] { svr.listen(HOST, PORT); });
  10934. auto se = detail::scope_exit([&] {
  10935. svr.stop();
  10936. t.join();
  10937. ASSERT_FALSE(svr.is_running());
  10938. ASSERT_TRUE(handled);
  10939. });
  10940. svr.wait_until_ready();
  10941. auto req = "POST /test HTTP/1.1\r\n"
  10942. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10943. "Content-Length: 167\r\n"
  10944. "\r\n----------\r\n"
  10945. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10946. "Content-Length: 5\r\n"
  10947. "\r\n"
  10948. "text1"
  10949. "\r\n----------\r\n"
  10950. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10951. "\r\n"
  10952. "text2"
  10953. "\r\n------------\r\n";
  10954. std::string response;
  10955. ASSERT_TRUE(send_request(1, req, &response));
  10956. ASSERT_EQ("200", response.substr(9, 3));
  10957. }
  10958. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10959. auto handled = false;
  10960. Server svr;
  10961. svr.Post("/test", [&](const Request &req, Response &) {
  10962. ASSERT_EQ(2u, req.form.fields.size());
  10963. const auto &text1 = req.form.get_field("text1");
  10964. ASSERT_EQ("text1", text1);
  10965. // TODO: Add header access for text fields if needed
  10966. const auto &text2 = req.form.get_field("text2");
  10967. ASSERT_EQ("text2", text2);
  10968. // TODO: Header access for text fields needs to be implemented
  10969. // auto &headers = it->second.headers;
  10970. // ASSERT_EQ(3U, headers.size());
  10971. // auto custom_header = headers.find("x-whatever");
  10972. // ASSERT_TRUE(custom_header != headers.end());
  10973. // ASSERT_NE("customvalue", custom_header->second);
  10974. // ASSERT_EQ("CustomValue", custom_header->second);
  10975. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10976. handled = true;
  10977. });
  10978. thread t = thread([&] { svr.listen(HOST, PORT); });
  10979. auto se = detail::scope_exit([&] {
  10980. svr.stop();
  10981. t.join();
  10982. ASSERT_FALSE(svr.is_running());
  10983. ASSERT_TRUE(handled);
  10984. });
  10985. svr.wait_until_ready();
  10986. auto req = "POST /test HTTP/1.1\r\n"
  10987. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10988. "Content-Length: 232\r\n"
  10989. "\r\n----------\r\n"
  10990. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10991. "Content-Length: 5\r\n"
  10992. "X-Test: 1\r\n"
  10993. "\r\n"
  10994. "text1"
  10995. "\r\n----------\r\n"
  10996. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10997. "Content-Type: text/plain\r\n"
  10998. "X-Whatever: CustomValue\r\n"
  10999. "\r\n"
  11000. "text2"
  11001. "\r\n------------\r\n"
  11002. "That should be disregarded. Not even read";
  11003. std::string response;
  11004. ASSERT_TRUE(send_request(1, req, &response));
  11005. ASSERT_EQ("200", response.substr(9, 3));
  11006. }
  11007. TEST(MultipartFormDataTest, LargeHeader) {
  11008. auto handled = false;
  11009. Server svr;
  11010. svr.Post("/test", [&](const Request &req, Response &) {
  11011. ASSERT_EQ(1u, req.form.fields.size());
  11012. const auto &text = req.form.get_field("name1");
  11013. ASSERT_EQ("text1", text);
  11014. handled = true;
  11015. });
  11016. thread t = thread([&] { svr.listen(HOST, PORT); });
  11017. auto se = detail::scope_exit([&] {
  11018. svr.stop();
  11019. t.join();
  11020. ASSERT_FALSE(svr.is_running());
  11021. ASSERT_TRUE(handled);
  11022. });
  11023. svr.wait_until_ready();
  11024. auto boundary = std::string("cpp-httplib-multipart-data");
  11025. std::string content = "--" + boundary +
  11026. "\r\n"
  11027. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11028. "\r\n"
  11029. "text1\r\n"
  11030. "--" +
  11031. boundary + "--\r\n";
  11032. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11033. "Content-Type: multipart/form-data;boundary=" +
  11034. boundary +
  11035. "\r\n"
  11036. "Content-Length: " +
  11037. std::to_string(content.size()) +
  11038. "\r\n"
  11039. "Dummy-Header: ";
  11040. std::string header_suffix = "\r\n"
  11041. "\r\n";
  11042. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11043. size_t header_dummy_size =
  11044. read_buff_size -
  11045. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11046. auto header_dummy = std::string(header_dummy_size, '@');
  11047. auto req = header_prefix + header_dummy + header_suffix + content;
  11048. std::string response;
  11049. ASSERT_TRUE(send_request(1, req, &response));
  11050. ASSERT_EQ("200", response.substr(9, 3));
  11051. }
  11052. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11053. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11054. // (not chunked Transfer-Encoding) after the streaming refactor.
  11055. auto handled = false;
  11056. Server svr;
  11057. svr.Post("/upload", [&](const Request &req, Response &res) {
  11058. auto cl_it = req.headers.find("Content-Length");
  11059. EXPECT_TRUE(cl_it != req.headers.end());
  11060. auto te_it = req.headers.find("Transfer-Encoding");
  11061. EXPECT_TRUE(te_it == req.headers.end());
  11062. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11063. res.set_content("ok", "text/plain");
  11064. handled = true;
  11065. });
  11066. auto port = svr.bind_to_any_port(HOST);
  11067. auto t = thread([&] { svr.listen_after_bind(); });
  11068. auto se = detail::scope_exit([&] {
  11069. svr.stop();
  11070. t.join();
  11071. ASSERT_FALSE(svr.is_running());
  11072. ASSERT_TRUE(handled);
  11073. });
  11074. svr.wait_until_ready();
  11075. UploadFormDataItems items = {
  11076. {"field1", "hello", "", "text/plain"},
  11077. {"file1", "world", "test.txt", "application/octet-stream"},
  11078. };
  11079. Client cli(HOST, port);
  11080. auto res = cli.Post("/upload", {}, items);
  11081. ASSERT_TRUE(res);
  11082. EXPECT_EQ(StatusCode::OK_200, res->status);
  11083. }
  11084. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11085. // Verify that make_multipart_content_provider coalesces many small segments
  11086. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11087. constexpr size_t kItemCount = 1000;
  11088. UploadFormDataItems items;
  11089. items.reserve(kItemCount);
  11090. for (size_t i = 0; i < kItemCount; i++) {
  11091. items.push_back(
  11092. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11093. }
  11094. const std::string boundary = "----test-boundary";
  11095. auto content_length = detail::get_multipart_content_length(items, boundary);
  11096. auto provider = detail::make_multipart_content_provider(items, boundary);
  11097. // Drive the provider the same way write_content_with_progress does
  11098. size_t write_count = 0;
  11099. size_t total_bytes = 0;
  11100. DataSink sink;
  11101. size_t offset = 0;
  11102. sink.write = [&](const char *d, size_t l) -> bool {
  11103. (void)d;
  11104. write_count++;
  11105. total_bytes += l;
  11106. offset += l;
  11107. return true;
  11108. };
  11109. sink.is_writable = []() -> bool { return true; };
  11110. while (offset < content_length) {
  11111. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11112. }
  11113. EXPECT_EQ(content_length, total_bytes);
  11114. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11115. // With buffering into 64KB blocks, write_count should be much smaller.
  11116. auto segment_count = 3 * kItemCount + 1;
  11117. EXPECT_LT(write_count, segment_count / 10);
  11118. }
  11119. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11120. // Integration test: send many UploadFormDataItems and verify the server
  11121. // receives all of them correctly (#2410).
  11122. constexpr size_t kItemCount = 500;
  11123. auto handled = false;
  11124. Server svr;
  11125. svr.Post("/upload", [&](const Request &req, Response &res) {
  11126. EXPECT_EQ(kItemCount, req.form.fields.size());
  11127. for (size_t i = 0; i < kItemCount; i++) {
  11128. auto key = "field" + std::to_string(i);
  11129. auto val = "value" + std::to_string(i);
  11130. auto it = req.form.fields.find(key);
  11131. if (it != req.form.fields.end()) {
  11132. EXPECT_EQ(val, it->second.content);
  11133. } else {
  11134. ADD_FAILURE() << "Missing field: " << key;
  11135. }
  11136. }
  11137. res.set_content("ok", "text/plain");
  11138. handled = true;
  11139. });
  11140. auto port = svr.bind_to_any_port(HOST);
  11141. auto t = thread([&] { svr.listen_after_bind(); });
  11142. auto se = detail::scope_exit([&] {
  11143. svr.stop();
  11144. t.join();
  11145. ASSERT_FALSE(svr.is_running());
  11146. ASSERT_TRUE(handled);
  11147. });
  11148. svr.wait_until_ready();
  11149. UploadFormDataItems items;
  11150. items.reserve(kItemCount);
  11151. for (size_t i = 0; i < kItemCount; i++) {
  11152. items.push_back(
  11153. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11154. }
  11155. Client cli(HOST, port);
  11156. auto res = cli.Post("/upload", items);
  11157. ASSERT_TRUE(res);
  11158. EXPECT_EQ(StatusCode::OK_200, res->status);
  11159. }
  11160. TEST(MultipartFormDataTest, MakeFileProvider) {
  11161. // Verify make_file_provider sends a file's contents correctly.
  11162. const std::string file_content(4096, 'Z');
  11163. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11164. {
  11165. std::ofstream ofs(tmp_path, std::ios::binary);
  11166. ofs.write(file_content.data(),
  11167. static_cast<std::streamsize>(file_content.size()));
  11168. }
  11169. auto handled = false;
  11170. Server svr;
  11171. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11172. const ContentReader &content_reader) {
  11173. ASSERT_TRUE(req.is_multipart_form_data());
  11174. std::vector<FormData> items;
  11175. content_reader(
  11176. [&](const FormData &file) {
  11177. items.push_back(file);
  11178. return true;
  11179. },
  11180. [&](const char *data, size_t data_length) {
  11181. items.back().content.append(data, data_length);
  11182. return true;
  11183. });
  11184. ASSERT_EQ(1u, items.size());
  11185. EXPECT_EQ("myfile", items[0].name);
  11186. EXPECT_EQ("data.bin", items[0].filename);
  11187. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11188. EXPECT_EQ(file_content, items[0].content);
  11189. handled = true;
  11190. });
  11191. auto port = svr.bind_to_any_port(HOST);
  11192. auto t = thread([&] { svr.listen_after_bind(); });
  11193. auto se = detail::scope_exit([&] {
  11194. svr.stop();
  11195. t.join();
  11196. ASSERT_FALSE(svr.is_running());
  11197. ASSERT_TRUE(handled);
  11198. std::remove(tmp_path.c_str());
  11199. });
  11200. svr.wait_until_ready();
  11201. FormDataProviderItems providers;
  11202. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11203. "application/octet-stream"));
  11204. Client cli(HOST, port);
  11205. auto res = cli.Post("/upload", {}, {}, providers);
  11206. ASSERT_TRUE(res);
  11207. EXPECT_EQ(StatusCode::OK_200, res->status);
  11208. }
  11209. TEST(MakeFileBodyTest, Basic) {
  11210. const std::string file_content(4096, 'Z');
  11211. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11212. {
  11213. std::ofstream ofs(tmp_path, std::ios::binary);
  11214. ofs.write(file_content.data(),
  11215. static_cast<std::streamsize>(file_content.size()));
  11216. }
  11217. auto handled = false;
  11218. Server svr;
  11219. svr.Post("/upload", [&](const Request &req, Response &res) {
  11220. EXPECT_EQ(file_content, req.body);
  11221. handled = true;
  11222. res.status = StatusCode::OK_200;
  11223. });
  11224. auto port = svr.bind_to_any_port(HOST);
  11225. auto t = thread([&] { svr.listen_after_bind(); });
  11226. auto se = detail::scope_exit([&] {
  11227. svr.stop();
  11228. t.join();
  11229. ASSERT_FALSE(svr.is_running());
  11230. ASSERT_TRUE(handled);
  11231. std::remove(tmp_path.c_str());
  11232. });
  11233. svr.wait_until_ready();
  11234. auto fb = make_file_body(tmp_path);
  11235. ASSERT_GT(fb.first, 0u);
  11236. Client cli(HOST, port);
  11237. auto res =
  11238. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11239. ASSERT_TRUE(res);
  11240. EXPECT_EQ(StatusCode::OK_200, res->status);
  11241. }
  11242. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11243. static constexpr unsigned int number_of_tasks{1000000};
  11244. std::atomic_uint count{0};
  11245. std::unique_ptr<TaskQueue> task_queue{
  11246. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11247. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11248. auto queued = task_queue->enqueue(
  11249. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11250. EXPECT_TRUE(queued);
  11251. }
  11252. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11253. task_queue->shutdown();
  11254. #else
  11255. EXPECT_NO_THROW(task_queue->shutdown());
  11256. #endif
  11257. EXPECT_EQ(number_of_tasks, count.load());
  11258. }
  11259. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11260. static constexpr unsigned int number_of_tasks{1000000};
  11261. static constexpr unsigned int qlimit{2};
  11262. unsigned int queued_count{0};
  11263. std::atomic_uint count{0};
  11264. std::unique_ptr<TaskQueue> task_queue{
  11265. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11266. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11267. if (task_queue->enqueue(
  11268. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11269. queued_count++;
  11270. }
  11271. }
  11272. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11273. task_queue->shutdown();
  11274. #else
  11275. EXPECT_NO_THROW(task_queue->shutdown());
  11276. #endif
  11277. EXPECT_EQ(queued_count, count.load());
  11278. EXPECT_TRUE(queued_count <= number_of_tasks);
  11279. EXPECT_TRUE(queued_count >= qlimit);
  11280. }
  11281. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11282. // Use a short idle timeout so a dynamic thread spawns, times out and
  11283. // exits during the test, and the pool keeps working afterwards.
  11284. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11285. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11286. /*idle_timeout_sec=*/1}};
  11287. std::atomic_uint count{0};
  11288. std::condition_variable cv;
  11289. std::mutex mtx;
  11290. bool release = false;
  11291. // Block the base thread so the second task spawns a dynamic thread.
  11292. EXPECT_TRUE(task_queue->enqueue([&] {
  11293. std::unique_lock<std::mutex> lock(mtx);
  11294. while (!release) {
  11295. cv.wait(lock);
  11296. }
  11297. count++;
  11298. }));
  11299. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11300. // Let the dynamic thread finish its task and exceed the idle timeout.
  11301. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11302. {
  11303. std::unique_lock<std::mutex> lock(mtx);
  11304. release = true;
  11305. }
  11306. cv.notify_all();
  11307. // The pool must still accept and run tasks after the dynamic thread exited.
  11308. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11309. task_queue->shutdown();
  11310. EXPECT_EQ(3u, count.load());
  11311. }
  11312. TEST(TaskQueueTest, MaxQueuedRequests) {
  11313. static constexpr unsigned int qlimit{3};
  11314. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11315. std::condition_variable sem_cv;
  11316. std::mutex sem_mtx;
  11317. int credits = 0;
  11318. bool queued;
  11319. /* Fill up the queue with tasks that will block until we give them credits to
  11320. * complete. */
  11321. for (unsigned int n = 0; n <= qlimit;) {
  11322. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11323. std::unique_lock<std::mutex> lock(sem_mtx);
  11324. while (credits <= 0) {
  11325. sem_cv.wait(lock);
  11326. }
  11327. /* Consume the credit and signal the test code if they are all gone. */
  11328. if (--credits == 0) { sem_cv.notify_one(); }
  11329. });
  11330. if (n < qlimit) {
  11331. /* The first qlimit enqueues must succeed. */
  11332. EXPECT_TRUE(queued);
  11333. } else {
  11334. /* The last one will succeed only when the worker thread
  11335. * starts and dequeues the first blocking task. Although
  11336. * not necessary for the correctness of this test, we sleep for
  11337. * a short while to avoid busy waiting. */
  11338. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11339. }
  11340. if (queued) { n++; }
  11341. }
  11342. /* Further enqueues must fail since the queue is full. */
  11343. for (auto i = 0; i < 4; i++) {
  11344. queued = task_queue->enqueue([] {});
  11345. EXPECT_FALSE(queued);
  11346. }
  11347. /* Give the credits to allow the previous tasks to complete. */
  11348. {
  11349. std::unique_lock<std::mutex> lock(sem_mtx);
  11350. credits += qlimit + 1;
  11351. }
  11352. sem_cv.notify_all();
  11353. /* Wait for all the credits to be consumed. */
  11354. {
  11355. std::unique_lock<std::mutex> lock(sem_mtx);
  11356. while (credits > 0) {
  11357. sem_cv.wait(lock);
  11358. }
  11359. }
  11360. /* Check that we are able again to enqueue at least qlimit tasks. */
  11361. for (unsigned int i = 0; i < qlimit; i++) {
  11362. queued = task_queue->enqueue([] {});
  11363. EXPECT_TRUE(queued);
  11364. }
  11365. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11366. task_queue->shutdown();
  11367. #else
  11368. EXPECT_NO_THROW(task_queue->shutdown());
  11369. #endif
  11370. }
  11371. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11372. Server svr;
  11373. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11374. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11375. });
  11376. svr.Get("/hello", [](const Request &req, Response &res) {
  11377. res.set_content(req.get_param_value("key"), "text/plain");
  11378. });
  11379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11380. auto se = detail::scope_exit([&] {
  11381. svr.stop();
  11382. thread.join();
  11383. ASSERT_FALSE(svr.is_running());
  11384. });
  11385. svr.wait_until_ready();
  11386. {
  11387. Client cli(HOST, PORT);
  11388. cli.set_follow_location(true);
  11389. auto res = cli.Get("/");
  11390. ASSERT_TRUE(res);
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. EXPECT_EQ("val&key2=val2", res->body);
  11393. }
  11394. }
  11395. #endif
  11396. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11397. Server svr;
  11398. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11399. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11400. });
  11401. svr.Get("/hello", [](const Request &req, Response &res) {
  11402. res.set_content(req.get_param_value("key"), "text/plain");
  11403. });
  11404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11405. auto se = detail::scope_exit([&] {
  11406. svr.stop();
  11407. thread.join();
  11408. ASSERT_FALSE(svr.is_running());
  11409. });
  11410. svr.wait_until_ready();
  11411. {
  11412. Client cli(HOST, PORT);
  11413. cli.set_follow_location(true);
  11414. auto res = cli.Get("/");
  11415. ASSERT_TRUE(res);
  11416. EXPECT_EQ(StatusCode::OK_200, res->status);
  11417. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11418. }
  11419. }
  11420. TEST(RedirectTest, RedirectWithPlusInPath) {
  11421. Server svr;
  11422. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11423. res.set_redirect("/a+b");
  11424. });
  11425. // Route pattern uses regex; escape + as \\+
  11426. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11427. res.set_content(req.path, "text/plain");
  11428. });
  11429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11430. auto se = detail::scope_exit([&] {
  11431. svr.stop();
  11432. thread.join();
  11433. ASSERT_FALSE(svr.is_running());
  11434. });
  11435. svr.wait_until_ready();
  11436. {
  11437. Client cli(HOST, PORT);
  11438. cli.set_follow_location(true);
  11439. auto res = cli.Get("/");
  11440. ASSERT_TRUE(res);
  11441. EXPECT_EQ(StatusCode::OK_200, res->status);
  11442. EXPECT_EQ("/a+b", res->body);
  11443. }
  11444. }
  11445. #ifdef CPPHTTPLIB_SSL_ENABLED
  11446. TEST(RedirectTest, Issue2185_Online) {
  11447. SSLClient client("github.com");
  11448. client.set_follow_location(true);
  11449. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11450. "Coollab-Windows.zip");
  11451. ASSERT_TRUE(res);
  11452. EXPECT_EQ(StatusCode::OK_200, res->status);
  11453. EXPECT_EQ(9920427U, res->body.size());
  11454. }
  11455. #endif
  11456. TEST(VulnerabilityTest, CRLFInjection) {
  11457. Server svr;
  11458. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11459. res.set_content("Hello 1", "text/plain");
  11460. });
  11461. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11462. res.set_content("Hello 2", "text/plain");
  11463. });
  11464. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11465. res.set_content("Hello 3", "text/plain");
  11466. });
  11467. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11468. res.set_content("Hello 4", "text/plain");
  11469. });
  11470. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11471. for (const auto &x : req.headers) {
  11472. auto key = x.first;
  11473. EXPECT_STRNE("evil", key.c_str());
  11474. }
  11475. });
  11476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11477. auto se = detail::scope_exit([&] {
  11478. svr.stop();
  11479. thread.join();
  11480. ASSERT_FALSE(svr.is_running());
  11481. });
  11482. svr.wait_until_ready();
  11483. {
  11484. Client cli(HOST, PORT);
  11485. cli.Post("/test1", "A=B",
  11486. "application/x-www-form-urlencoded\r\nevil: hello1");
  11487. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11488. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11489. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11490. }
  11491. }
  11492. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11493. auto server_thread = std::thread([] {
  11494. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11495. default_socket_options(srv);
  11496. sockaddr_in addr{};
  11497. addr.sin_family = AF_INET;
  11498. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11499. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11500. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11501. ::listen(srv, 1);
  11502. sockaddr_in cli_addr{};
  11503. socklen_t cli_len = sizeof(cli_addr);
  11504. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11505. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11506. std::string buf_all;
  11507. char buf[2048];
  11508. ssize_t n;
  11509. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11510. buf_all.append(buf, static_cast<size_t>(n));
  11511. size_t pos;
  11512. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11513. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11514. auto e = request_block.find("\r\n");
  11515. if (e != std::string::npos) {
  11516. auto request_line = request_block.substr(0, e);
  11517. std::string msg =
  11518. "CRLF injection detected in request line: '" + request_line + "'";
  11519. EXPECT_FALSE(true) << msg;
  11520. }
  11521. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11522. ::send(cli,
  11523. #ifdef _WIN32
  11524. static_cast<const char *>(resp.c_str()),
  11525. static_cast<int>(resp.size()),
  11526. #else
  11527. resp.c_str(), resp.size(),
  11528. #endif
  11529. 0);
  11530. buf_all.erase(0, pos + 4);
  11531. }
  11532. }
  11533. detail::close_socket(cli);
  11534. detail::close_socket(srv);
  11535. });
  11536. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11537. auto cli = Client("127.0.0.1", PORT + 1);
  11538. auto headers = Headers{
  11539. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11540. {"Connection", "keep-alive"}};
  11541. auto res = cli.Get("/hi", headers);
  11542. EXPECT_FALSE(res);
  11543. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11544. server_thread.join();
  11545. }
  11546. TEST(PathParamsTest, StaticMatch) {
  11547. const auto pattern = "/users/all";
  11548. detail::PathParamsMatcher matcher(pattern);
  11549. Request request;
  11550. request.path = "/users/all";
  11551. ASSERT_TRUE(matcher.match(request));
  11552. std::unordered_map<std::string, std::string> expected_params = {};
  11553. EXPECT_EQ(request.path_params, expected_params);
  11554. }
  11555. TEST(PathParamsTest, StaticMismatch) {
  11556. const auto pattern = "/users/all";
  11557. detail::PathParamsMatcher matcher(pattern);
  11558. Request request;
  11559. request.path = "/users/1";
  11560. ASSERT_FALSE(matcher.match(request));
  11561. }
  11562. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11563. const auto pattern = "/users/:id/subscriptions";
  11564. detail::PathParamsMatcher matcher(pattern);
  11565. Request request;
  11566. request.path = "/users/42/subscriptions";
  11567. ASSERT_TRUE(matcher.match(request));
  11568. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11569. EXPECT_EQ(request.path_params, expected_params);
  11570. }
  11571. TEST(PathParamsTest, SingleParamInTheEnd) {
  11572. const auto pattern = "/users/:id";
  11573. detail::PathParamsMatcher matcher(pattern);
  11574. Request request;
  11575. request.path = "/users/24";
  11576. ASSERT_TRUE(matcher.match(request));
  11577. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11578. EXPECT_EQ(request.path_params, expected_params);
  11579. }
  11580. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11581. const auto pattern = "/users/:id/";
  11582. detail::PathParamsMatcher matcher(pattern);
  11583. Request request;
  11584. request.path = "/users/42/";
  11585. ASSERT_TRUE(matcher.match(request));
  11586. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11587. EXPECT_EQ(request.path_params, expected_params);
  11588. }
  11589. TEST(PathParamsTest, EmptyParam) {
  11590. const auto pattern = "/users/:id/";
  11591. detail::PathParamsMatcher matcher(pattern);
  11592. Request request;
  11593. request.path = "/users//";
  11594. ASSERT_TRUE(matcher.match(request));
  11595. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11596. EXPECT_EQ(request.path_params, expected_params);
  11597. }
  11598. TEST(PathParamsTest, FragmentMismatch) {
  11599. const auto pattern = "/users/:id/";
  11600. detail::PathParamsMatcher matcher(pattern);
  11601. Request request;
  11602. request.path = "/admins/24/";
  11603. ASSERT_FALSE(matcher.match(request));
  11604. }
  11605. TEST(PathParamsTest, ExtraFragments) {
  11606. const auto pattern = "/users/:id";
  11607. detail::PathParamsMatcher matcher(pattern);
  11608. Request request;
  11609. request.path = "/users/42/subscriptions";
  11610. ASSERT_FALSE(matcher.match(request));
  11611. }
  11612. TEST(PathParamsTest, MissingTrailingParam) {
  11613. const auto pattern = "/users/:id";
  11614. detail::PathParamsMatcher matcher(pattern);
  11615. Request request;
  11616. request.path = "/users";
  11617. ASSERT_FALSE(matcher.match(request));
  11618. }
  11619. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11620. const auto pattern = "/users/:id/subscriptions";
  11621. detail::PathParamsMatcher matcher(pattern);
  11622. Request request;
  11623. request.path = "/users/subscriptions";
  11624. ASSERT_FALSE(matcher.match(request));
  11625. }
  11626. TEST(PathParamsTest, MultipleParams) {
  11627. const auto pattern = "/users/:userid/subscriptions/:subid";
  11628. detail::PathParamsMatcher matcher(pattern);
  11629. Request request;
  11630. request.path = "/users/42/subscriptions/2";
  11631. ASSERT_TRUE(matcher.match(request));
  11632. std::unordered_map<std::string, std::string> expected_params = {
  11633. {"userid", "42"}, {"subid", "2"}};
  11634. EXPECT_EQ(request.path_params, expected_params);
  11635. }
  11636. TEST(PathParamsTest, SequenceOfParams) {
  11637. const auto pattern = "/values/:x/:y/:z";
  11638. detail::PathParamsMatcher matcher(pattern);
  11639. Request request;
  11640. request.path = "/values/1/2/3";
  11641. ASSERT_TRUE(matcher.match(request));
  11642. std::unordered_map<std::string, std::string> expected_params = {
  11643. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11644. EXPECT_EQ(request.path_params, expected_params);
  11645. }
  11646. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11647. const auto pattern = "/prefix:suffix";
  11648. detail::PathParamsMatcher matcher(pattern);
  11649. Request request;
  11650. request.path = "/prefix:suffix";
  11651. ASSERT_TRUE(matcher.match(request));
  11652. const std::unordered_map<std::string, std::string> expected_params = {};
  11653. EXPECT_EQ(request.path_params, expected_params);
  11654. }
  11655. TEST(ParseUrlTest, VariousPatterns) {
  11656. {
  11657. detail::UrlComponents uc;
  11658. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11659. EXPECT_EQ("http", uc.scheme);
  11660. EXPECT_EQ("example.com", uc.host);
  11661. EXPECT_EQ("8080", uc.port);
  11662. EXPECT_EQ("/path", uc.path);
  11663. EXPECT_EQ("?q=1", uc.query);
  11664. }
  11665. {
  11666. detail::UrlComponents uc;
  11667. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11668. EXPECT_EQ("https", uc.scheme);
  11669. EXPECT_EQ("example.com", uc.host);
  11670. EXPECT_TRUE(uc.port.empty());
  11671. EXPECT_EQ("/path", uc.path);
  11672. }
  11673. {
  11674. detail::UrlComponents uc;
  11675. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11676. EXPECT_EQ("::1", uc.host);
  11677. EXPECT_EQ("8080", uc.port);
  11678. EXPECT_EQ("/path", uc.path);
  11679. }
  11680. {
  11681. detail::UrlComponents uc;
  11682. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11683. }
  11684. {
  11685. detail::UrlComponents uc;
  11686. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11687. EXPECT_TRUE(uc.scheme.empty());
  11688. EXPECT_EQ("example.com", uc.host);
  11689. EXPECT_EQ("/path", uc.path);
  11690. EXPECT_EQ("?q=1", uc.query);
  11691. }
  11692. {
  11693. detail::UrlComponents uc;
  11694. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11695. EXPECT_TRUE(uc.host.empty());
  11696. EXPECT_EQ("/path", uc.path);
  11697. EXPECT_EQ("?q=1", uc.query);
  11698. }
  11699. {
  11700. detail::UrlComponents uc;
  11701. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11702. EXPECT_EQ("example.com", uc.host);
  11703. EXPECT_EQ("8080", uc.port);
  11704. }
  11705. {
  11706. // Unix socket path — must not be parsed as host
  11707. detail::UrlComponents uc;
  11708. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11709. EXPECT_TRUE(uc.host.empty());
  11710. }
  11711. {
  11712. detail::UrlComponents uc;
  11713. ASSERT_TRUE(detail::parse_url("", uc));
  11714. EXPECT_TRUE(uc.host.empty());
  11715. EXPECT_TRUE(uc.path.empty());
  11716. }
  11717. {
  11718. detail::UrlComponents uc;
  11719. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11720. }
  11721. {
  11722. detail::UrlComponents uc;
  11723. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11724. }
  11725. {
  11726. // Accepted by parse_url; callers restrict to http/https
  11727. detail::UrlComponents uc;
  11728. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11729. EXPECT_EQ("ftp", uc.scheme);
  11730. }
  11731. {
  11732. detail::UrlComponents uc;
  11733. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11734. }
  11735. {
  11736. detail::UrlComponents uc;
  11737. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11738. }
  11739. }
  11740. TEST(ParseUrlTest, FragmentHandling) {
  11741. {
  11742. detail::UrlComponents uc;
  11743. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11744. EXPECT_EQ("/path", uc.path);
  11745. EXPECT_TRUE(uc.query.empty());
  11746. }
  11747. {
  11748. detail::UrlComponents uc;
  11749. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11750. EXPECT_TRUE(uc.path.empty());
  11751. EXPECT_TRUE(uc.query.empty());
  11752. }
  11753. }
  11754. TEST(ParseUrlTest, UserinfoHandling) {
  11755. // Userinfo with @ but no colon — host includes @
  11756. detail::UrlComponents uc;
  11757. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11758. EXPECT_EQ("user@host.com", uc.host);
  11759. EXPECT_EQ("/path", uc.path);
  11760. }
  11761. TEST(ParseUrlTest, IPv6EdgeCases) {
  11762. {
  11763. detail::UrlComponents uc;
  11764. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11765. EXPECT_TRUE(uc.scheme.empty());
  11766. EXPECT_EQ("::1", uc.host);
  11767. EXPECT_EQ("8080", uc.port);
  11768. }
  11769. {
  11770. // Zone ID '%25' is not in [a-fA-F0-9:]
  11771. detail::UrlComponents uc;
  11772. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11773. }
  11774. }
  11775. TEST(ParseUrlTest, SchemeEdgeCases) {
  11776. {
  11777. detail::UrlComponents uc;
  11778. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11779. }
  11780. {
  11781. detail::UrlComponents uc;
  11782. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11783. }
  11784. {
  11785. detail::UrlComponents uc;
  11786. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11787. }
  11788. }
  11789. TEST(ParseUrlTest, PortEdgeCases) {
  11790. {
  11791. detail::UrlComponents uc;
  11792. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11793. EXPECT_TRUE(uc.port.empty());
  11794. EXPECT_EQ("/path", uc.path);
  11795. }
  11796. {
  11797. // parse_url accepts any port string; validation is done by parse_port
  11798. detail::UrlComponents uc;
  11799. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11800. EXPECT_EQ("abc", uc.port);
  11801. }
  11802. }
  11803. TEST(ParseUrlTest, WebSocketPatterns) {
  11804. {
  11805. detail::UrlComponents uc;
  11806. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11807. EXPECT_EQ("ws", uc.scheme);
  11808. EXPECT_EQ("echo.example.com", uc.host);
  11809. EXPECT_EQ("8080", uc.port);
  11810. EXPECT_EQ("/ws", uc.path);
  11811. }
  11812. {
  11813. detail::UrlComponents uc;
  11814. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11815. EXPECT_EQ("wss", uc.scheme);
  11816. EXPECT_EQ("echo.example.com", uc.host);
  11817. EXPECT_TRUE(uc.port.empty());
  11818. EXPECT_EQ("/ws", uc.path);
  11819. }
  11820. }
  11821. TEST(ParseUrlTest, QueryOnly) {
  11822. detail::UrlComponents uc;
  11823. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11824. EXPECT_TRUE(uc.host.empty());
  11825. EXPECT_TRUE(uc.path.empty());
  11826. EXPECT_EQ("?q=1&r=2", uc.query);
  11827. }
  11828. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11829. detail::UrlComponents uc;
  11830. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11831. EXPECT_TRUE(uc.scheme.empty());
  11832. EXPECT_EQ("example.com", uc.host);
  11833. EXPECT_EQ("443", uc.port);
  11834. EXPECT_EQ("/path", uc.path);
  11835. }
  11836. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11837. // If ipv6 regex working, regex match codepath is taken.
  11838. // else port will default to 80 in Client impl
  11839. int clientImplMagicPort = 80;
  11840. int port = 4321;
  11841. // above ports must be different to avoid false negative
  11842. EXPECT_NE(clientImplMagicPort, port);
  11843. std::string ipV6TestURL = "http://[ff06::c3]";
  11844. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11845. CLIENT_PRIVATE_KEY_FILE);
  11846. EXPECT_EQ(cli.port(), port);
  11847. }
  11848. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11849. auto file_path = "./www/dir/index.html";
  11850. auto dir_path = "./www/dir";
  11851. detail::FileStat stat_file(file_path);
  11852. EXPECT_TRUE(stat_file.is_file());
  11853. EXPECT_FALSE(stat_file.is_dir());
  11854. detail::FileStat stat_dir(dir_path);
  11855. EXPECT_FALSE(stat_dir.is_file());
  11856. EXPECT_TRUE(stat_dir.is_dir());
  11857. }
  11858. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11859. // IPv4 with default HTTP port (80)
  11860. EXPECT_EQ("example.com",
  11861. detail::make_host_and_port_string("example.com", 80, false));
  11862. // IPv4 with default HTTPS port (443)
  11863. EXPECT_EQ("example.com",
  11864. detail::make_host_and_port_string("example.com", 443, true));
  11865. // IPv4 with non-default HTTP port
  11866. EXPECT_EQ("example.com:8080",
  11867. detail::make_host_and_port_string("example.com", 8080, false));
  11868. // IPv4 with non-default HTTPS port
  11869. EXPECT_EQ("example.com:8443",
  11870. detail::make_host_and_port_string("example.com", 8443, true));
  11871. // IPv6 with default HTTP port (80)
  11872. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11873. // IPv6 with default HTTPS port (443)
  11874. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11875. // IPv6 with non-default HTTP port
  11876. EXPECT_EQ("[::1]:8080",
  11877. detail::make_host_and_port_string("::1", 8080, false));
  11878. // IPv6 with non-default HTTPS port
  11879. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11880. // IPv6 full address with default port
  11881. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11882. detail::make_host_and_port_string(
  11883. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11884. // IPv6 full address with non-default port
  11885. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11886. detail::make_host_and_port_string(
  11887. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11888. // IPv6 localhost with non-default port
  11889. EXPECT_EQ("[::1]:3000",
  11890. detail::make_host_and_port_string("::1", 3000, false));
  11891. // IPv6 with zone ID (link-local address) with default port
  11892. EXPECT_EQ("[fe80::1%eth0]",
  11893. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11894. // IPv6 with zone ID (link-local address) with non-default port
  11895. EXPECT_EQ("[fe80::1%eth0]:8080",
  11896. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11897. // Edge case: Port 443 with is_ssl=false (should add port)
  11898. EXPECT_EQ("example.com:443",
  11899. detail::make_host_and_port_string("example.com", 443, false));
  11900. // Edge case: Port 80 with is_ssl=true (should add port)
  11901. EXPECT_EQ("example.com:80",
  11902. detail::make_host_and_port_string("example.com", 80, true));
  11903. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11904. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11905. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11906. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11907. // Security fix: Already bracketed IPv6 should not get double brackets
  11908. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11909. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11910. EXPECT_EQ("[::1]:8080",
  11911. detail::make_host_and_port_string("[::1]", 8080, false));
  11912. EXPECT_EQ("[2001:db8::1]:8080",
  11913. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11914. EXPECT_EQ("[fe80::1%eth0]",
  11915. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11916. EXPECT_EQ("[fe80::1%eth0]:8080",
  11917. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11918. // Edge case: Empty host (should return as-is)
  11919. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11920. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11921. // This is a known limitation but shouldn't crash
  11922. EXPECT_EQ("[host:name]",
  11923. detail::make_host_and_port_string("host:name", 80, false));
  11924. // Port number edge cases (no validation, but should not crash)
  11925. EXPECT_EQ("example.com:0",
  11926. detail::make_host_and_port_string("example.com", 0, false));
  11927. EXPECT_EQ("example.com:-1",
  11928. detail::make_host_and_port_string("example.com", -1, false));
  11929. EXPECT_EQ("example.com:65535",
  11930. detail::make_host_and_port_string("example.com", 65535, false));
  11931. EXPECT_EQ("example.com:65536",
  11932. detail::make_host_and_port_string("example.com", 65536, false));
  11933. }
  11934. #ifdef CPPHTTPLIB_SSL_ENABLED
  11935. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11936. httplib::SSLClient cli("roblox.com", 443);
  11937. cli.set_follow_location(true);
  11938. auto res = cli.Get("/");
  11939. ASSERT_TRUE(res);
  11940. EXPECT_EQ(StatusCode::OK_200, res->status);
  11941. }
  11942. #endif
  11943. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11944. Server svr;
  11945. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11946. EXPECT_EQ(res.status, 400);
  11947. });
  11948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11949. auto se = detail::scope_exit([&] {
  11950. svr.stop();
  11951. thread.join();
  11952. ASSERT_FALSE(svr.is_running());
  11953. });
  11954. svr.wait_until_ready();
  11955. Client cli(HOST, PORT);
  11956. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11957. }
  11958. TEST(InvalidHeaderCharsTest, is_field_name) {
  11959. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11960. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11961. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11962. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11963. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11964. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11965. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11966. EXPECT_FALSE(detail::fields::is_field_name(""));
  11967. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11968. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11969. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11970. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11971. }
  11972. TEST(InvalidHeaderCharsTest, is_field_value) {
  11973. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11974. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11975. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11976. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11977. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11978. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11979. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11980. EXPECT_TRUE(detail::fields::is_field_value(""));
  11981. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11982. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11983. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11984. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11985. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11986. }
  11987. TEST(InvalidHeaderCharsTest, OnServer) {
  11988. Server svr;
  11989. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11990. std::string header = "Not Set";
  11991. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11992. res.set_header(header, "value");
  11993. res.set_content("Page Content Page Content", "text/plain");
  11994. });
  11995. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11996. std::string header = "Not Set";
  11997. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11998. res.set_header("X-Test", header);
  11999. res.set_content("Page Content Page Content", "text/plain");
  12000. });
  12001. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12002. auto se = detail::scope_exit([&] {
  12003. svr.stop();
  12004. thread.join();
  12005. ASSERT_FALSE(svr.is_running());
  12006. });
  12007. svr.wait_until_ready();
  12008. Client cli(HOST, PORT);
  12009. {
  12010. auto res = cli.Get(
  12011. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12012. ASSERT_TRUE(res);
  12013. EXPECT_EQ("Page Content Page Content", res->body);
  12014. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12015. }
  12016. {
  12017. auto res = cli.Get(
  12018. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12019. ASSERT_TRUE(res);
  12020. EXPECT_EQ("Page Content Page Content", res->body);
  12021. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12022. }
  12023. }
  12024. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12025. auto handled = false;
  12026. Server svr;
  12027. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12028. thread t = thread([&] { svr.listen(HOST, PORT); });
  12029. auto se = detail::scope_exit([&] {
  12030. svr.stop();
  12031. t.join();
  12032. ASSERT_FALSE(svr.is_running());
  12033. ASSERT_FALSE(handled);
  12034. });
  12035. svr.wait_until_ready();
  12036. auto req = "POST /test HTTP/1.1\r\n"
  12037. "Content-Length: x\r\n"
  12038. "\r\n";
  12039. std::string response;
  12040. ASSERT_TRUE(send_request(1, req, &response));
  12041. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12042. response.substr(0, response.find("\r\n")));
  12043. }
  12044. #ifndef _WIN32
  12045. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12046. static constexpr char reject[] = "Unauthorized";
  12047. static constexpr char accept[] = "Upload accepted";
  12048. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12049. Server svr;
  12050. svr.set_expect_100_continue_handler(
  12051. [](const Request & /*req*/, Response &res) {
  12052. res.status = StatusCode::Unauthorized_401;
  12053. res.set_content(reject, "text/plain");
  12054. return res.status;
  12055. });
  12056. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12057. res.set_content(accept, "text/plain");
  12058. });
  12059. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12060. auto se = detail::scope_exit([&] {
  12061. svr.stop();
  12062. thread.join();
  12063. ASSERT_FALSE(svr.is_running());
  12064. });
  12065. svr.wait_until_ready();
  12066. {
  12067. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12068. curl_easy_init(), &curl_easy_cleanup};
  12069. ASSERT_NE(curl, nullptr);
  12070. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12071. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12072. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12073. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12074. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12075. &curl_slist_free_all};
  12076. ASSERT_NE(list, nullptr);
  12077. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12078. struct read_data {
  12079. size_t read_size;
  12080. size_t total_size;
  12081. } data = {0, total_size};
  12082. using read_callback_t =
  12083. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12084. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12085. void *userdata) -> size_t {
  12086. read_data *d = (read_data *)userdata;
  12087. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12088. std::fill_n(ptr, size * nmemb, 'A');
  12089. d->read_size += size * nmemb;
  12090. return size * nmemb;
  12091. };
  12092. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12093. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12094. std::vector<char> buffer;
  12095. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12096. using write_callback_t =
  12097. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12098. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12099. void *userdata) -> size_t {
  12100. std::vector<char> *buf = (std::vector<char> *)userdata;
  12101. buf->reserve(buf->size() + size * nmemb + 1);
  12102. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12103. return size * nmemb;
  12104. };
  12105. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12106. {
  12107. const auto res = curl_easy_perform(curl.get());
  12108. ASSERT_EQ(res, CURLE_OK);
  12109. }
  12110. {
  12111. auto response_code = long{};
  12112. const auto res =
  12113. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12114. ASSERT_EQ(res, CURLE_OK);
  12115. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12116. }
  12117. {
  12118. auto dl = curl_off_t{};
  12119. const auto res =
  12120. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12121. ASSERT_EQ(res, CURLE_OK);
  12122. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12123. }
  12124. {
  12125. buffer.push_back('\0');
  12126. ASSERT_STRCASEEQ(buffer.data(), reject);
  12127. }
  12128. }
  12129. }
  12130. #endif
  12131. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12132. // Regression test for #2458.
  12133. //
  12134. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12135. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12136. // ticket can make the client socket spuriously readable during the
  12137. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12138. // the client withholds the body and then blocks reading a response that never
  12139. // comes, failing with `Failed to read connection`.
  12140. //
  12141. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12142. // within the timeout. This raw OpenSSL server deliberately never sends
  12143. // `100 Continue`; the client must still deliver the body and receive 200.
  12144. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12145. signal(SIGPIPE, SIG_IGN);
  12146. const auto port = PORT + 4;
  12147. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12148. ASSERT_NE(srv, INVALID_SOCKET);
  12149. int opt = 1;
  12150. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12151. sockaddr_in addr{};
  12152. addr.sin_family = AF_INET;
  12153. addr.sin_port = htons(static_cast<uint16_t>(port));
  12154. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12155. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12156. ASSERT_EQ(0, ::listen(srv, 1));
  12157. std::atomic<size_t> server_body_bytes{0};
  12158. auto server_thread = std::thread([&] {
  12159. sockaddr_in cli_addr{};
  12160. socklen_t cli_len = sizeof(cli_addr);
  12161. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12162. if (cli == INVALID_SOCKET) { return; }
  12163. // Bound the lifetime of the server side so a buggy client (which never
  12164. // sends the body) cannot make this thread block forever on join.
  12165. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12166. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12167. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12168. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12169. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12170. SSL *ssl = SSL_new(ctx);
  12171. SSL_set_fd(ssl, static_cast<int>(cli));
  12172. if (SSL_accept(ssl) > 0) {
  12173. // Read the request headers. Reading here also flushes the TLS 1.3
  12174. // session tickets to the client. Deliberately do NOT send
  12175. // `100 Continue`.
  12176. std::string buf;
  12177. char tmp[1024];
  12178. while (buf.find("\r\n\r\n") == std::string::npos) {
  12179. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12180. if (n <= 0) { break; }
  12181. buf.append(tmp, static_cast<size_t>(n));
  12182. }
  12183. // A correct client sends the body now; count what arrives.
  12184. auto pos = buf.find("\r\n\r\n");
  12185. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12186. while (body < 4096) {
  12187. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12188. if (n <= 0) { break; }
  12189. body += static_cast<size_t>(n);
  12190. }
  12191. server_body_bytes = body;
  12192. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12193. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12194. SSL_shutdown(ssl);
  12195. }
  12196. SSL_free(ssl);
  12197. detail::close_socket(cli);
  12198. SSL_CTX_free(ctx);
  12199. });
  12200. auto se = detail::scope_exit([&] {
  12201. server_thread.join();
  12202. detail::close_socket(srv);
  12203. });
  12204. SSLClient cli("127.0.0.1", port);
  12205. cli.enable_server_certificate_verification(false);
  12206. cli.set_connection_timeout(5, 0);
  12207. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12208. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12209. std::string body(4096, 'A');
  12210. auto res = cli.Put("/api/test", body, "application/json");
  12211. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12212. EXPECT_EQ(StatusCode::OK_200, res->status);
  12213. EXPECT_EQ(body.size(), server_body_bytes.load());
  12214. }
  12215. #endif
  12216. template <typename S, typename C>
  12217. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12218. svr.Get("/stream", [&](const Request &, Response &res) {
  12219. auto data = new std::string("01234567890123456789");
  12220. res.set_content_provider(
  12221. data->size(), "text/plain",
  12222. [&, data](size_t offset, size_t length, DataSink &sink) {
  12223. const size_t DATA_CHUNK_SIZE = 4;
  12224. const auto &d = *data;
  12225. std::this_thread::sleep_for(std::chrono::seconds(1));
  12226. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12227. return true;
  12228. },
  12229. [data](bool success) {
  12230. EXPECT_FALSE(success);
  12231. delete data;
  12232. });
  12233. });
  12234. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12235. auto i = new size_t(0);
  12236. res.set_content_provider(
  12237. "text/plain",
  12238. [i](size_t, DataSink &sink) {
  12239. if (*i < 5) {
  12240. std::this_thread::sleep_for(std::chrono::seconds(1));
  12241. sink.write("abcd", 4);
  12242. (*i)++;
  12243. } else {
  12244. sink.done();
  12245. }
  12246. return true;
  12247. },
  12248. [i](bool success) {
  12249. EXPECT_FALSE(success);
  12250. delete i;
  12251. });
  12252. });
  12253. svr.Get("/chunked", [&](const Request &, Response &res) {
  12254. auto i = new size_t(0);
  12255. res.set_chunked_content_provider(
  12256. "text/plain",
  12257. [i](size_t, DataSink &sink) {
  12258. if (*i < 5) {
  12259. std::this_thread::sleep_for(std::chrono::seconds(1));
  12260. sink.os << "abcd";
  12261. (*i)++;
  12262. } else {
  12263. sink.done();
  12264. }
  12265. return true;
  12266. },
  12267. [i](bool success) {
  12268. EXPECT_FALSE(success);
  12269. delete i;
  12270. });
  12271. });
  12272. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12273. auto se = detail::scope_exit([&] {
  12274. svr.stop();
  12275. listen_thread.join();
  12276. ASSERT_FALSE(svr.is_running());
  12277. });
  12278. svr.wait_until_ready();
  12279. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12280. {
  12281. auto start = std::chrono::steady_clock::now();
  12282. auto res = cli.Get("/stream");
  12283. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12284. std::chrono::steady_clock::now() - start)
  12285. .count();
  12286. ASSERT_FALSE(res);
  12287. EXPECT_EQ(Error::Read, res.error());
  12288. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12289. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12290. }
  12291. {
  12292. auto start = std::chrono::steady_clock::now();
  12293. auto res = cli.Get("/stream_without_length");
  12294. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12295. std::chrono::steady_clock::now() - start)
  12296. .count();
  12297. ASSERT_FALSE(res);
  12298. EXPECT_EQ(Error::Read, res.error());
  12299. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12300. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12301. }
  12302. {
  12303. auto start = std::chrono::steady_clock::now();
  12304. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12305. EXPECT_EQ("abcd", string(data, data_length));
  12306. return true;
  12307. });
  12308. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12309. std::chrono::steady_clock::now() - start)
  12310. .count();
  12311. ASSERT_FALSE(res);
  12312. EXPECT_EQ(Error::Read, res.error());
  12313. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12314. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12315. }
  12316. }
  12317. TEST(MaxTimeoutTest, ContentStream) {
  12318. time_t timeout = 2000;
  12319. time_t threshold = 200;
  12320. Server svr;
  12321. Client cli("localhost", PORT);
  12322. max_timeout_test(svr, cli, timeout, threshold);
  12323. }
  12324. #ifdef CPPHTTPLIB_SSL_ENABLED
  12325. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12326. time_t timeout = 2000;
  12327. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12328. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12329. SSLClient cli("localhost", PORT);
  12330. cli.enable_server_certificate_verification(false);
  12331. max_timeout_test(svr, cli, timeout, threshold);
  12332. }
  12333. #endif
  12334. class EventDispatcher {
  12335. public:
  12336. EventDispatcher() {}
  12337. bool wait_event(DataSink *sink) {
  12338. unique_lock<mutex> lk(m_);
  12339. int id = id_;
  12340. // Wait with timeout to prevent hanging if client disconnects
  12341. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12342. [&] { return cid_ == id; })) {
  12343. return false; // Timeout occurred
  12344. }
  12345. sink->write(message_.data(), message_.size());
  12346. return true;
  12347. }
  12348. void send_event(const string &message) {
  12349. lock_guard<mutex> lk(m_);
  12350. cid_ = id_++;
  12351. message_ = message;
  12352. cv_.notify_all();
  12353. }
  12354. private:
  12355. mutex m_;
  12356. condition_variable cv_;
  12357. atomic_int id_{0};
  12358. atomic_int cid_{-1};
  12359. string message_;
  12360. };
  12361. TEST(ClientInThreadTest, Issue2068) {
  12362. EventDispatcher ed;
  12363. Server svr;
  12364. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12365. res.set_chunked_content_provider("text/event-stream",
  12366. [&](size_t /*offset*/, DataSink &sink) {
  12367. return ed.wait_event(&sink);
  12368. });
  12369. });
  12370. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12371. svr.wait_until_ready();
  12372. thread event_thread([&] {
  12373. int id = 0;
  12374. while (svr.is_running()) {
  12375. this_thread::sleep_for(chrono::milliseconds(500));
  12376. std::stringstream ss;
  12377. ss << "data: " << id << "\n\n";
  12378. ed.send_event(ss.str());
  12379. id++;
  12380. }
  12381. });
  12382. auto se = detail::scope_exit([&] {
  12383. svr.stop();
  12384. listen_thread.join();
  12385. event_thread.join();
  12386. ASSERT_FALSE(svr.is_running());
  12387. });
  12388. {
  12389. auto client = detail::make_unique<Client>(HOST, PORT);
  12390. client->set_read_timeout(std::chrono::minutes(10));
  12391. std::atomic<bool> stop{false};
  12392. std::thread t([&] {
  12393. client->Get("/event1",
  12394. [&](const char *, size_t) -> bool { return !stop; });
  12395. });
  12396. std::this_thread::sleep_for(std::chrono::seconds(2));
  12397. stop = true;
  12398. client->stop();
  12399. t.join();
  12400. // Reset client after thread has finished
  12401. client.reset();
  12402. }
  12403. }
  12404. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12405. auto handled = false;
  12406. Server svr;
  12407. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12408. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12409. auto se = detail::scope_exit([&] {
  12410. svr.stop();
  12411. t.join();
  12412. ASSERT_FALSE(svr.is_running());
  12413. ASSERT_FALSE(handled);
  12414. });
  12415. svr.wait_until_ready();
  12416. // Two Content-Length headers with different values — must be rejected
  12417. auto req = "POST /test HTTP/1.1\r\n"
  12418. "Content-Length: 5\r\n"
  12419. "Content-Length: 10\r\n"
  12420. "\r\n"
  12421. "hello";
  12422. std::string response;
  12423. ASSERT_TRUE(send_request(1, req, &response));
  12424. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12425. response.substr(0, response.find("\r\n")));
  12426. }
  12427. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12428. auto handled = false;
  12429. Server svr;
  12430. svr.Post("/test", [&](const Request &, Response &res) {
  12431. handled = true;
  12432. res.set_content("ok", "text/plain");
  12433. });
  12434. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12435. auto se = detail::scope_exit([&] {
  12436. svr.stop();
  12437. t.join();
  12438. ASSERT_FALSE(svr.is_running());
  12439. ASSERT_TRUE(handled);
  12440. });
  12441. svr.wait_until_ready();
  12442. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12443. auto req = "POST /test HTTP/1.1\r\n"
  12444. "Content-Length: 5\r\n"
  12445. "Content-Length: 5\r\n"
  12446. "\r\n"
  12447. "hello";
  12448. std::string response;
  12449. ASSERT_TRUE(send_request(1, req, &response));
  12450. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12451. }
  12452. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12453. Server svr;
  12454. svr.Get("/", [](const Request &req, Response &res) {
  12455. EXPECT_EQ(2U, req.trailers.size());
  12456. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12457. // Denied
  12458. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12459. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12460. // Accepted
  12461. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12462. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12463. EXPECT_TRUE(req.has_trailer("X-World"));
  12464. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12465. res.set_content("ok", "text/plain");
  12466. });
  12467. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12468. auto se = detail::scope_exit([&] {
  12469. svr.stop();
  12470. t.join();
  12471. ASSERT_FALSE(svr.is_running());
  12472. });
  12473. svr.wait_until_ready();
  12474. const std::string req = "GET / HTTP/1.1\r\n"
  12475. "Transfer-Encoding: chunked\r\n"
  12476. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12477. "\r\n"
  12478. "0\r\n"
  12479. "Content-Length: 10\r\n"
  12480. "Host: internal.local\r\n"
  12481. "Content-Type: malicious/content\r\n"
  12482. "Cookie: any\r\n"
  12483. "Set-Cookie: any\r\n"
  12484. "X-Forwarded-For: attacker.com\r\n"
  12485. "X-Real-Ip: 1.1.1.1\r\n"
  12486. "X-Hello: hello\r\n"
  12487. "X-World: world\r\n"
  12488. "\r\n";
  12489. std::string res;
  12490. ASSERT_TRUE(send_request(1, req, &res));
  12491. }
  12492. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12493. Server svr;
  12494. std::string observed_remote_addr;
  12495. std::string observed_xff;
  12496. svr.Get("/ip", [&](const Request &req, Response &res) {
  12497. observed_remote_addr = req.remote_addr;
  12498. observed_xff = req.get_header_value("X-Forwarded-For");
  12499. res.set_content("ok", "text/plain");
  12500. });
  12501. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12502. auto se = detail::scope_exit([&] {
  12503. svr.stop();
  12504. t.join();
  12505. ASSERT_FALSE(svr.is_running());
  12506. });
  12507. svr.wait_until_ready();
  12508. Client cli(HOST, PORT);
  12509. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  12510. ASSERT_TRUE(res);
  12511. EXPECT_EQ(StatusCode::OK_200, res->status);
  12512. EXPECT_EQ(observed_xff, "203.0.113.66");
  12513. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12514. observed_remote_addr == "127.0.0.1");
  12515. }
  12516. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12517. Server svr;
  12518. svr.set_trusted_proxies({"203.0.113.66"});
  12519. std::string observed_remote_addr;
  12520. std::string observed_xff;
  12521. svr.Get("/ip", [&](const Request &req, Response &res) {
  12522. observed_remote_addr = req.remote_addr;
  12523. observed_xff = req.get_header_value("X-Forwarded-For");
  12524. res.set_content("ok", "text/plain");
  12525. });
  12526. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12527. auto se = detail::scope_exit([&] {
  12528. svr.stop();
  12529. t.join();
  12530. ASSERT_FALSE(svr.is_running());
  12531. });
  12532. svr.wait_until_ready();
  12533. Client cli(HOST, PORT);
  12534. auto res = cli.Get("/ip");
  12535. ASSERT_TRUE(res);
  12536. EXPECT_EQ(StatusCode::OK_200, res->status);
  12537. EXPECT_EQ(observed_xff, "");
  12538. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12539. observed_remote_addr == "127.0.0.1");
  12540. }
  12541. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12542. Server svr;
  12543. svr.set_trusted_proxies({"203.0.113.66"});
  12544. std::string observed_remote_addr;
  12545. std::string observed_xff;
  12546. svr.Get("/ip", [&](const Request &req, Response &res) {
  12547. observed_remote_addr = req.remote_addr;
  12548. observed_xff = req.get_header_value("X-Forwarded-For");
  12549. res.set_content("ok", "text/plain");
  12550. });
  12551. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12552. auto se = detail::scope_exit([&] {
  12553. svr.stop();
  12554. t.join();
  12555. ASSERT_FALSE(svr.is_running());
  12556. });
  12557. svr.wait_until_ready();
  12558. Client cli(HOST, PORT);
  12559. auto res =
  12560. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12561. ASSERT_TRUE(res);
  12562. EXPECT_EQ(StatusCode::OK_200, res->status);
  12563. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12564. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12565. }
  12566. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12567. Server svr;
  12568. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12569. std::string observed_remote_addr;
  12570. std::string observed_xff;
  12571. svr.Get("/ip", [&](const Request &req, Response &res) {
  12572. observed_remote_addr = req.remote_addr;
  12573. observed_xff = req.get_header_value("X-Forwarded-For");
  12574. res.set_content("ok", "text/plain");
  12575. });
  12576. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12577. auto se = detail::scope_exit([&] {
  12578. svr.stop();
  12579. t.join();
  12580. ASSERT_FALSE(svr.is_running());
  12581. });
  12582. svr.wait_until_ready();
  12583. Client cli(HOST, PORT);
  12584. auto res = cli.Get(
  12585. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12586. ASSERT_TRUE(res);
  12587. EXPECT_EQ(StatusCode::OK_200, res->status);
  12588. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12589. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12590. }
  12591. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12592. Server svr;
  12593. svr.set_trusted_proxies({"192.0.2.45"});
  12594. std::string observed_remote_addr;
  12595. std::string observed_xff;
  12596. svr.Get("/ip", [&](const Request &req, Response &res) {
  12597. observed_remote_addr = req.remote_addr;
  12598. observed_xff = req.get_header_value("X-Forwarded-For");
  12599. res.set_content("ok", "text/plain");
  12600. });
  12601. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12602. auto se = detail::scope_exit([&] {
  12603. svr.stop();
  12604. t.join();
  12605. ASSERT_FALSE(svr.is_running());
  12606. });
  12607. svr.wait_until_ready();
  12608. Client cli(HOST, PORT);
  12609. auto res =
  12610. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12611. ASSERT_TRUE(res);
  12612. EXPECT_EQ(StatusCode::OK_200, res->status);
  12613. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12614. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12615. }
  12616. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12617. Server svr;
  12618. svr.set_trusted_proxies({"192.0.2.45"});
  12619. std::string observed_remote_addr;
  12620. std::string observed_xff;
  12621. svr.Get("/ip", [&](const Request &req, Response &res) {
  12622. observed_remote_addr = req.remote_addr;
  12623. observed_xff = req.get_header_value("X-Forwarded-For");
  12624. res.set_content("ok", "text/plain");
  12625. });
  12626. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12627. auto se = detail::scope_exit([&] {
  12628. svr.stop();
  12629. t.join();
  12630. ASSERT_FALSE(svr.is_running());
  12631. });
  12632. svr.wait_until_ready();
  12633. Client cli(HOST, PORT);
  12634. auto res = cli.Get(
  12635. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12636. ASSERT_TRUE(res);
  12637. EXPECT_EQ(StatusCode::OK_200, res->status);
  12638. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12639. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12640. }
  12641. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12642. Server svr;
  12643. svr.set_trusted_proxies({"192.0.2.45"});
  12644. std::string observed_remote_addr;
  12645. std::string observed_xff;
  12646. svr.Get("/ip", [&](const Request &req, Response &res) {
  12647. observed_remote_addr = req.remote_addr;
  12648. observed_xff = req.get_header_value("X-Forwarded-For");
  12649. res.set_content("ok", "text/plain");
  12650. });
  12651. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12652. auto se = detail::scope_exit([&] {
  12653. svr.stop();
  12654. t.join();
  12655. ASSERT_FALSE(svr.is_running());
  12656. });
  12657. svr.wait_until_ready();
  12658. std::string raw_req =
  12659. "GET /ip HTTP/1.1\r\n"
  12660. "Host: localhost\r\n"
  12661. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12662. "Connection: close\r\n"
  12663. "\r\n";
  12664. std::string out;
  12665. ASSERT_TRUE(send_request(5, raw_req, &out));
  12666. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12667. // Header parser trims surrounding whitespace of the header value
  12668. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12669. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12670. }
  12671. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12672. // crash the server (it used to call front() on an empty vector inside
  12673. // get_client_ip). The connection-level remote address must be retained instead.
  12674. static void run_malformed_xff_test(const std::string &xff_value) {
  12675. Server svr;
  12676. svr.set_trusted_proxies({"192.0.2.45"});
  12677. std::string observed_remote_addr;
  12678. svr.Get("/ip", [&](const Request &req, Response &res) {
  12679. observed_remote_addr = req.remote_addr;
  12680. res.set_content("ok", "text/plain");
  12681. });
  12682. int port = 0;
  12683. thread t = thread([&]() {
  12684. port = svr.bind_to_any_port(HOST);
  12685. svr.listen_after_bind();
  12686. });
  12687. auto se = detail::scope_exit([&] {
  12688. svr.stop();
  12689. t.join();
  12690. ASSERT_FALSE(svr.is_running());
  12691. });
  12692. svr.wait_until_ready();
  12693. Client cli(HOST, port);
  12694. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12695. ASSERT_TRUE(res);
  12696. EXPECT_EQ(StatusCode::OK_200, res->status);
  12697. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12698. observed_remote_addr == "127.0.0.1");
  12699. }
  12700. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12701. run_malformed_xff_test("");
  12702. }
  12703. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12704. run_malformed_xff_test(",");
  12705. }
  12706. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12707. run_malformed_xff_test(", , ,");
  12708. }
  12709. #ifndef _WIN32
  12710. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12711. Server svr;
  12712. svr.Post("/post", [&](const Request &req, Response &res) {
  12713. res.set_content(req.body, "text/plain");
  12714. });
  12715. svr.Put("/put", [&](const Request &req, Response &res) {
  12716. res.set_content(req.body, "text/plain");
  12717. });
  12718. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12719. res.set_content(req.body, "text/plain");
  12720. });
  12721. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12722. res.set_content(req.body, "text/plain");
  12723. });
  12724. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12725. auto se = detail::scope_exit([&] {
  12726. svr.stop();
  12727. t.join();
  12728. ASSERT_FALSE(svr.is_running());
  12729. });
  12730. svr.wait_until_ready();
  12731. std::string resp;
  12732. // POST without Content-Length
  12733. ASSERT_TRUE(send_request(5,
  12734. "POST /post HTTP/1.1\r\n"
  12735. "Host: localhost\r\n"
  12736. "Connection: close\r\n"
  12737. "\r\n",
  12738. &resp));
  12739. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12740. // PUT without Content-Length
  12741. resp.clear();
  12742. ASSERT_TRUE(send_request(5,
  12743. "PUT /put HTTP/1.1\r\n"
  12744. "Host: localhost\r\n"
  12745. "Connection: close\r\n"
  12746. "\r\n",
  12747. &resp));
  12748. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12749. // PATCH without Content-Length
  12750. resp.clear();
  12751. ASSERT_TRUE(send_request(5,
  12752. "PATCH /patch HTTP/1.1\r\n"
  12753. "Host: localhost\r\n"
  12754. "Connection: close\r\n"
  12755. "\r\n",
  12756. &resp));
  12757. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12758. // DELETE without Content-Length
  12759. resp.clear();
  12760. ASSERT_TRUE(send_request(5,
  12761. "DELETE /delete HTTP/1.1\r\n"
  12762. "Host: localhost\r\n"
  12763. "Connection: close\r\n"
  12764. "\r\n",
  12765. &resp));
  12766. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12767. }
  12768. #endif
  12769. //==============================================================================
  12770. // open_stream() Tests
  12771. //==============================================================================
  12772. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12773. std::string result;
  12774. char buf[8192];
  12775. ssize_t n;
  12776. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12777. result.append(buf, static_cast<size_t>(n));
  12778. }
  12779. return result;
  12780. }
  12781. // Mock stream for unit tests
  12782. class MockStream : public Stream {
  12783. public:
  12784. std::string data;
  12785. size_t pos = 0;
  12786. ssize_t error_after = -1; // -1 = no error
  12787. explicit MockStream(const std::string &d, ssize_t err = -1)
  12788. : data(d), error_after(err) {}
  12789. bool is_readable() const override { return true; }
  12790. bool wait_readable() const override { return true; }
  12791. bool wait_writable() const override { return true; }
  12792. ssize_t read(char *ptr, size_t size) override {
  12793. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12794. if (pos >= data.size()) return 0;
  12795. size_t limit =
  12796. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12797. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12798. std::memcpy(ptr, data.data() + pos, to_read);
  12799. pos += to_read;
  12800. return static_cast<ssize_t>(to_read);
  12801. }
  12802. ssize_t write(const char *, size_t) override { return -1; }
  12803. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12804. ip = "127.0.0.1";
  12805. port = 0;
  12806. }
  12807. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12808. ip = "127.0.0.1";
  12809. port = 0;
  12810. }
  12811. socket_t socket() const override { return INVALID_SOCKET; }
  12812. time_t duration() const override { return 0; }
  12813. };
  12814. TEST(StreamHandleTest, Basic) {
  12815. ClientImpl::StreamHandle handle;
  12816. EXPECT_FALSE(handle.is_valid());
  12817. handle.response = detail::make_unique<Response>();
  12818. handle.error = Error::Connection;
  12819. EXPECT_FALSE(handle.is_valid());
  12820. handle.error = Error::Success;
  12821. EXPECT_TRUE(handle.is_valid());
  12822. }
  12823. TEST(BodyReaderTest, Basic) {
  12824. MockStream stream("Hello, World!");
  12825. detail::BodyReader reader;
  12826. reader.stream = &stream;
  12827. reader.content_length = 13;
  12828. char buf[32];
  12829. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12830. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12831. EXPECT_TRUE(reader.eof);
  12832. }
  12833. TEST(BodyReaderTest, NoStream) {
  12834. detail::BodyReader reader;
  12835. char buf[32];
  12836. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12837. EXPECT_EQ(Error::Connection, reader.last_error);
  12838. }
  12839. TEST(BodyReaderTest, Error) {
  12840. MockStream stream("Hello, World!", 5);
  12841. detail::BodyReader reader;
  12842. reader.stream = &stream;
  12843. reader.content_length = 13;
  12844. char buf[32];
  12845. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12846. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12847. EXPECT_EQ(Error::Read, reader.last_error);
  12848. }
  12849. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12850. // Mock-based StreamHandle tests relying on private internals are removed.
  12851. class OpenStreamTest : public ::testing::Test {
  12852. protected:
  12853. void SetUp() override {
  12854. svr_.Get("/hello", [](const Request &, Response &res) {
  12855. res.set_content("Hello World!", "text/plain");
  12856. });
  12857. svr_.Get("/large", [](const Request &, Response &res) {
  12858. res.set_content(std::string(10000, 'X'), "text/plain");
  12859. });
  12860. svr_.Get("/chunked", [](const Request &, Response &res) {
  12861. res.set_chunked_content_provider("text/plain",
  12862. [](size_t offset, DataSink &sink) {
  12863. if (offset < 15) {
  12864. sink.write("chunk", 5);
  12865. return true;
  12866. }
  12867. sink.done();
  12868. return true;
  12869. });
  12870. });
  12871. svr_.Get("/compressible", [](const Request &, Response &res) {
  12872. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12873. DataSink &sink) {
  12874. if (offset < 100 * 1024) {
  12875. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12876. sink.write(chunk.data(), chunk.size());
  12877. return true;
  12878. }
  12879. sink.done();
  12880. return true;
  12881. });
  12882. });
  12883. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12884. [](const Request & /*req*/, Response &res) {
  12885. auto i = new int(0);
  12886. res.set_header("Trailer", "Content-Length, X-Allowed");
  12887. res.set_chunked_content_provider(
  12888. "text/plain",
  12889. [i](size_t /*offset*/, DataSink &sink) {
  12890. switch (*i) {
  12891. case 0: sink.os << "123"; break;
  12892. case 1: sink.os << "456"; break;
  12893. case 2: sink.os << "789"; break;
  12894. case 3: {
  12895. sink.done_with_trailer(
  12896. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12897. } break;
  12898. }
  12899. (*i)++;
  12900. return true;
  12901. },
  12902. [i](bool success) {
  12903. EXPECT_TRUE(success);
  12904. delete i;
  12905. });
  12906. });
  12907. // Echo headers endpoint for header-related tests
  12908. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12909. std::string body;
  12910. for (const auto &h : req.headers) {
  12911. body.append(h.first);
  12912. body.push_back(':');
  12913. body.append(h.second);
  12914. body.push_back('\n');
  12915. }
  12916. res.set_content(body, "text/plain");
  12917. });
  12918. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12919. std::string body;
  12920. for (const auto &h : req.headers) {
  12921. body.append(h.first);
  12922. body.push_back(':');
  12923. body.append(h.second);
  12924. body.push_back('\n');
  12925. }
  12926. res.set_content(body, "text/plain");
  12927. });
  12928. port_ = svr_.bind_to_any_port("127.0.0.1");
  12929. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12930. svr_.wait_until_ready();
  12931. }
  12932. void TearDown() override {
  12933. svr_.stop();
  12934. if (thread_.joinable()) thread_.join();
  12935. }
  12936. Server svr_;
  12937. std::thread thread_;
  12938. int port_ = 0;
  12939. };
  12940. TEST_F(OpenStreamTest, Basic) {
  12941. Client cli("127.0.0.1", port_);
  12942. auto handle = cli.open_stream("GET", "/hello");
  12943. EXPECT_TRUE(handle.is_valid());
  12944. EXPECT_EQ("Hello World!", read_all(handle));
  12945. }
  12946. TEST_F(OpenStreamTest, SmallBuffer) {
  12947. Client cli("127.0.0.1", port_);
  12948. auto handle = cli.open_stream("GET", "/hello");
  12949. std::string result;
  12950. char buf[4];
  12951. ssize_t n;
  12952. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12953. result.append(buf, static_cast<size_t>(n));
  12954. EXPECT_EQ("Hello World!", result);
  12955. }
  12956. TEST_F(OpenStreamTest, DefaultHeaders) {
  12957. Client cli("127.0.0.1", port_);
  12958. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12959. {
  12960. auto handle = cli.open_stream("GET", "/echo-headers");
  12961. ASSERT_TRUE(handle.is_valid());
  12962. auto body = read_all(handle);
  12963. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12964. std::string::npos);
  12965. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12966. std::string::npos);
  12967. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12968. }
  12969. // open_stream POST with body and no explicit content_type should NOT add
  12970. // text/plain Content-Type (behavior differs from non-streaming path), but
  12971. // should include Content-Length
  12972. {
  12973. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12974. ASSERT_TRUE(handle.is_valid());
  12975. auto body = read_all(handle);
  12976. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12977. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12978. }
  12979. // open_stream POST with explicit Content-Type should preserve it
  12980. {
  12981. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12982. {{"Content-Type", "application/custom"}},
  12983. "{}", "application/custom");
  12984. ASSERT_TRUE(handle.is_valid());
  12985. auto body = read_all(handle);
  12986. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12987. }
  12988. // User-specified User-Agent must not be overwritten for stream API
  12989. {
  12990. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12991. {{"User-Agent", "MyAgent/1.2"}});
  12992. ASSERT_TRUE(handle.is_valid());
  12993. auto body = read_all(handle);
  12994. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12995. }
  12996. }
  12997. TEST_F(OpenStreamTest, Large) {
  12998. Client cli("127.0.0.1", port_);
  12999. auto handle = cli.open_stream("GET", "/large");
  13000. EXPECT_EQ(10000u, read_all(handle).size());
  13001. }
  13002. TEST_F(OpenStreamTest, ConnectionError) {
  13003. Client cli("127.0.0.1", 9999);
  13004. auto handle = cli.open_stream("GET", "/hello");
  13005. EXPECT_FALSE(handle.is_valid());
  13006. }
  13007. TEST_F(OpenStreamTest, Chunked) {
  13008. Client cli("127.0.0.1", port_);
  13009. auto handle = cli.open_stream("GET", "/chunked");
  13010. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13011. "Transfer-Encoding") == "chunked");
  13012. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13013. }
  13014. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13015. Client cli("127.0.0.1", port_);
  13016. auto handle =
  13017. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13018. ASSERT_TRUE(handle.is_valid());
  13019. // Consume body to allow trailers to be received/parsed
  13020. auto body = read_all(handle);
  13021. // Explicitly parse trailers (ensure trailers are available for assertion)
  13022. handle.parse_trailers_if_needed();
  13023. EXPECT_EQ(std::string("123456789"), body);
  13024. // The response should include a Trailer header declaring both names
  13025. ASSERT_TRUE(handle.response);
  13026. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13027. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13028. handle.response->get_header_value("Trailer"));
  13029. // Prohibited trailer must not be present
  13030. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13031. // Allowed trailer should be present
  13032. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13033. EXPECT_EQ(std::string("yes"),
  13034. handle.response->get_trailer_value("X-Allowed"));
  13035. // Verify trailers are NOT present as regular headers
  13036. EXPECT_EQ(std::string(""),
  13037. handle.response->get_header_value("Content-Length"));
  13038. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13039. }
  13040. static std::thread serve_single_response(std::promise<int> &port_promise,
  13041. const std::string &response) {
  13042. return std::thread([&port_promise, response] {
  13043. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13044. default_socket_options(srv);
  13045. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13046. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13047. sockaddr_in addr{};
  13048. addr.sin_family = AF_INET;
  13049. addr.sin_port = htons(0); // Let OS assign a free port
  13050. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13051. int opt = 1;
  13052. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13053. #ifdef _WIN32
  13054. reinterpret_cast<const char *>(&opt),
  13055. #else
  13056. &opt,
  13057. #endif
  13058. sizeof(opt));
  13059. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13060. ::listen(srv, 1) != 0) {
  13061. port_promise.set_value(-1);
  13062. detail::close_socket(srv);
  13063. return;
  13064. }
  13065. socklen_t addr_len = sizeof(addr);
  13066. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13067. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13068. sockaddr_in cli_addr{};
  13069. socklen_t cli_len = sizeof(cli_addr);
  13070. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13071. if (cli != INVALID_SOCKET) {
  13072. // Read the complete HTTP request (until the blank line that terminates
  13073. // headers) before sending the response. If the server closes the socket
  13074. // while the client's request data is still unread in the kernel receive
  13075. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13076. // connection on both sides: it discards the client's receive buffer
  13077. // (which already holds our response) and causes any in-progress write on
  13078. // the client to fail with ECONNRESET. Reading all request data first
  13079. // ensures close() emits a graceful FIN.
  13080. {
  13081. char rbuf[256];
  13082. std::string req;
  13083. while (req.find("\r\n\r\n") == std::string::npos) {
  13084. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13085. if (n <= 0) { break; }
  13086. req.append(rbuf, static_cast<size_t>(n));
  13087. }
  13088. }
  13089. ::send(cli,
  13090. #ifdef _WIN32
  13091. static_cast<const char *>(response.c_str()),
  13092. static_cast<int>(response.size()),
  13093. #else
  13094. response.c_str(), response.size(),
  13095. #endif
  13096. 0);
  13097. detail::close_socket(cli);
  13098. }
  13099. detail::close_socket(srv);
  13100. });
  13101. }
  13102. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13103. #ifndef _WIN32
  13104. signal(SIGPIPE, SIG_IGN);
  13105. #endif
  13106. std::promise<int> port_promise;
  13107. auto port_future = port_promise.get_future();
  13108. auto server_thread =
  13109. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13110. "Content-Type: text/plain\r\n"
  13111. "Content-Length: not-a-number\r\n"
  13112. "Connection: close\r\n"
  13113. "\r\n"
  13114. "hello");
  13115. auto port = port_future.get();
  13116. ASSERT_GT(port, 0);
  13117. Client cli("127.0.0.1", port);
  13118. auto handle = cli.open_stream("GET", "/");
  13119. EXPECT_FALSE(handle.is_valid());
  13120. server_thread.join();
  13121. }
  13122. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13123. #ifndef _WIN32
  13124. signal(SIGPIPE, SIG_IGN);
  13125. #endif
  13126. std::promise<int> port_promise;
  13127. auto port_future = port_promise.get_future();
  13128. auto server_thread = serve_single_response(
  13129. port_promise, "HTTP/1.1 200 OK\r\n"
  13130. "Content-Type: text/plain\r\n"
  13131. "Content-Length: 99999999999999999999999999\r\n"
  13132. "Connection: close\r\n"
  13133. "\r\n"
  13134. "hello");
  13135. auto port = port_future.get();
  13136. ASSERT_GT(port, 0);
  13137. // Before the fix, std::stoull would throw std::out_of_range here and
  13138. // crash the process. After the fix, strtoull silently clamps to
  13139. // ULLONG_MAX so the stream opens without crashing. The important thing
  13140. // is that the process does NOT terminate.
  13141. Client cli("127.0.0.1", port);
  13142. auto handle = cli.open_stream("GET", "/");
  13143. EXPECT_TRUE(handle.is_valid());
  13144. server_thread.join();
  13145. }
  13146. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13147. TEST_F(OpenStreamTest, Gzip) {
  13148. Client cli("127.0.0.1", port_);
  13149. auto handle = cli.open_stream("GET", "/compressible", {},
  13150. {{"Accept-Encoding", "gzip"}});
  13151. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13152. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13153. }
  13154. #endif
  13155. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13156. TEST_F(OpenStreamTest, Brotli) {
  13157. Client cli("127.0.0.1", port_);
  13158. auto handle =
  13159. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13160. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13161. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13162. }
  13163. #endif
  13164. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13165. TEST_F(OpenStreamTest, Zstd) {
  13166. Client cli("127.0.0.1", port_);
  13167. auto handle = cli.open_stream("GET", "/compressible", {},
  13168. {{"Accept-Encoding", "zstd"}});
  13169. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13170. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13171. }
  13172. #endif
  13173. #ifdef CPPHTTPLIB_SSL_ENABLED
  13174. class SSLOpenStreamTest : public ::testing::Test {
  13175. protected:
  13176. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13177. void SetUp() override {
  13178. svr_.Get("/hello", [](const Request &, Response &res) {
  13179. res.set_content("Hello SSL World!", "text/plain");
  13180. });
  13181. svr_.Get("/chunked", [](const Request &, Response &res) {
  13182. res.set_chunked_content_provider("text/plain",
  13183. [](size_t offset, DataSink &sink) {
  13184. if (offset < 15) {
  13185. sink.write("chunk", 5);
  13186. return true;
  13187. }
  13188. sink.done();
  13189. return true;
  13190. });
  13191. });
  13192. svr_.Post("/echo", [](const Request &req, Response &res) {
  13193. res.set_content(req.body, req.get_header_value("Content-Type"));
  13194. });
  13195. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13196. std::string body = req.body;
  13197. res.set_chunked_content_provider(
  13198. "text/plain", [body](size_t offset, DataSink &sink) {
  13199. if (offset < body.size()) {
  13200. sink.write(body.data() + offset, body.size() - offset);
  13201. }
  13202. sink.done();
  13203. return true;
  13204. });
  13205. });
  13206. port_ = svr_.bind_to_any_port("127.0.0.1");
  13207. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13208. svr_.wait_until_ready();
  13209. }
  13210. void TearDown() override {
  13211. svr_.stop();
  13212. if (thread_.joinable()) thread_.join();
  13213. }
  13214. SSLServer svr_;
  13215. std::thread thread_;
  13216. int port_ = 0;
  13217. };
  13218. TEST_F(SSLOpenStreamTest, Basic) {
  13219. SSLClient cli("127.0.0.1", port_);
  13220. cli.enable_server_certificate_verification(false);
  13221. auto handle = cli.open_stream("GET", "/hello");
  13222. ASSERT_TRUE(handle.is_valid());
  13223. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13224. }
  13225. TEST_F(SSLOpenStreamTest, Chunked) {
  13226. SSLClient cli("127.0.0.1", port_);
  13227. cli.enable_server_certificate_verification(false);
  13228. auto handle = cli.open_stream("GET", "/chunked");
  13229. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13230. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13231. "Transfer-Encoding") == "chunked");
  13232. auto body = read_all(handle);
  13233. EXPECT_EQ("chunkchunkchunk", body);
  13234. }
  13235. TEST_F(SSLOpenStreamTest, Post) {
  13236. SSLClient cli("127.0.0.1", port_);
  13237. cli.enable_server_certificate_verification(false);
  13238. auto handle =
  13239. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13240. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13241. EXPECT_EQ(200, handle.response->status);
  13242. auto body = read_all(handle);
  13243. EXPECT_EQ("Hello SSL POST", body);
  13244. }
  13245. TEST_F(SSLOpenStreamTest, PostChunked) {
  13246. SSLClient cli("127.0.0.1", port_);
  13247. cli.enable_server_certificate_verification(false);
  13248. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13249. "Chunked SSL Data", "text/plain");
  13250. ASSERT_TRUE(handle.is_valid());
  13251. EXPECT_EQ(200, handle.response->status);
  13252. auto body = read_all(handle);
  13253. EXPECT_EQ("Chunked SSL Data", body);
  13254. }
  13255. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13256. // Content-Length is terminated by the server closing the connection. When the
  13257. // SSL peer sends a close_notify after the body, the client must treat it as a
  13258. // clean EOF and return a successful response rather than an error.
  13259. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13261. ASSERT_TRUE(svr.is_valid());
  13262. svr.set_keep_alive_max_count(1);
  13263. const std::string expected_body = "Hello from connection-close response!";
  13264. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13265. res.set_content_provider("text/plain",
  13266. [&](size_t offset, DataSink &sink) -> bool {
  13267. if (offset < expected_body.size()) {
  13268. sink.write(expected_body.data() + offset,
  13269. expected_body.size() - offset);
  13270. }
  13271. sink.done();
  13272. return true;
  13273. });
  13274. });
  13275. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13276. auto se = detail::scope_exit([&] {
  13277. svr.stop();
  13278. listen_thread.join();
  13279. ASSERT_FALSE(svr.is_running());
  13280. });
  13281. svr.wait_until_ready();
  13282. SSLClient cli(HOST, PORT);
  13283. cli.enable_server_certificate_verification(false);
  13284. auto res = cli.Get("/no-content-length");
  13285. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13286. EXPECT_EQ(StatusCode::OK_200, res->status);
  13287. EXPECT_EQ(expected_body, res->body);
  13288. }
  13289. #endif // CPPHTTPLIB_SSL_ENABLED
  13290. //==============================================================================
  13291. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13292. // results for various scenarios.
  13293. //==============================================================================
  13294. TEST(ParityTest, GetVsOpenStream) {
  13295. Server svr;
  13296. const std::string path = "/parity";
  13297. const std::string content = "Parity test content: hello world";
  13298. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13299. res.set_content(content, "text/plain");
  13300. });
  13301. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13302. auto se = detail::scope_exit([&] {
  13303. svr.stop();
  13304. t.join();
  13305. ASSERT_FALSE(svr.is_running());
  13306. });
  13307. svr.wait_until_ready();
  13308. Client cli(HOST, PORT);
  13309. // Non-stream path
  13310. auto r1 = cli.Get(path);
  13311. ASSERT_TRUE(r1);
  13312. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13313. // Stream path
  13314. auto h = cli.open_stream("GET", path);
  13315. ASSERT_TRUE(h.is_valid());
  13316. EXPECT_EQ(r1->body, read_all(h));
  13317. }
  13318. // Helper to compress data with provided compressor type T
  13319. template <typename Compressor>
  13320. static std::string compress_payload_for_parity(const std::string &in) {
  13321. std::string out;
  13322. Compressor compressor;
  13323. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13324. [&](const char *data, size_t n) {
  13325. out.append(data, n);
  13326. return true;
  13327. });
  13328. EXPECT_TRUE(ok);
  13329. return out;
  13330. }
  13331. // Helper function for compression parity tests
  13332. template <typename Compressor>
  13333. static void test_compression_parity(const std::string &original,
  13334. const std::string &path,
  13335. const std::string &encoding) {
  13336. const std::string compressed =
  13337. compress_payload_for_parity<Compressor>(original);
  13338. Server svr;
  13339. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13340. res.set_content(compressed, "application/octet-stream");
  13341. res.set_header("Content-Encoding", encoding);
  13342. });
  13343. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13344. auto se = detail::scope_exit([&] {
  13345. svr.stop();
  13346. t.join();
  13347. ASSERT_FALSE(svr.is_running());
  13348. });
  13349. svr.wait_until_ready();
  13350. Client cli(HOST, PORT);
  13351. // Non-streaming
  13352. {
  13353. auto res = cli.Get(path);
  13354. ASSERT_TRUE(res);
  13355. EXPECT_EQ(StatusCode::OK_200, res->status);
  13356. EXPECT_EQ(original, res->body);
  13357. }
  13358. // Streaming
  13359. {
  13360. auto h = cli.open_stream("GET", path);
  13361. ASSERT_TRUE(h.is_valid());
  13362. EXPECT_EQ(original, read_all(h));
  13363. }
  13364. }
  13365. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13366. TEST(ParityTest, Gzip) {
  13367. test_compression_parity<detail::gzip_compressor>(
  13368. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13369. }
  13370. #endif
  13371. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13372. TEST(ParityTest, Brotli) {
  13373. test_compression_parity<detail::brotli_compressor>(
  13374. "Hello, brotli parity test payload", "/parity-br", "br");
  13375. }
  13376. #endif
  13377. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13378. TEST(ParityTest, Zstd) {
  13379. test_compression_parity<detail::zstd_compressor>(
  13380. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13381. }
  13382. #endif
  13383. //==============================================================================
  13384. // New Stream API Tests
  13385. //==============================================================================
  13386. inline std::string read_body(httplib::stream::Result &result) {
  13387. std::string body;
  13388. while (result.next()) {
  13389. body.append(result.data(), result.size());
  13390. }
  13391. return body;
  13392. }
  13393. TEST(ClientConnectionTest, Basic) {
  13394. httplib::ClientConnection conn;
  13395. EXPECT_FALSE(conn.is_open());
  13396. conn.sock = 1;
  13397. EXPECT_TRUE(conn.is_open());
  13398. httplib::ClientConnection conn2(std::move(conn));
  13399. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13400. conn2.sock = INVALID_SOCKET;
  13401. }
  13402. // Unified test server for all stream::* tests
  13403. class StreamApiTest : public ::testing::Test {
  13404. protected:
  13405. void SetUp() override {
  13406. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13407. res.set_content("Hello World!", "text/plain");
  13408. });
  13409. svr_.Get("/echo-params",
  13410. [](const httplib::Request &req, httplib::Response &res) {
  13411. std::string r;
  13412. for (const auto &p : req.params) {
  13413. if (!r.empty()) r += "&";
  13414. r += p.first + "=" + p.second;
  13415. }
  13416. res.set_content(r, "text/plain");
  13417. });
  13418. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13419. res.set_content(req.body, req.get_header_value("Content-Type"));
  13420. });
  13421. svr_.Post("/echo-headers",
  13422. [](const httplib::Request &req, httplib::Response &res) {
  13423. std::string r;
  13424. for (const auto &h : req.headers)
  13425. r += h.first + ": " + h.second + "\n";
  13426. res.set_content(r, "text/plain");
  13427. });
  13428. svr_.Post("/echo-params",
  13429. [](const httplib::Request &req, httplib::Response &res) {
  13430. std::string r = "params:";
  13431. for (const auto &p : req.params)
  13432. r += p.first + "=" + p.second + ";";
  13433. res.set_content(r + " body:" + req.body, "text/plain");
  13434. });
  13435. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13436. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13437. });
  13438. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13439. res.set_content("PUT:" + req.body, "text/plain");
  13440. });
  13441. svr_.Patch("/echo",
  13442. [](const httplib::Request &req, httplib::Response &res) {
  13443. res.set_content("PATCH:" + req.body, "text/plain");
  13444. });
  13445. svr_.Delete(
  13446. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13447. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13448. "text/plain");
  13449. });
  13450. svr_.Get("/head-test",
  13451. [](const httplib::Request &, httplib::Response &res) {
  13452. res.set_content("body for HEAD", "text/plain");
  13453. });
  13454. svr_.Options("/options",
  13455. [](const httplib::Request &, httplib::Response &res) {
  13456. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13457. });
  13458. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13459. svr_.wait_until_ready();
  13460. }
  13461. void TearDown() override {
  13462. svr_.stop();
  13463. if (thread_.joinable()) thread_.join();
  13464. }
  13465. httplib::Server svr_;
  13466. std::thread thread_;
  13467. };
  13468. // stream::Get tests
  13469. TEST_F(StreamApiTest, GetBasic) {
  13470. httplib::Client cli(HOST, PORT);
  13471. auto result = httplib::stream::Get(cli, "/hello");
  13472. ASSERT_TRUE(result.is_valid());
  13473. EXPECT_EQ(200, result.status());
  13474. EXPECT_EQ("Hello World!", read_body(result));
  13475. }
  13476. TEST_F(StreamApiTest, GetWithParams) {
  13477. httplib::Client cli(HOST, PORT);
  13478. httplib::Params params{{"foo", "bar"}};
  13479. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13480. ASSERT_TRUE(result.is_valid());
  13481. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13482. }
  13483. TEST_F(StreamApiTest, GetConnectionError) {
  13484. httplib::Client cli(HOST, 9999);
  13485. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13486. }
  13487. TEST_F(StreamApiTest, Get404) {
  13488. httplib::Client cli(HOST, PORT);
  13489. auto result = httplib::stream::Get(cli, "/nonexistent");
  13490. EXPECT_TRUE(result.is_valid());
  13491. EXPECT_EQ(404, result.status());
  13492. }
  13493. // stream::Post tests
  13494. TEST_F(StreamApiTest, PostBasic) {
  13495. httplib::Client cli(HOST, PORT);
  13496. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13497. "application/json");
  13498. ASSERT_TRUE(result.is_valid());
  13499. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13500. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13501. }
  13502. TEST_F(StreamApiTest, PostWithHeaders) {
  13503. httplib::Client cli(HOST, PORT);
  13504. httplib::Headers headers{{"X-Custom", "value"}};
  13505. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13506. "text/plain");
  13507. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13508. }
  13509. TEST_F(StreamApiTest, PostWithParams) {
  13510. httplib::Client cli(HOST, PORT);
  13511. httplib::Params params{{"k", "v"}};
  13512. auto result =
  13513. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13514. auto body = read_body(result);
  13515. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13516. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13517. }
  13518. TEST_F(StreamApiTest, PostLarge) {
  13519. httplib::Client cli(HOST, PORT);
  13520. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13521. size_t total = 0;
  13522. while (result.next()) {
  13523. total += result.size();
  13524. }
  13525. EXPECT_EQ(100u * 1024u, total);
  13526. }
  13527. // stream::Put/Patch tests
  13528. TEST_F(StreamApiTest, PutAndPatch) {
  13529. httplib::Client cli(HOST, PORT);
  13530. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13531. EXPECT_EQ("PUT:test", read_body(put));
  13532. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13533. EXPECT_EQ("PATCH:test", read_body(patch));
  13534. }
  13535. // stream::Delete tests
  13536. TEST_F(StreamApiTest, Delete) {
  13537. httplib::Client cli(HOST, PORT);
  13538. auto del1 = httplib::stream::Delete(cli, "/resource");
  13539. EXPECT_EQ("Deleted", read_body(del1));
  13540. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13541. EXPECT_EQ("Deleted:data", read_body(del2));
  13542. }
  13543. // stream::Head/Options tests
  13544. TEST_F(StreamApiTest, HeadAndOptions) {
  13545. httplib::Client cli(HOST, PORT);
  13546. auto head = httplib::stream::Head(cli, "/head-test");
  13547. EXPECT_TRUE(head.is_valid());
  13548. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13549. auto opts = httplib::stream::Options(cli, "/options");
  13550. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13551. }
  13552. // SSL stream::* tests
  13553. #ifdef CPPHTTPLIB_SSL_ENABLED
  13554. class SSLStreamApiTest : public ::testing::Test {
  13555. protected:
  13556. void SetUp() override {
  13557. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13558. res.set_content("Hello SSL!", "text/plain");
  13559. });
  13560. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13561. res.set_content(req.body, "text/plain");
  13562. });
  13563. port_ = svr_.bind_to_any_port("127.0.0.1");
  13564. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13565. svr_.wait_until_ready();
  13566. }
  13567. void TearDown() override {
  13568. svr_.stop();
  13569. if (thread_.joinable()) thread_.join();
  13570. }
  13571. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13572. std::thread thread_;
  13573. int port_ = 0;
  13574. };
  13575. TEST_F(SSLStreamApiTest, GetAndPost) {
  13576. httplib::SSLClient cli("127.0.0.1", port_);
  13577. cli.enable_server_certificate_verification(false);
  13578. auto get = httplib::stream::Get(cli, "/hello");
  13579. EXPECT_EQ("Hello SSL!", read_body(get));
  13580. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13581. EXPECT_EQ("test", read_body(post));
  13582. }
  13583. #endif
  13584. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13585. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13586. // BodyReader
  13587. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13588. // Test that read timeout during streaming is detected
  13589. // Use a large content-length response where server delays mid-stream
  13590. Server svr;
  13591. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13592. // Send a large response with delay in the middle
  13593. res.set_content_provider(
  13594. 1000, // content_length
  13595. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13596. if (offset < 100) {
  13597. // Send first 100 bytes immediately
  13598. std::string data(100, 'A');
  13599. sink.write(data.c_str(), data.size());
  13600. return true;
  13601. }
  13602. // Then delay longer than client timeout
  13603. std::this_thread::sleep_for(std::chrono::seconds(3));
  13604. std::string data(900, 'B');
  13605. sink.write(data.c_str(), data.size());
  13606. return true;
  13607. });
  13608. });
  13609. auto port = 8091;
  13610. std::thread t([&]() { svr.listen("localhost", port); });
  13611. svr.wait_until_ready();
  13612. Client cli("localhost", port);
  13613. cli.set_read_timeout(1, 0); // 1 second timeout
  13614. auto handle = cli.open_stream("GET", "/slow-stream");
  13615. ASSERT_TRUE(handle.is_valid());
  13616. char buf[256];
  13617. ssize_t total = 0;
  13618. ssize_t n;
  13619. bool got_error = false;
  13620. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13621. total += n;
  13622. }
  13623. if (n < 0) {
  13624. got_error = true;
  13625. // Should be timeout or read error
  13626. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13627. handle.get_read_error() == Error::Read)
  13628. << "Actual error: " << to_string(handle.get_read_error());
  13629. }
  13630. // Either we got an error, or we got less data than expected
  13631. EXPECT_TRUE(got_error || total < 1000)
  13632. << "Expected timeout but got all " << total << " bytes";
  13633. svr.stop();
  13634. t.join();
  13635. }
  13636. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13637. // Test connection closed detection via BodyReader
  13638. Server svr;
  13639. std::atomic<bool> close_now{false};
  13640. svr.Get("/will-close", [&](const Request &, Response &res) {
  13641. res.set_content_provider(
  13642. 10000, // Large content_length that we won't fully send
  13643. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13644. if (offset < 100) {
  13645. std::string data(100, 'X');
  13646. sink.write(data.c_str(), data.size());
  13647. return true;
  13648. }
  13649. // Wait for signal then abort
  13650. while (!close_now) {
  13651. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13652. }
  13653. return false; // Abort - server will close connection
  13654. });
  13655. });
  13656. auto port = 8092;
  13657. std::thread t([&]() { svr.listen("localhost", port); });
  13658. svr.wait_until_ready();
  13659. Client cli("localhost", port);
  13660. auto handle = cli.open_stream("GET", "/will-close");
  13661. ASSERT_TRUE(handle.is_valid());
  13662. char buf[256];
  13663. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13664. EXPECT_GT(n, 0) << "First read should succeed";
  13665. // Signal server to close
  13666. close_now = true;
  13667. // Keep reading until error or EOF
  13668. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13669. // Keep reading
  13670. }
  13671. // Should get an error since content_length wasn't satisfied
  13672. if (n < 0) {
  13673. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13674. handle.get_read_error() == Error::Read)
  13675. << "Actual error: " << to_string(handle.get_read_error());
  13676. }
  13677. svr.stop();
  13678. t.join();
  13679. }
  13680. #ifdef CPPHTTPLIB_SSL_ENABLED
  13681. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13682. // Test that read timeout during SSL streaming is detected
  13683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13684. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13685. res.set_content_provider(
  13686. 1000, "text/plain",
  13687. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13688. if (offset < 100) {
  13689. std::string data(100, 'A');
  13690. sink.write(data.c_str(), data.size());
  13691. return true;
  13692. }
  13693. std::this_thread::sleep_for(std::chrono::seconds(3));
  13694. std::string data(900, 'B');
  13695. sink.write(data.c_str(), data.size());
  13696. return true;
  13697. });
  13698. });
  13699. auto port = 8093;
  13700. std::thread t([&]() { svr.listen("localhost", port); });
  13701. svr.wait_until_ready();
  13702. SSLClient cli("localhost", port);
  13703. cli.enable_server_certificate_verification(false);
  13704. cli.set_read_timeout(1, 0); // 1 second timeout
  13705. auto handle = cli.open_stream("GET", "/slow-stream");
  13706. ASSERT_TRUE(handle.is_valid());
  13707. char buf[256];
  13708. ssize_t total = 0;
  13709. ssize_t n;
  13710. bool got_error = false;
  13711. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13712. total += n;
  13713. }
  13714. if (n < 0) {
  13715. got_error = true;
  13716. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13717. handle.get_read_error() == Error::Read)
  13718. << "Actual error: " << to_string(handle.get_read_error());
  13719. }
  13720. EXPECT_TRUE(got_error || total < 1000)
  13721. << "Expected timeout but got all " << total << " bytes";
  13722. svr.stop();
  13723. t.join();
  13724. }
  13725. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13726. // Test SSL connection closed detection
  13727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13728. std::atomic<bool> close_now{false};
  13729. svr.Get("/will-close", [&](const Request &, Response &res) {
  13730. res.set_content_provider(
  13731. 10000, "text/plain",
  13732. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13733. if (offset < 100) {
  13734. std::string data(100, 'X');
  13735. sink.write(data.c_str(), data.size());
  13736. return true;
  13737. }
  13738. while (!close_now) {
  13739. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13740. }
  13741. return false;
  13742. });
  13743. });
  13744. auto port = 8094;
  13745. std::thread t([&]() { svr.listen("localhost", port); });
  13746. svr.wait_until_ready();
  13747. SSLClient cli("localhost", port);
  13748. cli.enable_server_certificate_verification(false);
  13749. auto handle = cli.open_stream("GET", "/will-close");
  13750. ASSERT_TRUE(handle.is_valid());
  13751. char buf[256];
  13752. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13753. EXPECT_GT(n, 0);
  13754. // Signal server to close
  13755. close_now = true;
  13756. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13757. // Keep reading
  13758. }
  13759. if (n < 0) {
  13760. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13761. handle.get_read_error() == Error::Read)
  13762. << "Actual error: " << to_string(handle.get_read_error());
  13763. }
  13764. svr.stop();
  13765. t.join();
  13766. }
  13767. #endif
  13768. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13769. using namespace httplib;
  13770. // Create a test file
  13771. const char *fname = "etag_testfile.txt";
  13772. const char *content = "etag-content";
  13773. {
  13774. std::ofstream ofs(fname);
  13775. ofs << content;
  13776. ASSERT_TRUE(ofs.good());
  13777. }
  13778. Server svr;
  13779. svr.set_mount_point("/static", ".");
  13780. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13781. svr.wait_until_ready();
  13782. Client cli(HOST, PORT);
  13783. // First request: should get 200 with ETag header
  13784. auto res1 = cli.Get("/static/etag_testfile.txt");
  13785. ASSERT_TRUE(res1);
  13786. ASSERT_EQ(200, res1->status);
  13787. ASSERT_TRUE(res1->has_header("ETag"));
  13788. std::string etag = res1->get_header_value("ETag");
  13789. EXPECT_FALSE(etag.empty());
  13790. // Verify ETag format: W/"hex-hex"
  13791. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13792. EXPECT_EQ('W', etag[0]);
  13793. EXPECT_EQ('/', etag[1]);
  13794. EXPECT_EQ('"', etag[2]);
  13795. EXPECT_EQ('"', etag.back());
  13796. // Exact match: expect 304 Not Modified
  13797. Headers h2 = {{"If-None-Match", etag}};
  13798. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13799. ASSERT_TRUE(res2);
  13800. EXPECT_EQ(304, res2->status);
  13801. // Wildcard match: expect 304 Not Modified
  13802. Headers h3 = {{"If-None-Match", "*"}};
  13803. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13804. ASSERT_TRUE(res3);
  13805. EXPECT_EQ(304, res3->status);
  13806. // Non-matching ETag: expect 200
  13807. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13808. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13809. ASSERT_TRUE(res4);
  13810. EXPECT_EQ(200, res4->status);
  13811. // Multiple ETags with one matching: expect 304
  13812. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13813. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13814. ASSERT_TRUE(res5);
  13815. EXPECT_EQ(304, res5->status);
  13816. svr.stop();
  13817. t.join();
  13818. std::remove(fname);
  13819. }
  13820. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13821. using namespace httplib;
  13822. Server svr;
  13823. svr.set_mount_point("/static", ".");
  13824. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13825. svr.wait_until_ready();
  13826. Client cli(HOST, PORT);
  13827. // Send If-None-Match: * to a non-existent file
  13828. Headers h = {{"If-None-Match", "*"}};
  13829. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13830. ASSERT_TRUE(res);
  13831. EXPECT_EQ(404, res->status);
  13832. svr.stop();
  13833. t.join();
  13834. }
  13835. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13836. using namespace httplib;
  13837. // Create a test file
  13838. const char *fname = "etag_boundary_testfile.txt";
  13839. const char *content = "boundary-test";
  13840. {
  13841. std::ofstream ofs(fname);
  13842. ofs << content;
  13843. ASSERT_TRUE(ofs.good());
  13844. }
  13845. Server svr;
  13846. svr.set_mount_point("/static", ".");
  13847. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13848. svr.wait_until_ready();
  13849. Client cli(HOST, PORT);
  13850. // Get the actual ETag
  13851. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13852. ASSERT_TRUE(res1);
  13853. ASSERT_EQ(200, res1->status);
  13854. ASSERT_TRUE(res1->has_header("ETag"));
  13855. std::string etag = res1->get_header_value("ETag");
  13856. // Test 1: Very long ETag value (longer than actual ETag)
  13857. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13858. Headers h1 = {{"If-None-Match", "W/"
  13859. "\"very-long-etag-value-that-is-much-longer-"
  13860. "than-the-actual-etag-value\""}};
  13861. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13862. ASSERT_TRUE(res2);
  13863. EXPECT_EQ(200, res2->status); // Should not match
  13864. // Test 2: Long string followed by wildcard
  13865. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13866. // string)
  13867. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13868. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13869. ASSERT_TRUE(res3);
  13870. EXPECT_EQ(304, res3->status); // Should match on "*"
  13871. // Test 3: Wildcard followed by long string
  13872. // Should match on "*" immediately and return 304
  13873. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13874. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13875. ASSERT_TRUE(res4);
  13876. EXPECT_EQ(304, res4->status); // Should match on "*"
  13877. // Test 4: Multiple long non-matching values
  13878. // Should NOT match and return 200 (test that all comparisons are safe)
  13879. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13880. "W/\"second-long-non-matching-value\", "
  13881. "W/\"third-long-non-matching-value\""}};
  13882. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13883. ASSERT_TRUE(res5);
  13884. EXPECT_EQ(200, res5->status); // Should not match
  13885. // Test 5: Single character that is not "*" (edge case)
  13886. Headers h5 = {{"If-None-Match", "X"}};
  13887. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13888. ASSERT_TRUE(res6);
  13889. EXPECT_EQ(200, res6->status); // Should not match
  13890. svr.stop();
  13891. t.join();
  13892. std::remove(fname);
  13893. }
  13894. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13895. using namespace httplib;
  13896. // Create a test file
  13897. const char *fname = "ims_testfile.txt";
  13898. const char *content = "if-modified-since-test";
  13899. {
  13900. std::ofstream ofs(fname);
  13901. ofs << content;
  13902. ASSERT_TRUE(ofs.good());
  13903. }
  13904. Server svr;
  13905. svr.set_mount_point("/static", ".");
  13906. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13907. svr.wait_until_ready();
  13908. Client cli(HOST, PORT);
  13909. // First request: should get 200 with Last-Modified header
  13910. auto res1 = cli.Get("/static/ims_testfile.txt");
  13911. ASSERT_TRUE(res1);
  13912. ASSERT_EQ(200, res1->status);
  13913. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13914. std::string last_modified = res1->get_header_value("Last-Modified");
  13915. EXPECT_FALSE(last_modified.empty());
  13916. // If-Modified-Since with same time: expect 304
  13917. Headers h2 = {{"If-Modified-Since", last_modified}};
  13918. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13919. ASSERT_TRUE(res2);
  13920. EXPECT_EQ(304, res2->status);
  13921. // If-Modified-Since with future time: expect 304
  13922. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13923. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13924. ASSERT_TRUE(res3);
  13925. EXPECT_EQ(304, res3->status);
  13926. // If-Modified-Since with past time: expect 200
  13927. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13928. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13929. ASSERT_TRUE(res4);
  13930. EXPECT_EQ(200, res4->status);
  13931. // If-None-Match takes precedence over If-Modified-Since
  13932. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13933. ASSERT_TRUE(res1->has_header("ETag"));
  13934. std::string etag = res1->get_header_value("ETag");
  13935. Headers h5 = {{"If-None-Match", etag},
  13936. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13937. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13938. ASSERT_TRUE(res5);
  13939. EXPECT_EQ(304, res5->status);
  13940. svr.stop();
  13941. t.join();
  13942. std::remove(fname);
  13943. }
  13944. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13945. using namespace httplib;
  13946. Server svr;
  13947. // Endpoint that returns compressible content
  13948. svr.Get("/compressible", [](const Request &, Response &res) {
  13949. // Return a large enough body to trigger compression
  13950. std::string body(1000, 'a');
  13951. res.set_content(body, "text/plain");
  13952. });
  13953. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13954. svr.wait_until_ready();
  13955. Client cli(HOST, PORT);
  13956. // Request with gzip support: should get Vary header when compressed
  13957. cli.set_compress(true);
  13958. auto res1 = cli.Get("/compressible");
  13959. ASSERT_TRUE(res1);
  13960. EXPECT_EQ(200, res1->status);
  13961. // If Content-Encoding is set, Vary should also be set
  13962. if (res1->has_header("Content-Encoding")) {
  13963. EXPECT_TRUE(res1->has_header("Vary"));
  13964. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13965. }
  13966. // Request without Accept-Encoding header: should not have compression
  13967. Headers h_no_compress;
  13968. auto res2 = cli.Get("/compressible", h_no_compress);
  13969. ASSERT_TRUE(res2);
  13970. EXPECT_EQ(200, res2->status);
  13971. // Verify Vary header is present when compression is applied
  13972. // (the exact behavior depends on server configuration)
  13973. svr.stop();
  13974. t.join();
  13975. }
  13976. TEST(ETagTest, IfRangeWithETag) {
  13977. using namespace httplib;
  13978. // Create a test file with known content
  13979. const char *fname = "if_range_testfile.txt";
  13980. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13981. {
  13982. std::ofstream ofs(fname);
  13983. ofs << content;
  13984. ASSERT_TRUE(ofs.good());
  13985. }
  13986. Server svr;
  13987. svr.set_mount_point("/static", ".");
  13988. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13989. svr.wait_until_ready();
  13990. Client cli(HOST, PORT);
  13991. // First request: get ETag
  13992. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13993. ASSERT_TRUE(res1);
  13994. ASSERT_EQ(200, res1->status);
  13995. ASSERT_TRUE(res1->has_header("ETag"));
  13996. std::string etag = res1->get_header_value("ETag");
  13997. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13998. // Since our server generates weak ETags (W/"..."), If-Range with our
  13999. // ETag should NOT result in partial content - it should return full content.
  14000. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14001. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14002. ASSERT_TRUE(res2);
  14003. // Weak ETag in If-Range -> full content (200), not partial (206)
  14004. EXPECT_EQ(200, res2->status);
  14005. EXPECT_EQ(content, res2->body);
  14006. EXPECT_FALSE(res2->has_header("Content-Range"));
  14007. // Range request with non-matching If-Range (ETag): should get 200 (full
  14008. // content)
  14009. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14010. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14011. ASSERT_TRUE(res3);
  14012. EXPECT_EQ(200, res3->status);
  14013. EXPECT_EQ(content, res3->body);
  14014. EXPECT_FALSE(res3->has_header("Content-Range"));
  14015. // Range request with strong ETag (hypothetical - our server doesn't generate
  14016. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14017. // should return full content)
  14018. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14019. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14020. ASSERT_TRUE(res4);
  14021. EXPECT_EQ(200, res4->status);
  14022. EXPECT_EQ(content, res4->body);
  14023. EXPECT_FALSE(res4->has_header("Content-Range"));
  14024. svr.stop();
  14025. t.join();
  14026. std::remove(fname);
  14027. }
  14028. TEST(ETagTest, IfRangeWithDate) {
  14029. using namespace httplib;
  14030. // Create a test file
  14031. const char *fname = "if_range_date_testfile.txt";
  14032. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14033. {
  14034. std::ofstream ofs(fname);
  14035. ofs << content;
  14036. ASSERT_TRUE(ofs.good());
  14037. }
  14038. Server svr;
  14039. svr.set_mount_point("/static", ".");
  14040. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14041. svr.wait_until_ready();
  14042. Client cli(HOST, PORT);
  14043. // First request: get Last-Modified
  14044. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14045. ASSERT_TRUE(res1);
  14046. ASSERT_EQ(200, res1->status);
  14047. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14048. std::string last_modified = res1->get_header_value("Last-Modified");
  14049. // Range request with matching If-Range (date): should get 206
  14050. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14051. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14052. ASSERT_TRUE(res2);
  14053. EXPECT_EQ(206, res2->status);
  14054. EXPECT_EQ("FGHIJ", res2->body);
  14055. // Range request with old If-Range date: should get 200 (full content)
  14056. Headers h3 = {{"Range", "bytes=5-9"},
  14057. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14058. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14059. ASSERT_TRUE(res3);
  14060. EXPECT_EQ(200, res3->status);
  14061. EXPECT_EQ(content, res3->body);
  14062. // Range request with future If-Range date: should get 206
  14063. Headers h4 = {{"Range", "bytes=0-4"},
  14064. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14065. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14066. ASSERT_TRUE(res4);
  14067. EXPECT_EQ(206, res4->status);
  14068. EXPECT_EQ("ABCDE", res4->body);
  14069. svr.stop();
  14070. t.join();
  14071. std::remove(fname);
  14072. }
  14073. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14074. using namespace httplib;
  14075. const char *fname = "etag_malformed.txt";
  14076. const char *content = "malformed-etag";
  14077. {
  14078. std::ofstream ofs(fname);
  14079. ofs << content;
  14080. ASSERT_TRUE(ofs.good());
  14081. }
  14082. Server svr;
  14083. svr.set_mount_point("/static", ".");
  14084. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14085. svr.wait_until_ready();
  14086. Client cli(HOST, PORT);
  14087. // baseline: should get 200 and an ETag
  14088. auto res1 = cli.Get("/static/etag_malformed.txt");
  14089. ASSERT_TRUE(res1);
  14090. ASSERT_EQ(200, res1->status);
  14091. ASSERT_TRUE(res1->has_header("ETag"));
  14092. // Malformed ETag value (missing quotes) should be treated as non-matching
  14093. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14094. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14095. ASSERT_TRUE(res_bad);
  14096. EXPECT_EQ(200, res_bad->status);
  14097. // Whitespace-only header value should be considered invalid / non-matching
  14098. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14099. "Host: localhost\r\n"
  14100. "If-None-Match: \r\n"
  14101. "Connection: close\r\n"
  14102. "\r\n";
  14103. std::string out;
  14104. ASSERT_TRUE(send_request(5, raw_req, &out));
  14105. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14106. svr.stop();
  14107. t.join();
  14108. std::remove(fname);
  14109. }
  14110. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14111. using namespace httplib;
  14112. const char *fname = "ims_invalid_format.txt";
  14113. const char *content = "ims-bad-format";
  14114. {
  14115. std::ofstream ofs(fname);
  14116. ofs << content;
  14117. ASSERT_TRUE(ofs.good());
  14118. }
  14119. Server svr;
  14120. svr.set_mount_point("/static", ".");
  14121. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14122. svr.wait_until_ready();
  14123. Client cli(HOST, PORT);
  14124. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14125. ASSERT_TRUE(res1);
  14126. ASSERT_EQ(200, res1->status);
  14127. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14128. // If-Modified-Since with invalid format should not result in 304
  14129. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14130. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14131. ASSERT_TRUE(res_bad);
  14132. EXPECT_EQ(200, res_bad->status);
  14133. // If-Range with invalid date format should be treated as mismatch -> full
  14134. // content (200)
  14135. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14136. {"If-Range", "invalid-date"}};
  14137. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14138. ASSERT_TRUE(res_ifrange);
  14139. EXPECT_EQ(200, res_ifrange->status);
  14140. svr.stop();
  14141. t.join();
  14142. std::remove(fname);
  14143. }
  14144. TEST(ETagTest, IfRangeWithMalformedETag) {
  14145. using namespace httplib;
  14146. const char *fname = "ifrange_malformed.txt";
  14147. const std::string content = "0123456789";
  14148. {
  14149. std::ofstream ofs(fname);
  14150. ofs << content;
  14151. ASSERT_TRUE(ofs.good());
  14152. }
  14153. Server svr;
  14154. svr.set_mount_point("/static", ".");
  14155. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14156. svr.wait_until_ready();
  14157. Client cli(HOST, PORT);
  14158. // First request: get ETag
  14159. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14160. ASSERT_TRUE(res1);
  14161. ASSERT_EQ(200, res1->status);
  14162. ASSERT_TRUE(res1->has_header("ETag"));
  14163. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14164. // full content (200)
  14165. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14166. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14167. ASSERT_TRUE(res2);
  14168. EXPECT_EQ(200, res2->status);
  14169. EXPECT_EQ(content, res2->body);
  14170. svr.stop();
  14171. t.join();
  14172. std::remove(fname);
  14173. }
  14174. TEST(ETagTest, ExtremeLargeDateValues) {
  14175. using namespace httplib;
  14176. const char *fname = "ims_extreme_date.txt";
  14177. const char *content = "ims-extreme-date";
  14178. {
  14179. std::ofstream ofs(fname);
  14180. ofs << content;
  14181. ASSERT_TRUE(ofs.good());
  14182. }
  14183. Server svr;
  14184. svr.set_mount_point("/static", ".");
  14185. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14186. svr.wait_until_ready();
  14187. Client cli(HOST, PORT);
  14188. auto res1 = cli.Get(std::string("/static/") + fname);
  14189. ASSERT_TRUE(res1);
  14190. ASSERT_EQ(200, res1->status);
  14191. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14192. // Extremely large year that may overflow date parsing routines.
  14193. Headers h_large_date = {
  14194. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14195. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14196. ASSERT_TRUE(res_bad);
  14197. // Expect server to treat this as invalid/mismatch and return full content
  14198. EXPECT_EQ(200, res_bad->status);
  14199. // If-Range with extremely large date should be treated as mismatch -> full
  14200. // content (200)
  14201. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14202. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14203. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14204. ASSERT_TRUE(res_ifrange);
  14205. EXPECT_EQ(200, res_ifrange->status);
  14206. svr.stop();
  14207. t.join();
  14208. std::remove(fname);
  14209. }
  14210. TEST(ETagTest, NegativeFileModificationTime) {
  14211. using namespace httplib;
  14212. const char *fname = "ims_negative_mtime.txt";
  14213. const std::string content = "negative-mtime";
  14214. {
  14215. std::ofstream ofs(fname);
  14216. ofs << content;
  14217. ASSERT_TRUE(ofs.good());
  14218. }
  14219. // Try to set file mtime to a negative value. This may fail on some
  14220. // platforms/filesystems; if it fails, the test will still verify server
  14221. // behaves safely by performing a regular conditional request.
  14222. #if defined(__APPLE__) || defined(__linux__)
  14223. bool set_negative = false;
  14224. do {
  14225. struct timeval times[2];
  14226. // access time: now
  14227. times[0].tv_sec = time(nullptr);
  14228. times[0].tv_usec = 0;
  14229. // modification time: negative (e.g., -1)
  14230. times[1].tv_sec = -1;
  14231. times[1].tv_usec = 0;
  14232. if (utimes(fname, times) == 0) { set_negative = true; }
  14233. } while (0);
  14234. #else
  14235. bool set_negative = false;
  14236. #endif
  14237. Server svr;
  14238. svr.set_mount_point("/static", ".");
  14239. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14240. svr.wait_until_ready();
  14241. Client cli(HOST, PORT);
  14242. auto res1 = cli.Get(std::string("/static/") + fname);
  14243. ASSERT_TRUE(res1);
  14244. ASSERT_EQ(200, res1->status);
  14245. bool has_last_modified = res1->has_header("Last-Modified");
  14246. std::string last_modified;
  14247. if (has_last_modified) {
  14248. last_modified = res1->get_header_value("Last-Modified");
  14249. }
  14250. if (set_negative) {
  14251. // If we successfully set a negative mtime, ensure server returns a
  14252. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14253. // with an old date and ensure server handles it without crash.
  14254. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14255. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14256. ASSERT_TRUE(res2);
  14257. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14258. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14259. } else {
  14260. // Could not set negative mtime on this platform; fall back to verifying
  14261. // that normal invalid/malformed dates are treated safely (non-304).
  14262. Headers h_bad_date = {
  14263. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14264. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14265. ASSERT_TRUE(res_bad);
  14266. EXPECT_EQ(200, res_bad->status);
  14267. }
  14268. svr.stop();
  14269. t.join();
  14270. std::remove(fname);
  14271. }
  14272. //==============================================================================
  14273. // SSE Parsing Tests
  14274. //==============================================================================
  14275. class SSEParsingTest : public ::testing::Test {
  14276. protected:
  14277. // Test helper that mimics SSE parsing behavior
  14278. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14279. int &retry_ms) {
  14280. // Blank line signals end of event
  14281. if (line.empty() || line == "\r") { return true; }
  14282. // Lines starting with ':' are comments (ignored)
  14283. if (!line.empty() && line[0] == ':') { return false; }
  14284. // Find the colon separator
  14285. auto colon_pos = line.find(':');
  14286. if (colon_pos == std::string::npos) {
  14287. // Line with no colon is treated as field name with empty value
  14288. return false;
  14289. }
  14290. std::string field = line.substr(0, colon_pos);
  14291. std::string value;
  14292. // Value starts after colon, skip optional single space
  14293. if (colon_pos + 1 < line.size()) {
  14294. size_t value_start = colon_pos + 1;
  14295. if (line[value_start] == ' ') { value_start++; }
  14296. value = line.substr(value_start);
  14297. // Remove trailing \r if present
  14298. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14299. }
  14300. // Handle known fields
  14301. if (field == "event") {
  14302. msg.event = value;
  14303. } else if (field == "data") {
  14304. // Multiple data lines are concatenated with newlines
  14305. if (!msg.data.empty()) { msg.data += "\n"; }
  14306. msg.data += value;
  14307. } else if (field == "id") {
  14308. // Empty id is valid (clears the last event ID)
  14309. msg.id = value;
  14310. } else if (field == "retry") {
  14311. // Parse retry interval in milliseconds
  14312. {
  14313. int v = 0;
  14314. auto res =
  14315. detail::from_chars(value.data(), value.data() + value.size(), v);
  14316. if (res.ec == std::errc{}) { retry_ms = v; }
  14317. }
  14318. }
  14319. // Unknown fields are ignored per SSE spec
  14320. return false;
  14321. }
  14322. };
  14323. // Test: Single-line data
  14324. TEST_F(SSEParsingTest, SingleLineData) {
  14325. sse::SSEMessage msg;
  14326. int retry_ms = 3000;
  14327. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14328. EXPECT_EQ(msg.data, "hello");
  14329. EXPECT_EQ(msg.event, "message");
  14330. // Blank line ends event
  14331. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14332. }
  14333. // Test: Multi-line data
  14334. TEST_F(SSEParsingTest, MultiLineData) {
  14335. sse::SSEMessage msg;
  14336. int retry_ms = 3000;
  14337. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14338. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14339. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14340. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14341. }
  14342. // Test: Custom event types
  14343. TEST_F(SSEParsingTest, CustomEventType) {
  14344. sse::SSEMessage msg;
  14345. int retry_ms = 3000;
  14346. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14347. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14348. EXPECT_EQ(msg.event, "update");
  14349. EXPECT_EQ(msg.data, "payload");
  14350. }
  14351. // Test: Event ID handling
  14352. TEST_F(SSEParsingTest, EventIdHandling) {
  14353. sse::SSEMessage msg;
  14354. int retry_ms = 3000;
  14355. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14356. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14357. EXPECT_EQ(msg.id, "12345");
  14358. }
  14359. // Test: Empty event ID (clears last event ID)
  14360. TEST_F(SSEParsingTest, EmptyEventId) {
  14361. sse::SSEMessage msg;
  14362. msg.id = "previous";
  14363. int retry_ms = 3000;
  14364. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14365. EXPECT_EQ(msg.id, "");
  14366. }
  14367. // Test: Retry field parsing
  14368. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14369. sse::SSEMessage msg;
  14370. int retry_ms = 3000;
  14371. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14372. EXPECT_EQ(retry_ms, 5000);
  14373. }
  14374. // Test: Invalid retry value
  14375. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14376. sse::SSEMessage msg;
  14377. int retry_ms = 3000;
  14378. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14379. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14380. }
  14381. // Test: Comments (lines starting with :)
  14382. TEST_F(SSEParsingTest, CommentsIgnored) {
  14383. sse::SSEMessage msg;
  14384. int retry_ms = 3000;
  14385. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14386. EXPECT_EQ(msg.data, "");
  14387. EXPECT_EQ(msg.event, "message");
  14388. }
  14389. // Test: Colon in value
  14390. TEST_F(SSEParsingTest, ColonInValue) {
  14391. sse::SSEMessage msg;
  14392. int retry_ms = 3000;
  14393. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14394. EXPECT_EQ(msg.data, "hello:world:test");
  14395. }
  14396. // Test: Line with no colon (field name only)
  14397. TEST_F(SSEParsingTest, FieldNameOnly) {
  14398. sse::SSEMessage msg;
  14399. int retry_ms = 3000;
  14400. // According to SSE spec, this is treated as field name with empty value
  14401. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14402. // Since we don't recognize "data" without colon, data should be empty
  14403. EXPECT_EQ(msg.data, "");
  14404. }
  14405. // Test: Trailing \r handling
  14406. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14407. sse::SSEMessage msg;
  14408. int retry_ms = 3000;
  14409. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14410. EXPECT_EQ(msg.data, "hello");
  14411. }
  14412. // Test: Unknown fields ignored
  14413. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14414. sse::SSEMessage msg;
  14415. int retry_ms = 3000;
  14416. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14417. EXPECT_EQ(msg.data, "");
  14418. EXPECT_EQ(msg.event, "message");
  14419. }
  14420. // Test: Space after colon is optional
  14421. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14422. sse::SSEMessage msg1, msg2;
  14423. int retry_ms = 3000;
  14424. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14425. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14426. EXPECT_EQ(msg1.data, "hello");
  14427. EXPECT_EQ(msg2.data, "hello");
  14428. }
  14429. // Test: SSEMessage clear
  14430. TEST_F(SSEParsingTest, MessageClear) {
  14431. sse::SSEMessage msg;
  14432. msg.event = "custom";
  14433. msg.data = "some data";
  14434. msg.id = "123";
  14435. msg.clear();
  14436. EXPECT_EQ(msg.event, "message");
  14437. EXPECT_EQ(msg.data, "");
  14438. EXPECT_EQ(msg.id, "");
  14439. }
  14440. // Test: Complete event parsing
  14441. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14442. sse::SSEMessage msg;
  14443. int retry_ms = 3000;
  14444. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14445. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14446. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14447. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14448. // Blank line ends event
  14449. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14450. EXPECT_EQ(msg.event, "notification");
  14451. EXPECT_EQ(msg.id, "evt-42");
  14452. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14453. EXPECT_EQ(retry_ms, 1000);
  14454. }
  14455. //==============================================================================
  14456. // Integration Tests with Server
  14457. //==============================================================================
  14458. class SSEIntegrationTest : public ::testing::Test {
  14459. protected:
  14460. void SetUp() override {
  14461. stop_server_.store(false);
  14462. events_.clear();
  14463. server_ = httplib::detail::make_unique<Server>();
  14464. setup_server();
  14465. start_server();
  14466. }
  14467. void TearDown() override {
  14468. stop_server_.store(true);
  14469. event_cv_.notify_all();
  14470. server_->stop();
  14471. if (server_thread_.joinable()) { server_thread_.join(); }
  14472. }
  14473. void setup_server() {
  14474. // Simple SSE endpoint
  14475. server_->Get("/events", [this](const Request &req, Response &res) {
  14476. auto last_id = req.get_header_value("Last-Event-ID");
  14477. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14478. res.set_chunked_content_provider(
  14479. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14480. std::unique_lock<std::mutex> lock(event_mutex_);
  14481. if (event_cv_.wait_for(
  14482. lock, std::chrono::milliseconds(200), [this] {
  14483. return !events_.empty() || stop_server_.load();
  14484. })) {
  14485. if (stop_server_.load()) { return false; }
  14486. if (!events_.empty()) {
  14487. std::string event = events_.front();
  14488. events_.erase(events_.begin());
  14489. sink.write(event.data(), event.size());
  14490. return true;
  14491. }
  14492. }
  14493. return !stop_server_.load();
  14494. });
  14495. });
  14496. // Endpoint that returns error
  14497. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14498. res.status = 500;
  14499. res.set_content("Internal Server Error", "text/plain");
  14500. });
  14501. // Endpoint for custom event types
  14502. server_->Get("/custom-events", [](const Request &, Response &res) {
  14503. res.set_chunked_content_provider(
  14504. "text/event-stream", [](size_t offset, DataSink &sink) {
  14505. if (offset == 0) {
  14506. std::string event = "event: update\ndata: updated\n\n"
  14507. "event: delete\ndata: deleted\n\n";
  14508. sink.write(event.data(), event.size());
  14509. }
  14510. return false; // End stream after sending
  14511. });
  14512. });
  14513. }
  14514. void start_server() {
  14515. port_ = server_->bind_to_any_port(HOST);
  14516. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14517. // Wait for server to start
  14518. while (!server_->is_running()) {
  14519. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14520. }
  14521. }
  14522. int get_port() const { return port_; }
  14523. void send_event(const std::string &event) {
  14524. std::lock_guard<std::mutex> lock(event_mutex_);
  14525. events_.push_back(event);
  14526. event_cv_.notify_all();
  14527. }
  14528. std::unique_ptr<Server> server_;
  14529. std::thread server_thread_;
  14530. std::mutex event_mutex_;
  14531. std::condition_variable event_cv_;
  14532. std::vector<std::string> events_;
  14533. std::atomic<bool> stop_server_{false};
  14534. std::string last_received_event_id_;
  14535. int port_ = 0;
  14536. };
  14537. // Test: Successful connection and on_open callback
  14538. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14539. // Add a simple endpoint that sends one event and closes
  14540. server_->Get("/simple-event", [](const Request &, Response &res) {
  14541. res.set_chunked_content_provider(
  14542. "text/event-stream", [](size_t offset, DataSink &sink) {
  14543. if (offset == 0) {
  14544. std::string event = "data: hello\n\n";
  14545. sink.write(event.data(), event.size());
  14546. }
  14547. return false; // Close stream after sending
  14548. });
  14549. });
  14550. Client client("localhost", get_port());
  14551. sse::SSEClient sse(client, "/simple-event");
  14552. std::atomic<bool> open_called{false};
  14553. std::atomic<bool> message_received{false};
  14554. sse.on_open([&open_called]() { open_called.store(true); });
  14555. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14556. if (msg.data == "hello") { message_received.store(true); }
  14557. });
  14558. sse.set_reconnect_interval(100);
  14559. sse.set_max_reconnect_attempts(1);
  14560. // Start async
  14561. sse.start_async();
  14562. // Wait for message to be processed
  14563. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14564. sse.stop();
  14565. EXPECT_TRUE(open_called.load());
  14566. EXPECT_TRUE(message_received.load());
  14567. }
  14568. // Test: on_message callback
  14569. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14570. // Endpoint that sends multiple events then closes
  14571. server_->Get("/multi-event", [](const Request &, Response &res) {
  14572. res.set_chunked_content_provider(
  14573. "text/event-stream", [](size_t offset, DataSink &sink) {
  14574. if (offset == 0) {
  14575. std::string events = "data: message1\n\ndata: message2\n\n";
  14576. sink.write(events.data(), events.size());
  14577. }
  14578. return false;
  14579. });
  14580. });
  14581. Client client("localhost", get_port());
  14582. sse::SSEClient sse(client, "/multi-event");
  14583. std::vector<std::string> received_messages;
  14584. std::mutex messages_mutex;
  14585. sse.on_message([&](const sse::SSEMessage &msg) {
  14586. std::lock_guard<std::mutex> lock(messages_mutex);
  14587. received_messages.push_back(msg.data);
  14588. });
  14589. sse.set_reconnect_interval(100);
  14590. sse.set_max_reconnect_attempts(1);
  14591. sse.start_async();
  14592. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14593. sse.stop();
  14594. std::lock_guard<std::mutex> lock(messages_mutex);
  14595. EXPECT_GE(received_messages.size(), 2u);
  14596. if (received_messages.size() >= 2) {
  14597. EXPECT_EQ(received_messages[0], "message1");
  14598. EXPECT_EQ(received_messages[1], "message2");
  14599. }
  14600. }
  14601. // Test: on_event for specific types
  14602. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14603. Client client("localhost", get_port());
  14604. sse::SSEClient sse(client, "/custom-events");
  14605. std::atomic<bool> update_received{false};
  14606. std::atomic<bool> delete_received{false};
  14607. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14608. if (msg.data == "updated") { update_received.store(true); }
  14609. });
  14610. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14611. if (msg.data == "deleted") { delete_received.store(true); }
  14612. });
  14613. sse.set_max_reconnect_attempts(1);
  14614. sse.start_async();
  14615. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14616. sse.stop();
  14617. EXPECT_TRUE(update_received.load());
  14618. EXPECT_TRUE(delete_received.load());
  14619. }
  14620. // Test: on_error callback on connection failure
  14621. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14622. // Connect to a non-existent port
  14623. Client client("localhost", 59999);
  14624. sse::SSEClient sse(client, "/events");
  14625. std::atomic<bool> error_called{false};
  14626. Error received_error = Error::Success;
  14627. sse.on_error([&](Error err) {
  14628. error_called.store(true);
  14629. received_error = err;
  14630. });
  14631. sse.set_reconnect_interval(50);
  14632. sse.set_max_reconnect_attempts(1);
  14633. sse.start_async();
  14634. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14635. sse.stop();
  14636. EXPECT_TRUE(error_called.load());
  14637. EXPECT_NE(received_error, Error::Success);
  14638. }
  14639. // Test: Last-Event-ID header sent on reconnect
  14640. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14641. // Endpoint that sends event with ID
  14642. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14643. res.set_chunked_content_provider(
  14644. "text/event-stream", [](size_t offset, DataSink &sink) {
  14645. if (offset == 0) {
  14646. std::string event = "id: evt-123\ndata: test\n\n";
  14647. sink.write(event.data(), event.size());
  14648. }
  14649. return false;
  14650. });
  14651. });
  14652. Client client("localhost", get_port());
  14653. sse::SSEClient sse(client, "/event-with-id");
  14654. std::atomic<bool> id_received{false};
  14655. sse.on_message([&](const sse::SSEMessage &msg) {
  14656. if (!msg.id.empty()) { id_received.store(true); }
  14657. });
  14658. sse.set_reconnect_interval(100);
  14659. sse.set_max_reconnect_attempts(1);
  14660. sse.start_async();
  14661. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14662. sse.stop();
  14663. EXPECT_TRUE(id_received.load());
  14664. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14665. }
  14666. // Test: Manual stop
  14667. TEST_F(SSEIntegrationTest, ManualStop) {
  14668. // Endpoint that sends one event and stays open briefly
  14669. std::atomic<bool> handler_running{true};
  14670. server_->Get("/stay-open", [&handler_running](const Request &,
  14671. Response &res) {
  14672. res.set_chunked_content_provider(
  14673. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14674. if (offset == 0) {
  14675. std::string event = "data: connected\n\n";
  14676. sink.write(event.data(), event.size());
  14677. }
  14678. // Keep connection open while handler_running is true
  14679. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14680. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14681. }
  14682. return false;
  14683. });
  14684. });
  14685. Client client("localhost", get_port());
  14686. sse::SSEClient sse(client, "/stay-open");
  14687. std::atomic<bool> connected{false};
  14688. sse.on_open([&connected]() { connected.store(true); });
  14689. sse.set_reconnect_interval(100);
  14690. sse.set_max_reconnect_attempts(1);
  14691. sse.start_async();
  14692. // Wait for connection to establish
  14693. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14694. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14695. }
  14696. EXPECT_TRUE(connected.load());
  14697. EXPECT_TRUE(sse.is_connected());
  14698. // Signal handler to stop
  14699. handler_running.store(false);
  14700. // Stop SSE client
  14701. sse.stop();
  14702. EXPECT_FALSE(sse.is_connected());
  14703. }
  14704. // Test: SSEClient with custom headers
  14705. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14706. // Setup a server endpoint that checks for custom header
  14707. std::atomic<bool> header_received{false};
  14708. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14709. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14710. header_received.store(true);
  14711. }
  14712. res.set_chunked_content_provider("text/event-stream",
  14713. [](size_t, DataSink &) { return false; });
  14714. });
  14715. Client client("localhost", get_port());
  14716. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14717. sse::SSEClient sse(client, "/header-check", headers);
  14718. sse.set_max_reconnect_attempts(1);
  14719. sse.start_async();
  14720. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14721. sse.stop();
  14722. EXPECT_TRUE(header_received.load());
  14723. }
  14724. // Test: Reconnect interval configuration
  14725. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14726. Client client("localhost", get_port());
  14727. sse::SSEClient sse(client, "/events");
  14728. auto &result = sse.set_reconnect_interval(500);
  14729. // Builder pattern should return reference to self
  14730. EXPECT_EQ(&result, &sse);
  14731. }
  14732. // Test: Max reconnect attempts
  14733. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14734. // Connect to non-existent port to force reconnects
  14735. Client client("localhost", 59998);
  14736. sse::SSEClient sse(client, "/events");
  14737. std::atomic<int> error_count{0};
  14738. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14739. sse.set_reconnect_interval(50);
  14740. sse.set_max_reconnect_attempts(2);
  14741. auto start = std::chrono::steady_clock::now();
  14742. sse.start(); // Blocking call
  14743. auto end = std::chrono::steady_clock::now();
  14744. // Should have stopped after 2 failed attempts
  14745. EXPECT_GE(error_count.load(), 2);
  14746. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14747. auto duration =
  14748. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14749. #ifdef _WIN32
  14750. // Windows is much slower for socket connection failures
  14751. EXPECT_LT(duration.count(), 7000);
  14752. #else
  14753. EXPECT_LT(duration.count(), 1000);
  14754. #endif
  14755. }
  14756. // Test: Multi-line data in integration
  14757. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14758. // Endpoint with multi-line data
  14759. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14760. res.set_chunked_content_provider(
  14761. "text/event-stream", [](size_t offset, DataSink &sink) {
  14762. if (offset == 0) {
  14763. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14764. sink.write(event.data(), event.size());
  14765. }
  14766. return false;
  14767. });
  14768. });
  14769. Client client("localhost", get_port());
  14770. sse::SSEClient sse(client, "/multiline-data");
  14771. std::string received_data;
  14772. std::mutex data_mutex;
  14773. sse.on_message([&](const sse::SSEMessage &msg) {
  14774. std::lock_guard<std::mutex> lock(data_mutex);
  14775. received_data = msg.data;
  14776. });
  14777. sse.set_reconnect_interval(100);
  14778. sse.set_max_reconnect_attempts(1);
  14779. sse.start_async();
  14780. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14781. sse.stop();
  14782. std::lock_guard<std::mutex> lock(data_mutex);
  14783. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14784. }
  14785. // Test: Auto-reconnect after server disconnection
  14786. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14787. std::atomic<int> connection_count{0};
  14788. std::atomic<int> message_count{0};
  14789. // Endpoint that sends one event and closes, forcing reconnect
  14790. server_->Get("/reconnect-test",
  14791. [&connection_count](const Request &, Response &res) {
  14792. connection_count.fetch_add(1);
  14793. res.set_chunked_content_provider(
  14794. "text/event-stream", [](size_t offset, DataSink &sink) {
  14795. if (offset == 0) {
  14796. std::string event = "data: hello\n\n";
  14797. sink.write(event.data(), event.size());
  14798. }
  14799. return false; // Close connection after sending
  14800. });
  14801. });
  14802. Client client("localhost", get_port());
  14803. sse::SSEClient sse(client, "/reconnect-test");
  14804. sse.on_message([&message_count](const sse::SSEMessage &) {
  14805. message_count.fetch_add(1);
  14806. });
  14807. sse.set_reconnect_interval(100);
  14808. sse.set_max_reconnect_attempts(3);
  14809. sse.start_async();
  14810. // Wait long enough for multiple reconnects
  14811. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14812. sse.stop();
  14813. // Should have connected multiple times (initial + reconnects)
  14814. EXPECT_GE(connection_count.load(), 2);
  14815. // Should have received messages from multiple connections
  14816. EXPECT_GE(message_count.load(), 2);
  14817. }
  14818. // Test: Last-Event-ID sent on reconnect
  14819. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14820. std::atomic<int> connection_count{0};
  14821. std::vector<std::string> received_last_event_ids;
  14822. std::mutex id_mutex;
  14823. // Endpoint that checks Last-Event-ID header and sends event with ID
  14824. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14825. int conn = connection_count.fetch_add(1);
  14826. // Capture the Last-Event-ID header from each connection
  14827. {
  14828. std::lock_guard<std::mutex> lock(id_mutex);
  14829. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14830. }
  14831. res.set_chunked_content_provider(
  14832. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14833. if (offset == 0) {
  14834. std::string event =
  14835. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14836. sink.write(event.data(), event.size());
  14837. }
  14838. return false;
  14839. });
  14840. });
  14841. Client client("localhost", get_port());
  14842. sse::SSEClient sse(client, "/reconnect-with-id");
  14843. sse.set_reconnect_interval(100);
  14844. sse.set_max_reconnect_attempts(3);
  14845. sse.start_async();
  14846. // Wait for at least 2 connections
  14847. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14848. sse.stop();
  14849. // Verify behavior
  14850. std::lock_guard<std::mutex> lock(id_mutex);
  14851. EXPECT_GE(received_last_event_ids.size(), 2u);
  14852. // First connection should have no Last-Event-ID
  14853. if (!received_last_event_ids.empty()) {
  14854. EXPECT_EQ(received_last_event_ids[0], "");
  14855. }
  14856. // Second connection should have Last-Event-ID from first connection
  14857. if (received_last_event_ids.size() >= 2) {
  14858. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14859. }
  14860. }
  14861. // Test: set_headers updates headers used on reconnect
  14862. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14863. std::vector<std::string> received_tokens;
  14864. std::mutex token_mutex;
  14865. // Endpoint that captures Authorization header
  14866. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14867. {
  14868. std::lock_guard<std::mutex> lock(token_mutex);
  14869. received_tokens.push_back(req.get_header_value("Authorization"));
  14870. }
  14871. res.set_chunked_content_provider(
  14872. "text/event-stream", [](size_t offset, DataSink &sink) {
  14873. if (offset == 0) {
  14874. std::string event = "data: hello\n\n";
  14875. sink.write(event.data(), event.size());
  14876. }
  14877. return false; // Close connection to trigger reconnect
  14878. });
  14879. });
  14880. Client client("localhost", get_port());
  14881. Headers headers = {{"Authorization", "Bearer old-token"}};
  14882. sse::SSEClient sse(client, "/auth-check", headers);
  14883. // Update headers on each successful connection
  14884. sse.on_open(
  14885. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14886. sse.set_reconnect_interval(100);
  14887. sse.set_max_reconnect_attempts(3);
  14888. sse.start_async();
  14889. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14890. sse.stop();
  14891. std::lock_guard<std::mutex> lock(token_mutex);
  14892. ASSERT_GE(received_tokens.size(), 2u);
  14893. // First connection uses original header
  14894. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14895. // Second connection uses updated header from set_headers
  14896. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14897. }
  14898. // Test: 401 allows reconnection (so on_error can refresh headers)
  14899. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14900. std::atomic<int> connection_count{0};
  14901. // Endpoint: returns 401 on first attempt, 200 on second
  14902. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14903. int conn = connection_count.fetch_add(1);
  14904. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14905. res.status = StatusCode::Unauthorized_401;
  14906. res.set_content("Unauthorized", "text/plain");
  14907. return;
  14908. }
  14909. res.set_chunked_content_provider(
  14910. "text/event-stream", [](size_t offset, DataSink &sink) {
  14911. if (offset == 0) {
  14912. std::string event = "data: authenticated\n\n";
  14913. sink.write(event.data(), event.size());
  14914. }
  14915. return false;
  14916. });
  14917. });
  14918. Client client("localhost", get_port());
  14919. Headers headers = {{"Authorization", "Bearer expired"}};
  14920. sse::SSEClient sse(client, "/auth-retry", headers);
  14921. std::atomic<bool> message_received{false};
  14922. // Refresh token on error
  14923. sse.on_error(
  14924. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14925. sse.on_message([&](const sse::SSEMessage &msg) {
  14926. if (msg.data == "authenticated") { message_received.store(true); }
  14927. });
  14928. sse.set_reconnect_interval(100);
  14929. sse.set_max_reconnect_attempts(3);
  14930. sse.start_async();
  14931. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14932. sse.stop();
  14933. // Should have reconnected after 401 and succeeded with new token
  14934. EXPECT_GE(connection_count.load(), 2);
  14935. EXPECT_TRUE(message_received.load());
  14936. }
  14937. TEST(Issue2318Test, EmptyHostString) {
  14938. {
  14939. httplib::Client cli_empty("", PORT);
  14940. auto res = cli_empty.Get("/");
  14941. ASSERT_FALSE(res);
  14942. EXPECT_EQ(httplib::Error::Connection, res.error());
  14943. }
  14944. {
  14945. httplib::Client cli(" ", PORT);
  14946. auto res = cli.Get("/");
  14947. ASSERT_FALSE(res);
  14948. EXPECT_EQ(httplib::Error::Connection, res.error());
  14949. }
  14950. }
  14951. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14952. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14953. Server svr;
  14954. // Set a small payload limit (1KB)
  14955. svr.set_payload_max_length(1024);
  14956. svr.Post("/test", [&](const Request &req, Response &res) {
  14957. res.set_content("Body size: " + std::to_string(req.body.size()),
  14958. "text/plain");
  14959. });
  14960. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14961. auto se = detail::scope_exit([&] {
  14962. svr.stop();
  14963. listen_thread.join();
  14964. });
  14965. svr.wait_until_ready();
  14966. // Create data that compresses well but exceeds limit when decompressed
  14967. // 8KB of repeated null bytes compresses to a very small size
  14968. std::string original_data(8 * 1024, '\0');
  14969. // Compress the data using gzip
  14970. std::string compressed_data;
  14971. detail::gzip_compressor compressor;
  14972. compressor.compress(original_data.data(), original_data.size(), true,
  14973. [&](const char *data, size_t size) {
  14974. compressed_data.append(data, size);
  14975. return true;
  14976. });
  14977. // Verify compression worked (compressed should be much smaller)
  14978. ASSERT_LT(compressed_data.size(), original_data.size());
  14979. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14980. // Send compressed data with Content-Encoding: gzip
  14981. Client cli(HOST, PORT);
  14982. Headers headers = {{"Content-Encoding", "gzip"}};
  14983. auto res =
  14984. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14985. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14986. ASSERT_TRUE(res);
  14987. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14988. }
  14989. #endif
  14990. // ============================================================================
  14991. // OpenSSL-Specific Tests
  14992. // ============================================================================
  14993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14994. X509 *readCertificate(const std::string &strFileName) {
  14995. std::ifstream inStream(strFileName);
  14996. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14997. std::istreambuf_iterator<char>());
  14998. if (strCertPEM.empty()) return (nullptr);
  14999. BIO *pbCert = BIO_new(BIO_s_mem());
  15000. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15001. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15002. BIO_free(pbCert);
  15003. return (pCert);
  15004. }
  15005. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15006. std::ifstream inStream(strFileName);
  15007. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15008. std::istreambuf_iterator<char>());
  15009. if (strPrivateKeyPEM.empty()) return (nullptr);
  15010. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15011. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15012. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15013. BIO_free(pbPrivKey);
  15014. return (pPrivateKey);
  15015. }
  15016. TEST(BindServerTest, UpdateCerts) {
  15017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15018. int port = svr.bind_to_any_port("0.0.0.0");
  15019. ASSERT_TRUE(svr.is_valid());
  15020. ASSERT_TRUE(port > 0);
  15021. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15022. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15023. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15024. ASSERT_TRUE(cert != nullptr);
  15025. ASSERT_TRUE(ca_cert != nullptr);
  15026. ASSERT_TRUE(key != nullptr);
  15027. X509_STORE *cert_store = X509_STORE_new();
  15028. X509_STORE_add_cert(cert_store, ca_cert);
  15029. // svr.update_certs(cert, key, cert_store); // deprecated
  15030. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15031. CLIENT_CA_CERT_FILE);
  15032. ASSERT_TRUE(svr.is_valid());
  15033. svr.stop();
  15034. X509_STORE_free(cert_store);
  15035. X509_free(cert);
  15036. X509_free(ca_cert);
  15037. EVP_PKEY_free(key);
  15038. }
  15039. // Test that update_certs() updates client CA list correctly
  15040. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15041. // Start with file-based constructor
  15042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15043. ASSERT_TRUE(svr.is_valid());
  15044. // Initially no client CA list should be set
  15045. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15046. ASSERT_TRUE(ssl_ctx != nullptr);
  15047. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15048. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15049. EXPECT_EQ(0, count_before);
  15050. // Now update with client CA (PEM string)
  15051. std::string cert_pem, key_pem, ca_pem;
  15052. read_file(SERVER_CERT_FILE, cert_pem);
  15053. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15054. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15055. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15056. ASSERT_TRUE(svr.is_valid());
  15057. // Now client CA list should be set
  15058. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15059. ASSERT_TRUE(ca_list_after != nullptr);
  15060. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15061. }
  15062. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15063. // Test that the file-path SSLServer constructor properly sets the client CA
  15064. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15066. ASSERT_TRUE(svr.is_valid());
  15067. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15068. ASSERT_TRUE(ssl_ctx != nullptr);
  15069. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15070. ASSERT_TRUE(ca_list != nullptr);
  15071. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15072. }
  15073. #endif
  15074. // ============================================================================
  15075. // MbedTLS-Specific Tests
  15076. // ============================================================================
  15077. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15078. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15079. using namespace httplib::tls;
  15080. // Track if callback was invoked
  15081. bool callback_invoked = false;
  15082. // The callback receives void* ctx which is actually MbedTlsContext*
  15083. // We can access the mbedtls_ssl_config via the context
  15084. auto setup_callback = [&callback_invoked](void *ctx) {
  15085. callback_invoked = true;
  15086. // Cast to MbedTlsContext* to access the ssl config
  15087. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15088. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15089. // Use static variables to hold certificate data (simplified for test)
  15090. static mbedtls_x509_crt own_cert;
  15091. static mbedtls_pk_context own_key;
  15092. static mbedtls_x509_crt ca_chain;
  15093. static bool initialized = false;
  15094. if (!initialized) {
  15095. mbedtls_x509_crt_init(&own_cert);
  15096. mbedtls_pk_init(&own_key);
  15097. mbedtls_x509_crt_init(&ca_chain);
  15098. // Load server certificate
  15099. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15100. return false;
  15101. }
  15102. // Load server private key
  15103. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15104. #if MBEDTLS_VERSION_MAJOR >= 3
  15105. ,
  15106. mbedtls_ctr_drbg_random, nullptr
  15107. #endif
  15108. ) != 0) {
  15109. return false;
  15110. }
  15111. // Load CA chain for client verification
  15112. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15113. return false;
  15114. }
  15115. initialized = true;
  15116. }
  15117. // Configure the SSL config
  15118. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15119. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15120. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15121. // Set minimum TLS version using mbedTLS native API
  15122. #if MBEDTLS_VERSION_MAJOR >= 3
  15123. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15124. #else
  15125. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15126. MBEDTLS_SSL_MINOR_VERSION_3);
  15127. #endif
  15128. return true;
  15129. };
  15130. SSLServer svr(setup_callback);
  15131. ASSERT_TRUE(svr.is_valid());
  15132. ASSERT_TRUE(callback_invoked);
  15133. svr.Get("/test", [&](const Request &req, Response &res) {
  15134. res.set_content("test", "text/plain");
  15135. auto cert = req.peer_cert();
  15136. ASSERT_TRUE(static_cast<bool>(cert));
  15137. auto common_name = cert.subject_cn();
  15138. EXPECT_EQ("Common Name", common_name);
  15139. });
  15140. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15141. auto se = detail::scope_exit([&] {
  15142. svr.stop();
  15143. t.join();
  15144. ASSERT_FALSE(svr.is_running());
  15145. });
  15146. svr.wait_until_ready();
  15147. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15148. cli.enable_server_certificate_verification(false);
  15149. cli.set_connection_timeout(30);
  15150. auto res = cli.Get("/test");
  15151. ASSERT_TRUE(res);
  15152. ASSERT_EQ(StatusCode::OK_200, res->status);
  15153. }
  15154. #endif
  15155. // WebSocket Tests
  15156. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15157. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15158. // defining the meaning of these bits has been negotiated.
  15159. auto make_frame = [](uint8_t first_byte) {
  15160. std::string frame;
  15161. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15162. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15163. frame += "Hello";
  15164. return frame;
  15165. };
  15166. // RSV1 set (0x40)
  15167. {
  15168. detail::BufferStream strm;
  15169. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15170. ws::Opcode opcode;
  15171. std::string payload;
  15172. bool fin;
  15173. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15174. false, 1024));
  15175. }
  15176. // RSV2 set (0x20)
  15177. {
  15178. detail::BufferStream strm;
  15179. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15180. ws::Opcode opcode;
  15181. std::string payload;
  15182. bool fin;
  15183. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15184. false, 1024));
  15185. }
  15186. // RSV3 set (0x10)
  15187. {
  15188. detail::BufferStream strm;
  15189. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15190. ws::Opcode opcode;
  15191. std::string payload;
  15192. bool fin;
  15193. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15194. false, 1024));
  15195. }
  15196. // No RSV bits set - should succeed
  15197. {
  15198. detail::BufferStream strm;
  15199. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15200. ws::Opcode opcode;
  15201. std::string payload;
  15202. bool fin;
  15203. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15204. false, 1024));
  15205. EXPECT_EQ(ws::Opcode::Text, opcode);
  15206. EXPECT_EQ("Hello", payload);
  15207. EXPECT_TRUE(fin);
  15208. }
  15209. }
  15210. TEST(WebSocketTest, ControlFrameValidation) {
  15211. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15212. // payload length <= 125.
  15213. // Ping with FIN=0 - must be rejected
  15214. {
  15215. detail::BufferStream strm;
  15216. std::string frame;
  15217. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15218. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15219. strm.write(frame.data(), frame.size());
  15220. ws::Opcode opcode;
  15221. std::string payload;
  15222. bool fin;
  15223. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15224. false, 1024));
  15225. }
  15226. // Close with FIN=0 - must be rejected
  15227. {
  15228. detail::BufferStream strm;
  15229. std::string frame;
  15230. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15231. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15232. strm.write(frame.data(), frame.size());
  15233. ws::Opcode opcode;
  15234. std::string payload;
  15235. bool fin;
  15236. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15237. false, 1024));
  15238. }
  15239. // Ping with payload_len=126 (extended length) - must be rejected
  15240. {
  15241. detail::BufferStream strm;
  15242. std::string frame;
  15243. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15244. frame += static_cast<char>(126); // payload_len=126 (>125)
  15245. frame += static_cast<char>(0x00); // extended length high byte
  15246. frame += static_cast<char>(126); // extended length low byte
  15247. frame += std::string(126, 'x');
  15248. strm.write(frame.data(), frame.size());
  15249. ws::Opcode opcode;
  15250. std::string payload;
  15251. bool fin;
  15252. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15253. false, 1024));
  15254. }
  15255. // Ping with FIN=1 and payload_len=125 - should succeed
  15256. {
  15257. detail::BufferStream strm;
  15258. std::string frame;
  15259. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15260. frame += static_cast<char>(125); // payload_len=125
  15261. frame += std::string(125, 'x');
  15262. strm.write(frame.data(), frame.size());
  15263. ws::Opcode opcode;
  15264. std::string payload;
  15265. bool fin;
  15266. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15267. false, 1024));
  15268. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15269. EXPECT_EQ(125u, payload.size());
  15270. EXPECT_TRUE(fin);
  15271. }
  15272. }
  15273. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15274. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15275. // length MUST be 0.
  15276. // MSB set - must be rejected
  15277. {
  15278. detail::BufferStream strm;
  15279. std::string frame;
  15280. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15281. frame += static_cast<char>(127); // 64-bit extended length
  15282. frame += static_cast<char>(0x80); // MSB set (invalid)
  15283. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15284. strm.write(frame.data(), frame.size());
  15285. ws::Opcode opcode;
  15286. std::string payload;
  15287. bool fin;
  15288. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15289. false, 1024));
  15290. }
  15291. // MSB clear - should pass length parsing (will be rejected by max_len,
  15292. // but that's a different check; use a small length to verify)
  15293. {
  15294. detail::BufferStream strm;
  15295. std::string frame;
  15296. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15297. frame += static_cast<char>(127); // 64-bit extended length
  15298. frame += std::string(7, '\0'); // high bytes = 0
  15299. frame += static_cast<char>(0x03); // length = 3
  15300. frame += "abc";
  15301. strm.write(frame.data(), frame.size());
  15302. ws::Opcode opcode;
  15303. std::string payload;
  15304. bool fin;
  15305. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15306. false, 1024));
  15307. EXPECT_EQ(ws::Opcode::Text, opcode);
  15308. EXPECT_EQ("abc", payload);
  15309. }
  15310. }
  15311. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15312. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15313. // Valid UTF-8
  15314. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15315. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15316. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15317. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15318. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15319. // Invalid UTF-8
  15320. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15321. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15322. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15323. EXPECT_FALSE(
  15324. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15325. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15326. }
  15327. TEST(WebSocketTest, ConnectAndDisconnect) {
  15328. Server svr;
  15329. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15330. std::string msg;
  15331. while (ws.read(msg)) {}
  15332. });
  15333. auto port = svr.bind_to_any_port(HOST);
  15334. std::thread t([&]() { svr.listen_after_bind(); });
  15335. svr.wait_until_ready();
  15336. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15337. ASSERT_TRUE(client.connect());
  15338. EXPECT_TRUE(client.is_open());
  15339. client.close();
  15340. EXPECT_FALSE(client.is_open());
  15341. svr.stop();
  15342. t.join();
  15343. }
  15344. TEST(WebSocketTest, ValidURL) {
  15345. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15346. EXPECT_TRUE(ws1.is_valid());
  15347. ws::WebSocketClient ws2("ws://example.com/path");
  15348. EXPECT_TRUE(ws2.is_valid());
  15349. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15350. EXPECT_TRUE(ws3.is_valid());
  15351. #ifdef CPPHTTPLIB_SSL_ENABLED
  15352. ws::WebSocketClient wss1("wss://example.com/path");
  15353. EXPECT_TRUE(wss1.is_valid());
  15354. ws::WebSocketClient wss2("wss://example.com:443/path");
  15355. EXPECT_TRUE(wss2.is_valid());
  15356. #endif
  15357. }
  15358. TEST(WebSocketTest, InvalidURL) {
  15359. // No scheme
  15360. ws::WebSocketClient ws1("localhost:8080/path");
  15361. EXPECT_FALSE(ws1.is_valid());
  15362. // No path
  15363. ws::WebSocketClient ws2("ws://localhost:8080");
  15364. EXPECT_FALSE(ws2.is_valid());
  15365. // Empty string
  15366. ws::WebSocketClient ws3("");
  15367. EXPECT_FALSE(ws3.is_valid());
  15368. // Missing host
  15369. ws::WebSocketClient ws4("ws://:8080/path");
  15370. EXPECT_FALSE(ws4.is_valid());
  15371. // Port number overflow — should not crash
  15372. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15373. EXPECT_FALSE(ws5.is_valid());
  15374. // Port out of range
  15375. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15376. EXPECT_FALSE(ws6.is_valid());
  15377. }
  15378. TEST(WebSocketTest, UnsupportedScheme) {
  15379. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15380. ws::WebSocketClient ws1("http://localhost:8080/path");
  15381. EXPECT_FALSE(ws1.is_valid());
  15382. ws::WebSocketClient ws2("https://localhost:8080/path");
  15383. EXPECT_FALSE(ws2.is_valid());
  15384. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15385. EXPECT_FALSE(ws3.is_valid());
  15386. #else
  15387. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15388. std::invalid_argument);
  15389. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15390. std::invalid_argument);
  15391. #endif
  15392. }
  15393. TEST(WebSocketTest, ConnectWhenInvalid) {
  15394. ws::WebSocketClient ws("not a valid url");
  15395. EXPECT_FALSE(ws.is_valid());
  15396. EXPECT_FALSE(ws.connect());
  15397. }
  15398. TEST(WebSocketTest, DefaultPort) {
  15399. ws::WebSocketClient ws1("ws://example.com/path");
  15400. EXPECT_TRUE(ws1.is_valid());
  15401. // ws:// defaults to port 80 (verified by successful parse)
  15402. #ifdef CPPHTTPLIB_SSL_ENABLED
  15403. ws::WebSocketClient ws2("wss://example.com/path");
  15404. EXPECT_TRUE(ws2.is_valid());
  15405. // wss:// defaults to port 443 (verified by successful parse)
  15406. #endif
  15407. }
  15408. TEST(WebSocketTest, IPv6LiteralAddress) {
  15409. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15410. EXPECT_TRUE(ws1.is_valid());
  15411. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15412. EXPECT_TRUE(ws2.is_valid());
  15413. }
  15414. TEST(WebSocketTest, ComplexPath) {
  15415. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15416. EXPECT_TRUE(ws1.is_valid());
  15417. ws::WebSocketClient ws2("ws://localhost:8080/");
  15418. EXPECT_TRUE(ws2.is_valid());
  15419. }
  15420. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15421. Server svr;
  15422. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15423. std::string msg;
  15424. while (ws.read(msg)) {}
  15425. });
  15426. auto port = svr.bind_to_any_port(HOST);
  15427. std::thread t([&]() { svr.listen_after_bind(); });
  15428. svr.wait_until_ready();
  15429. auto another_host = "example.com";
  15430. auto wrong_ip = "192.0.2.1";
  15431. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15432. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15433. ASSERT_TRUE(client.connect());
  15434. EXPECT_TRUE(client.is_open());
  15435. client.close();
  15436. svr.stop();
  15437. t.join();
  15438. }
  15439. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15440. Server svr;
  15441. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15442. std::string msg;
  15443. while (ws.read(msg)) {}
  15444. });
  15445. auto port = svr.bind_to_any_port(HOST);
  15446. std::thread t([&]() { svr.listen_after_bind(); });
  15447. svr.wait_until_ready();
  15448. auto wrong_ip = "192.0.2.1";
  15449. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15450. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15451. client.set_connection_timeout(1);
  15452. client.set_read_timeout(1);
  15453. client.set_write_timeout(1);
  15454. EXPECT_FALSE(client.connect());
  15455. EXPECT_FALSE(client.is_open());
  15456. svr.stop();
  15457. t.join();
  15458. }
  15459. class WebSocketIntegrationTest : public ::testing::Test {
  15460. protected:
  15461. void SetUp() override {
  15462. server_ = httplib::detail::make_unique<Server>();
  15463. setup_server();
  15464. start_server();
  15465. }
  15466. void TearDown() override {
  15467. server_->stop();
  15468. if (server_thread_.joinable()) { server_thread_.join(); }
  15469. }
  15470. void setup_server() {
  15471. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15472. std::string msg;
  15473. ws::ReadResult ret;
  15474. while ((ret = ws.read(msg))) {
  15475. if (ret == ws::Binary) {
  15476. ws.send(msg.data(), msg.size());
  15477. } else {
  15478. ws.send(msg);
  15479. }
  15480. }
  15481. });
  15482. server_->WebSocket("/ws-echo-string",
  15483. [](const Request &, ws::WebSocket &ws) {
  15484. std::string msg;
  15485. while (ws.read(msg)) {
  15486. ws.send("echo: " + msg);
  15487. }
  15488. });
  15489. server_->WebSocket(
  15490. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15491. // Echo back request metadata
  15492. ws.send("path:" + req.path);
  15493. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15494. std::string msg;
  15495. while (ws.read(msg)) {}
  15496. });
  15497. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15498. std::string msg;
  15499. ws.read(msg); // wait for a message
  15500. ws.close();
  15501. });
  15502. server_->WebSocket("/ws-close-status",
  15503. [](const Request &, ws::WebSocket &ws) {
  15504. std::string msg;
  15505. ws.read(msg); // wait for a message
  15506. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15507. });
  15508. server_->WebSocket(
  15509. "/ws-subprotocol",
  15510. [](const Request &, ws::WebSocket &ws) {
  15511. std::string msg;
  15512. while (ws.read(msg)) {
  15513. ws.send(msg);
  15514. }
  15515. },
  15516. [](const std::vector<std::string> &protocols) -> std::string {
  15517. for (const auto &p : protocols) {
  15518. if (p == "graphql-ws") { return p; }
  15519. }
  15520. return "";
  15521. });
  15522. }
  15523. void start_server() {
  15524. port_ = server_->bind_to_any_port(HOST);
  15525. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15526. server_->wait_until_ready();
  15527. }
  15528. std::unique_ptr<Server> server_;
  15529. std::thread server_thread_;
  15530. int port_ = 0;
  15531. };
  15532. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15533. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15534. "/ws-echo");
  15535. ASSERT_TRUE(client.connect());
  15536. ASSERT_TRUE(client.is_open());
  15537. ASSERT_TRUE(client.send("Hello WebSocket"));
  15538. std::string msg;
  15539. EXPECT_EQ(ws::Text, client.read(msg));
  15540. EXPECT_EQ("Hello WebSocket", msg);
  15541. client.close();
  15542. }
  15543. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15544. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15545. "/ws-echo");
  15546. ASSERT_TRUE(client.connect());
  15547. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15548. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15549. std::string msg;
  15550. EXPECT_EQ(ws::Binary, client.read(msg));
  15551. EXPECT_EQ(binary_data, msg);
  15552. client.close();
  15553. }
  15554. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15555. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15556. "/ws-echo");
  15557. ASSERT_TRUE(client.connect());
  15558. for (int i = 0; i < 10; i++) {
  15559. auto text = "message " + std::to_string(i);
  15560. ASSERT_TRUE(client.send(text));
  15561. std::string msg;
  15562. ASSERT_TRUE(client.read(msg));
  15563. EXPECT_EQ(text, msg);
  15564. }
  15565. client.close();
  15566. }
  15567. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15568. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15569. "/ws-close");
  15570. ASSERT_TRUE(client.connect());
  15571. // Send a message to trigger the server to close
  15572. ASSERT_TRUE(client.send("trigger close"));
  15573. // The server will close, so read should return false
  15574. std::string msg;
  15575. EXPECT_FALSE(client.read(msg));
  15576. EXPECT_FALSE(client.is_open());
  15577. }
  15578. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15579. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15580. "/ws-echo");
  15581. ASSERT_TRUE(client.connect());
  15582. // 128KB message
  15583. std::string large_data(128 * 1024, 'X');
  15584. ASSERT_TRUE(client.send(large_data));
  15585. std::string msg;
  15586. ASSERT_TRUE(client.read(msg));
  15587. EXPECT_EQ(large_data, msg);
  15588. client.close();
  15589. }
  15590. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15591. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15592. "/ws-echo");
  15593. ASSERT_TRUE(client.connect());
  15594. const int num_threads = 4;
  15595. std::vector<std::thread> threads;
  15596. std::atomic<int> send_count{0};
  15597. for (int t = 0; t < num_threads; t++) {
  15598. threads.emplace_back([&client, &send_count, t]() {
  15599. for (int i = 0; i < 5; i++) {
  15600. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15601. if (client.send(text)) { send_count++; }
  15602. }
  15603. });
  15604. }
  15605. for (auto &th : threads) {
  15606. th.join();
  15607. }
  15608. int received = 0;
  15609. std::string msg;
  15610. while (received < send_count.load()) {
  15611. if (!client.read(msg)) { break; }
  15612. received++;
  15613. }
  15614. EXPECT_EQ(send_count.load(), received);
  15615. client.close();
  15616. }
  15617. TEST_F(WebSocketIntegrationTest, ReadString) {
  15618. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15619. "/ws-echo-string");
  15620. ASSERT_TRUE(client.connect());
  15621. ASSERT_TRUE(client.send("hello"));
  15622. std::string msg;
  15623. ASSERT_TRUE(client.read(msg));
  15624. EXPECT_EQ("echo: hello", msg);
  15625. ASSERT_TRUE(client.send("world"));
  15626. ASSERT_TRUE(client.read(msg));
  15627. EXPECT_EQ("echo: world", msg);
  15628. client.close();
  15629. }
  15630. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15631. Headers headers = {{"X-Test-Header", "test-value"}};
  15632. ws::WebSocketClient client(
  15633. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15634. ASSERT_TRUE(client.connect());
  15635. std::string msg;
  15636. ASSERT_TRUE(client.read(msg));
  15637. EXPECT_EQ("path:/ws-request-info", msg);
  15638. ASSERT_TRUE(client.read(msg));
  15639. EXPECT_EQ("header:test-value", msg);
  15640. client.close();
  15641. }
  15642. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15643. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15644. "/ws-echo");
  15645. client.set_read_timeout(1, 0); // 1 second
  15646. ASSERT_TRUE(client.connect());
  15647. // Don't send anything — server echo handler waits for a message,
  15648. // so read() should time out and return false.
  15649. std::string msg;
  15650. EXPECT_FALSE(client.read(msg));
  15651. }
  15652. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15653. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15654. "/ws-echo");
  15655. client.set_read_timeout(5, 0);
  15656. ASSERT_TRUE(client.connect());
  15657. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15658. // The server should reject it and close the connection.
  15659. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15660. client.send(oversized);
  15661. // The server's read() should have failed due to payload limit,
  15662. // so our read() should return false (connection closed).
  15663. std::string msg;
  15664. EXPECT_FALSE(client.read(msg));
  15665. }
  15666. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15668. "/ws-echo");
  15669. client.set_read_timeout(10, 0);
  15670. ASSERT_TRUE(client.connect());
  15671. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15672. // This should succeed.
  15673. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15674. ASSERT_TRUE(client.send(at_limit));
  15675. std::string msg;
  15676. ASSERT_TRUE(client.read(msg));
  15677. EXPECT_EQ(at_limit.size(), msg.size());
  15678. client.close();
  15679. }
  15680. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15681. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15682. "/nonexistent");
  15683. EXPECT_FALSE(client.connect());
  15684. EXPECT_FALSE(client.is_open());
  15685. }
  15686. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15688. "/ws-echo");
  15689. ASSERT_TRUE(client.connect());
  15690. ASSERT_TRUE(client.send(""));
  15691. std::string msg;
  15692. EXPECT_EQ(ws::Text, client.read(msg));
  15693. EXPECT_EQ("", msg);
  15694. client.close();
  15695. }
  15696. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15697. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15698. "/ws-echo");
  15699. // First connection
  15700. ASSERT_TRUE(client.connect());
  15701. ASSERT_TRUE(client.send("first"));
  15702. std::string msg;
  15703. ASSERT_TRUE(client.read(msg));
  15704. EXPECT_EQ("first", msg);
  15705. client.close();
  15706. EXPECT_FALSE(client.is_open());
  15707. // Reconnect using the same client object
  15708. ASSERT_TRUE(client.connect());
  15709. ASSERT_TRUE(client.is_open());
  15710. ASSERT_TRUE(client.send("second"));
  15711. ASSERT_TRUE(client.read(msg));
  15712. EXPECT_EQ("second", msg);
  15713. client.close();
  15714. }
  15715. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15716. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15717. "/ws-close-status");
  15718. ASSERT_TRUE(client.connect());
  15719. // Trigger the server to close with GoingAway status
  15720. ASSERT_TRUE(client.send("trigger"));
  15721. // read() should return false after receiving the close frame
  15722. std::string msg;
  15723. EXPECT_FALSE(client.read(msg));
  15724. EXPECT_FALSE(client.is_open());
  15725. }
  15726. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15727. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15728. "/ws-echo");
  15729. ASSERT_TRUE(client.connect());
  15730. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15731. EXPECT_FALSE(client.is_open());
  15732. }
  15733. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15734. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15735. ws::WebSocketClient client(
  15736. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15737. ASSERT_TRUE(client.connect());
  15738. // Server should have selected graphql-ws
  15739. EXPECT_EQ("graphql-ws", client.subprotocol());
  15740. client.close();
  15741. }
  15742. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15743. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15744. ws::WebSocketClient client(
  15745. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15746. ASSERT_TRUE(client.connect());
  15747. // Server should not have selected any subprotocol
  15748. EXPECT_TRUE(client.subprotocol().empty());
  15749. client.close();
  15750. }
  15751. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15752. // Connect without requesting any subprotocol
  15753. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15754. "/ws-subprotocol");
  15755. ASSERT_TRUE(client.connect());
  15756. EXPECT_TRUE(client.subprotocol().empty());
  15757. client.close();
  15758. }
  15759. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15760. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15761. "/ws-echo");
  15762. client.set_tcp_nodelay(true);
  15763. client.set_connection_timeout(3, 0);
  15764. bool socket_options_called = false;
  15765. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15766. ASSERT_TRUE(client.connect());
  15767. ASSERT_TRUE(client.is_open());
  15768. EXPECT_TRUE(socket_options_called);
  15769. ASSERT_TRUE(client.send("hello"));
  15770. std::string msg;
  15771. auto result = client.read(msg);
  15772. EXPECT_EQ(result, ws::ReadResult::Text);
  15773. EXPECT_EQ(msg, "hello");
  15774. client.close();
  15775. }
  15776. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15777. Server svr;
  15778. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15779. if (!req.has_header("Authorization")) {
  15780. res.status = StatusCode::Unauthorized_401;
  15781. res.set_content("Unauthorized", "text/plain");
  15782. return Server::HandlerResponse::Handled;
  15783. }
  15784. return Server::HandlerResponse::Unhandled;
  15785. });
  15786. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15787. std::string msg;
  15788. while (ws.read(msg)) {
  15789. ws.send(msg);
  15790. }
  15791. });
  15792. auto port = svr.bind_to_any_port("localhost");
  15793. std::thread t([&]() { svr.listen_after_bind(); });
  15794. svr.wait_until_ready();
  15795. // Without Authorization header - should be rejected before upgrade
  15796. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15797. EXPECT_FALSE(client1.connect());
  15798. // With Authorization header - should succeed
  15799. Headers headers = {{"Authorization", "Bearer token123"}};
  15800. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15801. headers);
  15802. ASSERT_TRUE(client2.connect());
  15803. ASSERT_TRUE(client2.send("hello"));
  15804. std::string msg;
  15805. ASSERT_TRUE(client2.read(msg));
  15806. EXPECT_EQ("hello", msg);
  15807. client2.close();
  15808. svr.stop();
  15809. t.join();
  15810. }
  15811. TEST(WebSocketTest, QueryStringInHandshake) {
  15812. Server svr;
  15813. std::mutex mtx;
  15814. std::string received_target;
  15815. std::string received_token;
  15816. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15817. {
  15818. std::lock_guard<std::mutex> lock(mtx);
  15819. received_target = req.target;
  15820. if (req.has_param("token")) {
  15821. received_token = req.get_param_value("token");
  15822. }
  15823. }
  15824. std::string msg;
  15825. while (ws.read(msg)) {
  15826. ws.send(msg);
  15827. }
  15828. });
  15829. auto port = svr.bind_to_any_port("localhost");
  15830. std::thread t([&]() { svr.listen_after_bind(); });
  15831. svr.wait_until_ready();
  15832. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15833. "/ws?token=ABC&session=123");
  15834. ASSERT_TRUE(client.connect());
  15835. // Round-trip ensures the handler has run and captured the request.
  15836. ASSERT_TRUE(client.send("hello"));
  15837. std::string msg;
  15838. ASSERT_TRUE(client.read(msg));
  15839. EXPECT_EQ("hello", msg);
  15840. client.close();
  15841. {
  15842. std::lock_guard<std::mutex> lock(mtx);
  15843. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15844. EXPECT_EQ("ABC", received_token);
  15845. }
  15846. svr.stop();
  15847. t.join();
  15848. }
  15849. TEST(WebSocketTest, HostHeaderInHandshake) {
  15850. Server svr;
  15851. std::mutex mtx;
  15852. std::string received_host;
  15853. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15854. {
  15855. std::lock_guard<std::mutex> lock(mtx);
  15856. received_host = req.get_header_value("Host");
  15857. }
  15858. std::string msg;
  15859. while (ws.read(msg)) {
  15860. ws.send(msg);
  15861. }
  15862. });
  15863. auto port = svr.bind_to_any_port("localhost");
  15864. std::thread t([&]() { svr.listen_after_bind(); });
  15865. svr.wait_until_ready();
  15866. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15867. ASSERT_TRUE(client.connect());
  15868. // Round-trip ensures the handler has run and captured the request.
  15869. ASSERT_TRUE(client.send("hello"));
  15870. std::string msg;
  15871. ASSERT_TRUE(client.read(msg));
  15872. client.close();
  15873. {
  15874. std::lock_guard<std::mutex> lock(mtx);
  15875. // Non-default port must be present in the Host header. Default ports
  15876. // (80/443) are omitted; that logic is covered by
  15877. // MakeHostAndPortStringTest.
  15878. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  15879. }
  15880. svr.stop();
  15881. t.join();
  15882. }
  15883. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15884. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15885. protected:
  15886. void SetUp() override {
  15887. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15888. SERVER_PRIVATE_KEY_FILE);
  15889. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15890. std::string msg;
  15891. ws::ReadResult ret;
  15892. while ((ret = ws.read(msg))) {
  15893. if (ret == ws::Binary) {
  15894. ws.send(msg.data(), msg.size());
  15895. } else {
  15896. ws.send(msg);
  15897. }
  15898. }
  15899. });
  15900. port_ = server_->bind_to_any_port(HOST);
  15901. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15902. server_->wait_until_ready();
  15903. }
  15904. void TearDown() override {
  15905. server_->stop();
  15906. if (server_thread_.joinable()) { server_thread_.join(); }
  15907. }
  15908. std::unique_ptr<SSLServer> server_;
  15909. std::thread server_thread_;
  15910. int port_ = 0;
  15911. };
  15912. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15913. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15914. "/ws-echo");
  15915. client.enable_server_certificate_verification(false);
  15916. ASSERT_TRUE(client.connect());
  15917. ASSERT_TRUE(client.is_open());
  15918. ASSERT_TRUE(client.send("Hello WSS"));
  15919. std::string msg;
  15920. EXPECT_EQ(ws::Text, client.read(msg));
  15921. EXPECT_EQ("Hello WSS", msg);
  15922. client.close();
  15923. }
  15924. #endif
  15925. #ifdef CPPHTTPLIB_SSL_ENABLED
  15926. class WebSocketSSLCATest : public ::testing::Test {
  15927. protected:
  15928. void SetUp() override {
  15929. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  15930. SERVER_PRIVATE_KEY_FILE);
  15931. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15932. std::string msg;
  15933. while (ws.read(msg)) {
  15934. ws.send(msg);
  15935. }
  15936. });
  15937. port_ = server_->bind_to_any_port("127.0.0.1");
  15938. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15939. server_->wait_until_ready();
  15940. }
  15941. void TearDown() override {
  15942. server_->stop();
  15943. if (server_thread_.joinable()) { server_thread_.join(); }
  15944. }
  15945. std::string url() const {
  15946. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  15947. }
  15948. std::unique_ptr<SSLServer> server_;
  15949. std::thread server_thread_;
  15950. int port_ = 0;
  15951. };
  15952. // A custom CA loaded as PEM verifies the server with full certificate
  15953. // verification enabled
  15954. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  15955. ws::WebSocketClient client(url());
  15956. std::string cert;
  15957. read_file(SERVER_CERT2_FILE, cert);
  15958. client.load_ca_cert_store(cert.c_str(), cert.size());
  15959. ASSERT_TRUE(client.connect());
  15960. ASSERT_TRUE(client.send("hello"));
  15961. std::string msg;
  15962. EXPECT_EQ(ws::Text, client.read(msg));
  15963. EXPECT_EQ("hello", msg);
  15964. client.close();
  15965. }
  15966. // A custom CA that does not cover the server must fail verification (the
  15967. // custom CA is exclusive; system certs are not loaded alongside it)
  15968. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  15969. ws::WebSocketClient client(url());
  15970. std::string cert;
  15971. read_file(CLIENT_CA_CERT_FILE, cert);
  15972. client.load_ca_cert_store(cert.c_str(), cert.size());
  15973. ASSERT_FALSE(client.connect());
  15974. }
  15975. // Regression test: reconnecting with a native custom CA store used to reuse
  15976. // a store handle the previous TLS context had already freed (use-after-free
  15977. // under the OpenSSL backend). The context now lives as long as the client.
  15978. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  15979. ws::WebSocketClient client(url());
  15980. std::string cert;
  15981. read_file(SERVER_CERT2_FILE, cert);
  15982. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15983. ASSERT_TRUE(client.connect());
  15984. client.close();
  15985. ASSERT_TRUE(client.connect());
  15986. ASSERT_TRUE(client.send("again"));
  15987. std::string msg;
  15988. EXPECT_EQ(ws::Text, client.read(msg));
  15989. EXPECT_EQ("again", msg);
  15990. client.close();
  15991. }
  15992. // Regression test: a certificate with a trusted chain but no identity match
  15993. // for the server IP must be rejected. The Mbed TLS backend used to skip
  15994. // verification entirely for IP hosts, so this connection succeeded there.
  15995. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  15996. // chain verification while the identity check must still fail.
  15997. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  15998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15999. ASSERT_TRUE(svr.is_valid());
  16000. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16001. std::string msg;
  16002. while (ws.read(msg)) {
  16003. ws.send(msg);
  16004. }
  16005. });
  16006. auto port = svr.bind_to_any_port("127.0.0.1");
  16007. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16008. auto se = detail::scope_exit([&] {
  16009. svr.stop();
  16010. t.join();
  16011. });
  16012. svr.wait_until_ready();
  16013. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16014. "/echo");
  16015. std::string cert;
  16016. read_file(SERVER_CERT_FILE, cert);
  16017. client.load_ca_cert_store(cert.c_str(), cert.size());
  16018. ASSERT_FALSE(client.connect());
  16019. }
  16020. #endif
  16021. #if !defined(_WIN32)
  16022. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16023. auto secret_dir = std::string("./symlink_test_secret");
  16024. auto served_dir = std::string("./symlink_test_served");
  16025. auto secret_file = secret_dir + "/secret.txt";
  16026. auto symlink_path = served_dir + "/escape";
  16027. // Setup: create directories and files
  16028. mkdir(secret_dir.c_str(), 0755);
  16029. mkdir(served_dir.c_str(), 0755);
  16030. {
  16031. std::ofstream ofs(secret_file);
  16032. ofs << "SECRET_DATA";
  16033. }
  16034. // Create symlink using absolute path so it resolves correctly
  16035. #ifdef PATH_MAX
  16036. char abs_secret[PATH_MAX];
  16037. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16038. #else
  16039. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16040. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16041. ASSERT_NE(nullptr, abs_secret);
  16042. #endif
  16043. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16044. auto se = detail::scope_exit([&] {
  16045. unlink(symlink_path.c_str());
  16046. unlink(secret_file.c_str());
  16047. rmdir(served_dir.c_str());
  16048. rmdir(secret_dir.c_str());
  16049. });
  16050. Server svr;
  16051. svr.set_mount_point("/", served_dir);
  16052. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16053. auto se2 = detail::scope_exit([&] {
  16054. svr.stop();
  16055. listen_thread.join();
  16056. });
  16057. svr.wait_until_ready();
  16058. Client cli("localhost", PORT);
  16059. // Symlink pointing outside base dir should be blocked
  16060. auto res = cli.Get("/escape/secret.txt");
  16061. ASSERT_TRUE(res);
  16062. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16063. }
  16064. #endif
  16065. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16066. // A GET request with Content-Length to a static file handler must have its
  16067. // body drained before the keep-alive connection is reused. Otherwise the
  16068. // unread body bytes are interpreted as the next HTTP request.
  16069. //
  16070. // The body is sent AFTER receiving the first response (as in the original
  16071. // PoC) so that the stream_line_reader cannot buffer it together with the
  16072. // headers of the first request.
  16073. Server svr;
  16074. svr.set_mount_point("/", "./www");
  16075. std::atomic<int> smuggled_count(0);
  16076. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16077. smuggled_count++;
  16078. res.set_content("oops", "text/plain");
  16079. });
  16080. auto port = svr.bind_to_any_port("localhost");
  16081. thread t = thread([&] { svr.listen_after_bind(); });
  16082. auto se = detail::scope_exit([&] {
  16083. svr.stop();
  16084. t.join();
  16085. });
  16086. svr.wait_until_ready();
  16087. auto error = Error::Success;
  16088. auto sock = detail::create_client_socket(
  16089. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16090. /*connection_timeout_sec=*/2, 0,
  16091. /*read_timeout_sec=*/2, 0,
  16092. /*write_timeout_sec=*/2, 0, std::string(), error);
  16093. ASSERT_NE(INVALID_SOCKET, sock);
  16094. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16095. // The "smuggled" request will be sent as the body of the outer GET
  16096. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16097. "Host: localhost\r\n"
  16098. "Connection: close\r\n"
  16099. "\r\n";
  16100. // Step 1: Send only the outer request headers (no body yet)
  16101. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16102. "Host: localhost\r\n"
  16103. "Content-Length: " +
  16104. std::to_string(smuggled.size()) +
  16105. "\r\n"
  16106. "\r\n";
  16107. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16108. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16109. // Step 2: Read the first response (server serves file without reading body)
  16110. std::string first_response;
  16111. char buf[4096];
  16112. for (;;) {
  16113. auto n = recv(sock, buf, sizeof(buf), 0);
  16114. if (n <= 0) break;
  16115. first_response.append(buf, static_cast<size_t>(n));
  16116. // Stop once we have a complete response (headers + body)
  16117. auto hdr_end = first_response.find("\r\n\r\n");
  16118. if (hdr_end != std::string::npos) {
  16119. // Check for Content-Length to know when the body is complete
  16120. auto cl_pos = first_response.find("Content-Length:");
  16121. if (cl_pos != std::string::npos) {
  16122. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16123. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16124. auto cl = std::stoul(
  16125. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16126. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16127. } else {
  16128. break; // No Content-Length, assume headers-only response
  16129. }
  16130. }
  16131. }
  16132. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16133. // Step 3: Now send the body, which looks like a new HTTP request.
  16134. // On a vulnerable server the keep-alive loop reads this as a second request.
  16135. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16136. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16137. // Step 4: Try to read a second response (should NOT exist after fix)
  16138. std::string second_response;
  16139. for (;;) {
  16140. auto n = recv(sock, buf, sizeof(buf), 0);
  16141. if (n <= 0) break;
  16142. second_response.append(buf, static_cast<size_t>(n));
  16143. }
  16144. // The smuggled request must NOT have been processed
  16145. EXPECT_EQ(0, smuggled_count.load());
  16146. }
  16147. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16148. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16149. // must be rejected with 400 Bad Request.
  16150. Server svr;
  16151. svr.Post("/test", [&](const Request &, Response &res) {
  16152. res.set_content("ok", "text/plain");
  16153. });
  16154. thread t = thread([&] { svr.listen(HOST, PORT); });
  16155. auto se = detail::scope_exit([&] {
  16156. svr.stop();
  16157. t.join();
  16158. ASSERT_FALSE(svr.is_running());
  16159. });
  16160. svr.wait_until_ready();
  16161. // Exact "chunked"
  16162. {
  16163. auto req = "POST /test HTTP/1.1\r\n"
  16164. "Host: localhost\r\n"
  16165. "Content-Length: 5\r\n"
  16166. "Transfer-Encoding: chunked\r\n"
  16167. "Connection: close\r\n"
  16168. "\r\n"
  16169. "hello";
  16170. std::string response;
  16171. ASSERT_TRUE(send_request(1, req, &response));
  16172. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16173. response.substr(0, response.find("\r\n")));
  16174. }
  16175. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16176. {
  16177. auto req = "POST /test HTTP/1.1\r\n"
  16178. "Host: localhost\r\n"
  16179. "Content-Length: 5\r\n"
  16180. "Transfer-Encoding: gzip, chunked\r\n"
  16181. "Connection: close\r\n"
  16182. "\r\n"
  16183. "hello";
  16184. std::string response;
  16185. ASSERT_TRUE(send_request(1, req, &response));
  16186. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16187. response.substr(0, response.find("\r\n")));
  16188. }
  16189. }
  16190. // Regression for issue #2450: a DELETE without Content-Length on a
  16191. // keep-alive connection must not let the post-response drain consume the
  16192. // next request's bytes.
  16193. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16194. Server svr;
  16195. std::atomic<int> delete_count(0);
  16196. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16197. delete_count++;
  16198. res.status = StatusCode::NoContent_204;
  16199. });
  16200. auto port = svr.bind_to_any_port(HOST);
  16201. thread t = thread([&] { svr.listen_after_bind(); });
  16202. auto se = detail::scope_exit([&] {
  16203. svr.stop();
  16204. t.join();
  16205. });
  16206. svr.wait_until_ready();
  16207. auto error = Error::Success;
  16208. auto sock = detail::create_client_socket(
  16209. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16210. /*connection_timeout_sec=*/2, 0,
  16211. /*read_timeout_sec=*/2, 0,
  16212. /*write_timeout_sec=*/2, 0, std::string(), error);
  16213. ASSERT_NE(INVALID_SOCKET, sock);
  16214. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16215. auto send_request_and_read_response = [&](const std::string &req,
  16216. std::string &out) -> bool {
  16217. auto sent = send(sock, req.data(), req.size(), 0);
  16218. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16219. char buf[4096];
  16220. for (;;) {
  16221. auto n = recv(sock, buf, sizeof(buf), 0);
  16222. if (n <= 0) { return !out.empty(); }
  16223. out.append(buf, static_cast<size_t>(n));
  16224. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16225. }
  16226. };
  16227. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16228. "Host: localhost\r\n"
  16229. "\r\n";
  16230. std::string resp1;
  16231. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16232. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16233. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16234. "Host: localhost\r\n"
  16235. "Connection: close\r\n"
  16236. "\r\n";
  16237. std::string resp2;
  16238. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16239. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16240. EXPECT_EQ(2, delete_count.load());
  16241. }
  16242. namespace no_proxy_test {
  16243. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16244. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16245. // calling listen().
  16246. class ScopedServer {
  16247. public:
  16248. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16249. ~ScopedServer() {
  16250. svr_.stop();
  16251. if (th_.joinable()) { th_.join(); }
  16252. }
  16253. Server &svr() { return svr_; }
  16254. int port() const { return port_; }
  16255. void listen() {
  16256. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16257. svr_.wait_until_ready();
  16258. }
  16259. private:
  16260. Server svr_;
  16261. std::thread th_;
  16262. int port_ = 0;
  16263. };
  16264. class ProxyAndTargetServers {
  16265. public:
  16266. ProxyAndTargetServers() {
  16267. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16268. proxy_hits_++;
  16269. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16270. res.set_content("via-proxy", "text/plain");
  16271. });
  16272. target_.Get(".*", [this](const Request &req, Response &res) {
  16273. target_hits_++;
  16274. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16275. res.set_content("direct", "text/plain");
  16276. });
  16277. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16278. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16279. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16280. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16281. proxy_mock_.wait_until_ready();
  16282. target_.wait_until_ready();
  16283. }
  16284. ~ProxyAndTargetServers() {
  16285. proxy_mock_.stop();
  16286. target_.stop();
  16287. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16288. if (target_thread_.joinable()) { target_thread_.join(); }
  16289. }
  16290. Server &proxy_mock() { return proxy_mock_; }
  16291. Server &target() { return target_; }
  16292. int proxy_port() const { return proxy_port_; }
  16293. int target_port() const { return target_port_; }
  16294. int proxy_hits() const { return proxy_hits_.load(); }
  16295. int target_hits() const { return target_hits_.load(); }
  16296. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16297. void reset_counters() {
  16298. proxy_hits_ = 0;
  16299. target_hits_ = 0;
  16300. last_had_proxy_authz_ = false;
  16301. }
  16302. private:
  16303. Server proxy_mock_;
  16304. Server target_;
  16305. std::thread proxy_thread_;
  16306. std::thread target_thread_;
  16307. int proxy_port_ = 0;
  16308. int target_port_ = 0;
  16309. std::atomic<int> proxy_hits_{0};
  16310. std::atomic<int> target_hits_{0};
  16311. std::atomic<bool> last_had_proxy_authz_{false};
  16312. };
  16313. inline std::unique_ptr<Client> make_client(const std::string &host,
  16314. ProxyAndTargetServers &s) {
  16315. auto cli = detail::make_unique<Client>(host, s.target_port());
  16316. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16317. cli->set_proxy("127.0.0.1", s.proxy_port());
  16318. return cli;
  16319. }
  16320. } // namespace no_proxy_test
  16321. using no_proxy_test::make_client;
  16322. using no_proxy_test::ProxyAndTargetServers;
  16323. TEST(NoProxyTest, ExactHostnameBypasses) {
  16324. ProxyAndTargetServers s;
  16325. auto cli = make_client("example.com", s);
  16326. cli->set_no_proxy({"example.com"});
  16327. auto res = cli->Get("/");
  16328. ASSERT_TRUE(res);
  16329. EXPECT_EQ(0, s.proxy_hits());
  16330. EXPECT_EQ(1, s.target_hits());
  16331. }
  16332. TEST(NoProxyTest, SubdomainBypasses) {
  16333. ProxyAndTargetServers s;
  16334. auto cli = make_client("foo.example.com", s);
  16335. cli->set_no_proxy({"example.com"});
  16336. auto res = cli->Get("/");
  16337. ASSERT_TRUE(res);
  16338. EXPECT_EQ(0, s.proxy_hits());
  16339. EXPECT_EQ(1, s.target_hits());
  16340. }
  16341. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16342. // Regression guard: "evilexample.com" must not be considered a subdomain
  16343. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16344. // check would let traffic bypass the proxy and leak credentials direct
  16345. // to the attacker host.
  16346. ProxyAndTargetServers s;
  16347. auto cli = make_client("evilexample.com", s);
  16348. cli->set_no_proxy({"example.com"});
  16349. auto res = cli->Get("/");
  16350. ASSERT_TRUE(res);
  16351. EXPECT_GE(s.proxy_hits(), 1);
  16352. EXPECT_EQ(0, s.target_hits());
  16353. }
  16354. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16355. ProxyAndTargetServers s;
  16356. auto cli = make_client("example.com.evil.com", s);
  16357. cli->set_no_proxy({"example.com"});
  16358. auto res = cli->Get("/");
  16359. ASSERT_TRUE(res);
  16360. EXPECT_GE(s.proxy_hits(), 1);
  16361. EXPECT_EQ(0, s.target_hits());
  16362. }
  16363. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16364. ProxyAndTargetServers s;
  16365. auto cli = make_client("example.com", s);
  16366. cli->set_no_proxy({".example.com"});
  16367. auto res = cli->Get("/");
  16368. ASSERT_TRUE(res);
  16369. EXPECT_EQ(0, s.proxy_hits());
  16370. EXPECT_EQ(1, s.target_hits());
  16371. }
  16372. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16373. ProxyAndTargetServers s;
  16374. auto cli = make_client("Example.COM", s);
  16375. cli->set_no_proxy({"EXAMPLE.com"});
  16376. auto res = cli->Get("/");
  16377. ASSERT_TRUE(res);
  16378. EXPECT_EQ(0, s.proxy_hits());
  16379. EXPECT_EQ(1, s.target_hits());
  16380. }
  16381. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16382. ProxyAndTargetServers s;
  16383. auto cli = make_client("example.com.", s);
  16384. cli->set_no_proxy({"example.com"});
  16385. auto res = cli->Get("/");
  16386. ASSERT_TRUE(res);
  16387. EXPECT_EQ(0, s.proxy_hits());
  16388. EXPECT_EQ(1, s.target_hits());
  16389. }
  16390. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16391. // Trailing dots must be normalized on BOTH sides — host and entry.
  16392. // An implementation that only strips the host-side trailing dot would
  16393. // fail to match host "example.com" against entry "example.com." because
  16394. // a literal substring search would compare 11 chars against 12.
  16395. ProxyAndTargetServers s;
  16396. auto cli = make_client("example.com", s);
  16397. cli->set_no_proxy({"example.com."});
  16398. auto res = cli->Get("/");
  16399. ASSERT_TRUE(res);
  16400. EXPECT_EQ(0, s.proxy_hits());
  16401. EXPECT_EQ(1, s.target_hits());
  16402. }
  16403. TEST(NoProxyTest, WildcardBypassesEverything) {
  16404. ProxyAndTargetServers s;
  16405. auto cli = make_client("anything.invalid.test", s);
  16406. cli->set_no_proxy({"*"});
  16407. auto res = cli->Get("/");
  16408. ASSERT_TRUE(res);
  16409. EXPECT_EQ(0, s.proxy_hits());
  16410. EXPECT_EQ(1, s.target_hits());
  16411. }
  16412. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16413. ProxyAndTargetServers s;
  16414. Client cli("127.0.0.1", s.target_port());
  16415. cli.set_proxy("127.0.0.1", s.proxy_port());
  16416. cli.set_no_proxy({"127.0.0.1"});
  16417. auto res = cli.Get("/");
  16418. ASSERT_TRUE(res);
  16419. EXPECT_EQ(0, s.proxy_hits());
  16420. EXPECT_EQ(1, s.target_hits());
  16421. }
  16422. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16423. ProxyAndTargetServers s;
  16424. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16425. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16426. cli.set_proxy("127.0.0.1", s.proxy_port());
  16427. cli.set_no_proxy({"::1"});
  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, BareIPv6LiteralMatchesIPv6Cidr) {
  16434. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16435. // must still be recognized as IPv6 for CIDR matching. Implementations
  16436. // that detect IPv6 only when the host begins with '[' would parse the
  16437. // host as a hostname and miss the match.
  16438. ProxyAndTargetServers s;
  16439. Client cli("fe80::1", s.target_port());
  16440. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16441. cli.set_proxy("127.0.0.1", s.proxy_port());
  16442. cli.set_no_proxy({"fe80::/10"});
  16443. auto res = cli.Get("/");
  16444. ASSERT_TRUE(res);
  16445. EXPECT_EQ(0, s.proxy_hits());
  16446. EXPECT_EQ(1, s.target_hits());
  16447. }
  16448. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16449. ProxyAndTargetServers s;
  16450. Client cli("::1", s.target_port());
  16451. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16452. cli.set_proxy("127.0.0.1", s.proxy_port());
  16453. cli.set_no_proxy({"[::1]"});
  16454. auto res = cli.Get("/");
  16455. ASSERT_TRUE(res);
  16456. EXPECT_EQ(0, s.proxy_hits());
  16457. EXPECT_EQ(1, s.target_hits());
  16458. }
  16459. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16460. ProxyAndTargetServers s;
  16461. Client cli("fe80::1", s.target_port());
  16462. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16463. cli.set_proxy("127.0.0.1", s.proxy_port());
  16464. cli.set_no_proxy({"[fe80::]/10"});
  16465. auto res = cli.Get("/");
  16466. ASSERT_TRUE(res);
  16467. EXPECT_EQ(0, s.proxy_hits());
  16468. EXPECT_EQ(1, s.target_hits());
  16469. }
  16470. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16471. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16472. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16473. // tricks via address-family conversion.
  16474. ProxyAndTargetServers s;
  16475. Client cli("::ffff:127.0.0.1", s.target_port());
  16476. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16477. cli.set_proxy("127.0.0.1", s.proxy_port());
  16478. cli.set_no_proxy({"127.0.0.1"});
  16479. auto res = cli.Get("/");
  16480. ASSERT_TRUE(res);
  16481. EXPECT_GE(s.proxy_hits(), 1);
  16482. EXPECT_EQ(0, s.target_hits());
  16483. }
  16484. TEST(NoProxyTest, IPv4CidrMatch) {
  16485. ProxyAndTargetServers s;
  16486. Client cli("127.0.0.1", s.target_port());
  16487. cli.set_proxy("127.0.0.1", s.proxy_port());
  16488. cli.set_no_proxy({"127.0.0.0/8"});
  16489. auto res = cli.Get("/");
  16490. ASSERT_TRUE(res);
  16491. EXPECT_EQ(0, s.proxy_hits());
  16492. EXPECT_EQ(1, s.target_hits());
  16493. }
  16494. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16495. ProxyAndTargetServers s;
  16496. Client cli("127.0.0.1", s.target_port());
  16497. cli.set_proxy("127.0.0.1", s.proxy_port());
  16498. cli.set_no_proxy({"10.0.0.0/8"});
  16499. auto res = cli.Get("/");
  16500. ASSERT_TRUE(res);
  16501. EXPECT_GE(s.proxy_hits(), 1);
  16502. EXPECT_EQ(0, s.target_hits());
  16503. }
  16504. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16505. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16506. // IPv4 target matches.
  16507. ProxyAndTargetServers s;
  16508. Client cli("127.0.0.1", s.target_port());
  16509. cli.set_proxy("127.0.0.1", s.proxy_port());
  16510. cli.set_no_proxy({"0.0.0.0/0"});
  16511. auto res = cli.Get("/");
  16512. ASSERT_TRUE(res);
  16513. EXPECT_EQ(0, s.proxy_hits());
  16514. EXPECT_EQ(1, s.target_hits());
  16515. }
  16516. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16517. ProxyAndTargetServers s;
  16518. Client cli("127.0.0.1", s.target_port());
  16519. cli.set_proxy("127.0.0.1", s.proxy_port());
  16520. cli.set_no_proxy({"127.0.0.1"});
  16521. auto res = cli.Get("/");
  16522. ASSERT_TRUE(res);
  16523. EXPECT_EQ(0, s.proxy_hits());
  16524. EXPECT_EQ(1, s.target_hits());
  16525. }
  16526. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16527. ProxyAndTargetServers s;
  16528. Client cli("127.0.0.1", s.target_port());
  16529. cli.set_proxy("127.0.0.1", s.proxy_port());
  16530. cli.set_no_proxy({"127.0.0.0/33"});
  16531. auto res = cli.Get("/");
  16532. ASSERT_TRUE(res);
  16533. EXPECT_GE(s.proxy_hits(), 1);
  16534. EXPECT_EQ(0, s.target_hits());
  16535. }
  16536. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16537. // Empty prefix after the slash must be rejected, not silently treated as /32.
  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_GE(s.proxy_hits(), 1);
  16545. EXPECT_EQ(0, s.target_hits());
  16546. }
  16547. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16548. ProxyAndTargetServers s;
  16549. auto cli = make_client("internal.corp", s);
  16550. cli->set_proxy_basic_auth("u", "p");
  16551. cli->set_no_proxy({"internal.corp"});
  16552. auto res = cli->Get("/");
  16553. ASSERT_TRUE(res);
  16554. EXPECT_EQ(1, s.target_hits());
  16555. EXPECT_EQ(0, s.proxy_hits());
  16556. EXPECT_FALSE(s.last_had_proxy_authz())
  16557. << "Proxy-Authorization must not be sent direct to the target";
  16558. }
  16559. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16560. ProxyAndTargetServers s;
  16561. auto cli = make_client("public.example", s);
  16562. cli->set_proxy_basic_auth("u", "p");
  16563. cli->set_no_proxy({"internal.corp"}); // does not match
  16564. auto res = cli->Get("/");
  16565. ASSERT_TRUE(res);
  16566. EXPECT_GE(s.proxy_hits(), 1);
  16567. EXPECT_TRUE(s.last_had_proxy_authz());
  16568. }
  16569. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16570. ProxyAndTargetServers s;
  16571. auto cli = make_client("anything.test", s);
  16572. auto res = cli->Get("/");
  16573. ASSERT_TRUE(res);
  16574. EXPECT_GE(s.proxy_hits(), 1);
  16575. EXPECT_EQ(0, s.target_hits());
  16576. }
  16577. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16578. ProxyAndTargetServers s;
  16579. auto cli = make_client("example.com", s);
  16580. cli->set_no_proxy({"example.com:8080"});
  16581. auto res = cli->Get("/");
  16582. ASSERT_TRUE(res);
  16583. EXPECT_GE(s.proxy_hits(), 1);
  16584. EXPECT_EQ(0, s.target_hits());
  16585. }
  16586. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16587. ProxyAndTargetServers s;
  16588. auto cli = make_client("anything.test", s);
  16589. cli->set_no_proxy({"", " ", "\t"});
  16590. auto res = cli->Get("/");
  16591. ASSERT_TRUE(res);
  16592. EXPECT_GE(s.proxy_hits(), 1);
  16593. EXPECT_EQ(0, s.target_hits());
  16594. }
  16595. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16596. // An entry with leading/trailing whitespace must still match — env-style
  16597. // values are commonly pasted with stray spaces and an implementation
  16598. // that feeds the raw token directly to inet_pton would fail to match
  16599. // valid CIDRs because of the spaces.
  16600. ProxyAndTargetServers s;
  16601. Client cli("127.0.0.1", s.target_port());
  16602. cli.set_proxy("127.0.0.1", s.proxy_port());
  16603. cli.set_no_proxy({" 127.0.0.0/8 "});
  16604. auto res = cli.Get("/");
  16605. ASSERT_TRUE(res);
  16606. EXPECT_EQ(0, s.proxy_hits());
  16607. EXPECT_EQ(1, s.target_hits());
  16608. }
  16609. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16610. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16611. // go direct and must NOT carry Proxy-Authorization.
  16612. std::atomic<int> proxy_hits{0};
  16613. std::atomic<int> target_hits{0};
  16614. std::atomic<bool> target_saw_authz{false};
  16615. no_proxy_test::ScopedServer proxy_mock, target;
  16616. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16617. proxy_hits++;
  16618. res.status = 302;
  16619. res.set_header("Location", "http://127.0.0.1:" +
  16620. std::to_string(target.port()) + "/landed");
  16621. });
  16622. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16623. target_hits++;
  16624. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16625. res.set_content("direct", "text/plain");
  16626. });
  16627. proxy_mock.listen();
  16628. target.listen();
  16629. Client cli("public.example", target.port());
  16630. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16631. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16632. cli.set_proxy_basic_auth("u", "p");
  16633. cli.set_no_proxy({"127.0.0.1"});
  16634. cli.set_follow_location(true);
  16635. auto res = cli.Get("/redir");
  16636. ASSERT_TRUE(res);
  16637. EXPECT_GE(proxy_hits.load(), 1);
  16638. EXPECT_GE(target_hits.load(), 1);
  16639. EXPECT_FALSE(target_saw_authz.load());
  16640. }
  16641. #ifdef CPPHTTPLIB_SSL_ENABLED
  16642. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16643. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16644. // proxy creds would be sent to the (possibly hostile) origin.
  16645. std::atomic<int> target_hits{0};
  16646. std::atomic<bool> target_saw_proxy_authz{false};
  16647. no_proxy_test::ScopedServer target;
  16648. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16649. target_hits++;
  16650. if (req.has_header("Proxy-Authorization")) {
  16651. target_saw_proxy_authz = true;
  16652. }
  16653. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16654. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16655. "nonce=\"abc\", algorithm=MD5");
  16656. });
  16657. target.listen();
  16658. // The proxy address is set to the target's port: the bypass MUST kick in;
  16659. // if it doesn't, the test still routes "via proxy" to the same server and
  16660. // the Proxy-Authorization assertion below catches the leak.
  16661. Client cli("evil.example", target.port());
  16662. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16663. cli.set_proxy("127.0.0.1", target.port());
  16664. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16665. cli.set_no_proxy({"evil.example"});
  16666. auto res = cli.Get("/x");
  16667. ASSERT_TRUE(res);
  16668. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16669. EXPECT_EQ(1, target_hits.load());
  16670. EXPECT_FALSE(target_saw_proxy_authz.load());
  16671. }
  16672. #endif
  16673. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16674. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16675. std::atomic<int> proxy_hits{0};
  16676. std::atomic<int> bypass_hits{0};
  16677. std::atomic<bool> proxy_saw_c_url{false};
  16678. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16679. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16680. proxy_hits++;
  16681. if (req.path.find("/start") != std::string::npos) {
  16682. res.status = 302;
  16683. res.set_header("Location", "http://127.0.0.1:" +
  16684. std::to_string(bypass_server.port()) +
  16685. "/middle");
  16686. return;
  16687. }
  16688. if (req.path.find("/end") != std::string::npos) {
  16689. proxy_saw_c_url = true;
  16690. res.set_content("c-via-proxy", "text/plain");
  16691. return;
  16692. }
  16693. res.set_content("unexpected", "text/plain");
  16694. });
  16695. // public.example's "advertised" port is arbitrary (the request never lands
  16696. // there — it goes through the proxy), but use a dynamic value to stay
  16697. // friendly with sharded parallel runs.
  16698. int public_port = bypass_server.port();
  16699. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16700. bypass_hits++;
  16701. res.status = 302;
  16702. res.set_header("Location", "http://public.example:" +
  16703. std::to_string(public_port) + "/end");
  16704. });
  16705. proxy_mock.listen();
  16706. bypass_server.listen();
  16707. Client cli("public.example", public_port);
  16708. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16709. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16710. cli.set_no_proxy({"127.0.0.1"});
  16711. cli.set_follow_location(true);
  16712. auto res = cli.Get("/start");
  16713. ASSERT_TRUE(res);
  16714. EXPECT_EQ(StatusCode::OK_200, res->status);
  16715. EXPECT_EQ("c-via-proxy", res->body);
  16716. EXPECT_GE(proxy_hits.load(), 2);
  16717. EXPECT_GE(bypass_hits.load(), 1);
  16718. EXPECT_TRUE(proxy_saw_c_url.load());
  16719. }
  16720. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16721. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16722. // request reconnects to the correct endpoint.
  16723. std::atomic<int> proxy_hits{0};
  16724. std::atomic<int> target_hits{0};
  16725. no_proxy_test::ScopedServer proxy_mock, target;
  16726. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16727. proxy_hits++;
  16728. res.set_content("via-proxy", "text/plain");
  16729. });
  16730. target.svr().Get(".*", [&](const Request &, Response &res) {
  16731. target_hits++;
  16732. res.set_content("direct", "text/plain");
  16733. });
  16734. proxy_mock.listen();
  16735. target.listen();
  16736. Client cli("public.example", target.port());
  16737. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16738. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16739. cli.set_keep_alive(true);
  16740. auto res1 = cli.Get("/a");
  16741. ASSERT_TRUE(res1);
  16742. EXPECT_EQ("via-proxy", res1->body);
  16743. EXPECT_EQ(1, proxy_hits.load());
  16744. EXPECT_EQ(0, target_hits.load());
  16745. cli.set_no_proxy({"public.example"});
  16746. auto res2 = cli.Get("/b");
  16747. ASSERT_TRUE(res2);
  16748. EXPECT_EQ("direct", res2->body);
  16749. EXPECT_EQ(1, proxy_hits.load());
  16750. EXPECT_EQ(1, target_hits.load());
  16751. }
  16752. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16753. namespace proxy_tunnel_test {
  16754. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16755. class ScopedSSLServer {
  16756. public:
  16757. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16758. port_ = svr_.bind_to_any_port("127.0.0.1");
  16759. }
  16760. ~ScopedSSLServer() {
  16761. svr_.stop();
  16762. if (th_.joinable()) { th_.join(); }
  16763. }
  16764. SSLServer &svr() { return svr_; }
  16765. int port() const { return port_; }
  16766. void listen() {
  16767. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16768. svr_.wait_until_ready();
  16769. }
  16770. private:
  16771. SSLServer svr_;
  16772. std::thread th_;
  16773. int port_ = 0;
  16774. };
  16775. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16776. class ScopedConnectProxy {
  16777. public:
  16778. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16779. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16780. if (listen_fd_ < 0) { return; }
  16781. int yes = 1;
  16782. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16783. sockaddr_in a{};
  16784. a.sin_family = AF_INET;
  16785. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16786. a.sin_port = 0;
  16787. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16788. return;
  16789. }
  16790. socklen_t alen = sizeof(a);
  16791. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16792. 0) {
  16793. return;
  16794. }
  16795. port_ = ntohs(a.sin_port);
  16796. if (::listen(listen_fd_, 1) != 0) { return; }
  16797. th_ = std::thread([this] { run(); });
  16798. }
  16799. ~ScopedConnectProxy() {
  16800. stop_ = true;
  16801. if (listen_fd_ >= 0) {
  16802. ::shutdown(listen_fd_, SHUT_RDWR);
  16803. ::close(listen_fd_);
  16804. }
  16805. if (th_.joinable()) { th_.join(); }
  16806. }
  16807. int port() const { return port_; }
  16808. int connect_hits() const { return connect_hits_.load(); }
  16809. private:
  16810. void run() {
  16811. while (!stop_.load()) {
  16812. fd_set rfds;
  16813. FD_ZERO(&rfds);
  16814. FD_SET(listen_fd_, &rfds);
  16815. timeval tv{0, 100 * 1000};
  16816. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16817. if (sel <= 0) { continue; }
  16818. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16819. if (client_fd < 0) { continue; }
  16820. std::string req;
  16821. char buf[2048];
  16822. while (req.find("\r\n\r\n") == std::string::npos) {
  16823. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16824. if (n <= 0) { break; }
  16825. req.append(buf, static_cast<size_t>(n));
  16826. }
  16827. if (req.compare(0, 7, "CONNECT") != 0) {
  16828. ::close(client_fd);
  16829. continue;
  16830. }
  16831. connect_hits_++;
  16832. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16833. ::send(client_fd, ok, std::strlen(ok), 0);
  16834. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16835. sockaddr_in o{};
  16836. o.sin_family = AF_INET;
  16837. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16838. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16839. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16840. 0) {
  16841. ::close(client_fd);
  16842. ::close(origin_fd);
  16843. continue;
  16844. }
  16845. auto forward = [](int from, int to) {
  16846. char b[8192];
  16847. for (;;) {
  16848. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16849. if (n <= 0) { break; }
  16850. ssize_t off = 0;
  16851. while (off < n) {
  16852. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16853. if (s <= 0) {
  16854. off = n;
  16855. break;
  16856. }
  16857. off += s;
  16858. }
  16859. }
  16860. ::shutdown(to, SHUT_WR);
  16861. };
  16862. std::thread t1([&] { forward(client_fd, origin_fd); });
  16863. std::thread t2([&] { forward(origin_fd, client_fd); });
  16864. t1.join();
  16865. t2.join();
  16866. ::close(client_fd);
  16867. ::close(origin_fd);
  16868. }
  16869. }
  16870. int forward_port_ = -1;
  16871. int listen_fd_ = -1;
  16872. int port_ = 0;
  16873. std::thread th_;
  16874. std::atomic<bool> stop_{false};
  16875. std::atomic<int> connect_hits_{0};
  16876. };
  16877. } // namespace proxy_tunnel_test
  16878. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16879. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16880. // retry; otherwise proxy creds would be sent to the origin.
  16881. std::atomic<int> origin_hits{0};
  16882. std::atomic<bool> origin_saw_proxy_authz{false};
  16883. proxy_tunnel_test::ScopedSSLServer origin;
  16884. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16885. origin_hits++;
  16886. if (req.has_header("Proxy-Authorization")) {
  16887. origin_saw_proxy_authz = true;
  16888. }
  16889. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16890. res.set_header("Proxy-Authenticate",
  16891. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16892. "algorithm=MD5");
  16893. });
  16894. origin.listen();
  16895. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16896. ASSERT_NE(0, proxy.port());
  16897. SSLClient cli(HOST, origin.port());
  16898. cli.enable_server_certificate_verification(false);
  16899. cli.set_proxy(HOST, proxy.port());
  16900. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16901. auto res = cli.Get("/x");
  16902. ASSERT_TRUE(res);
  16903. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16904. EXPECT_EQ(1, origin_hits.load());
  16905. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16906. EXPECT_EQ(1, proxy.connect_hits());
  16907. }
  16908. #endif