test.cc 585 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052
  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_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(DivideTest, DivideStringTests) {
  666. auto divide = [](const std::string &str, char d) {
  667. std::string lhs;
  668. std::string rhs;
  669. detail::divide(str, d,
  670. [&](const char *lhs_data, std::size_t lhs_size,
  671. const char *rhs_data, std::size_t rhs_size) {
  672. lhs.assign(lhs_data, lhs_size);
  673. rhs.assign(rhs_data, rhs_size);
  674. });
  675. return std::make_pair(std::move(lhs), std::move(rhs));
  676. };
  677. {
  678. const auto res = divide("", '=');
  679. EXPECT_EQ(res.first, "");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "");
  686. }
  687. {
  688. const auto res = divide(" ", '=');
  689. EXPECT_EQ(res.first, " ");
  690. EXPECT_EQ(res.second, "");
  691. }
  692. {
  693. const auto res = divide("a", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "");
  696. }
  697. {
  698. const auto res = divide("a=", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "");
  701. }
  702. {
  703. const auto res = divide("=b", '=');
  704. EXPECT_EQ(res.first, "");
  705. EXPECT_EQ(res.second, "b");
  706. }
  707. {
  708. const auto res = divide("a=b", '=');
  709. EXPECT_EQ(res.first, "a");
  710. EXPECT_EQ(res.second, "b");
  711. }
  712. {
  713. const auto res = divide("a=b=", '=');
  714. EXPECT_EQ(res.first, "a");
  715. EXPECT_EQ(res.second, "b=");
  716. }
  717. {
  718. const auto res = divide("a=b=c", '=');
  719. EXPECT_EQ(res.first, "a");
  720. EXPECT_EQ(res.second, "b=c");
  721. }
  722. }
  723. TEST(SplitTest, ParseQueryString) {
  724. string s = "key1=val1&key2=val2&key3=val3";
  725. Params dic;
  726. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  727. [&](const char *b, const char *e) {
  728. string key, val;
  729. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  730. if (key.empty()) {
  731. key.assign(b2, e2);
  732. } else {
  733. val.assign(b2, e2);
  734. }
  735. });
  736. dic.emplace(key, val);
  737. });
  738. EXPECT_EQ("val1", dic.find("key1")->second);
  739. EXPECT_EQ("val2", dic.find("key2")->second);
  740. EXPECT_EQ("val3", dic.find("key3")->second);
  741. }
  742. TEST(SplitTest, ParseInvalidQueryTests) {
  743. {
  744. string s = " ";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. {
  750. string s = " = =";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. }
  756. TEST(ParseQueryTest, ParseQueryString) {
  757. {
  758. std::string s = "key1=val1&key2=val2&key3=val3";
  759. Params dic;
  760. detail::parse_query_text(s, dic);
  761. EXPECT_EQ("val1", dic.find("key1")->second);
  762. EXPECT_EQ("val2", dic.find("key2")->second);
  763. EXPECT_EQ("val3", dic.find("key3")->second);
  764. }
  765. {
  766. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  767. Params dic;
  768. detail::parse_query_text(s, dic);
  769. EXPECT_EQ("", dic.find("key1")->second);
  770. EXPECT_EQ("val1", dic.find("key2")->second);
  771. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  772. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  773. }
  774. }
  775. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  776. Params dic;
  777. EXPECT_EQ(detail::params_to_query_str(dic), "");
  778. dic.emplace("key1", "val1");
  779. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  780. dic.emplace("key2", "val2");
  781. dic.emplace("key3", "val3");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  783. }
  784. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  785. string content_type = "multipart/form-data; boundary=something";
  786. string boundary;
  787. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(boundary, "something");
  790. }
  791. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  792. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  793. string boundary;
  794. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  795. EXPECT_TRUE(ret);
  796. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  797. }
  798. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  799. string content_type =
  800. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  801. string boundary;
  802. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  803. EXPECT_TRUE(ret);
  804. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  805. }
  806. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  807. string content_type =
  808. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  809. string boundary;
  810. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  811. EXPECT_TRUE(ret);
  812. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  813. }
  814. TEST(GetHeaderValueTest, DefaultValue) {
  815. Headers headers = {{"Dummy", "Dummy"}};
  816. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  817. EXPECT_STREQ("text/plain", val);
  818. }
  819. TEST(GetHeaderValueTest, DefaultValueInt) {
  820. Headers headers = {{"Dummy", "Dummy"}};
  821. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  822. EXPECT_EQ(100ull, val);
  823. }
  824. TEST(GetHeaderValueTest, RegularValue) {
  825. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  826. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  827. EXPECT_STREQ("text/html", val);
  828. }
  829. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  830. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  832. EXPECT_STREQ("text/html", val);
  833. }
  834. TEST(GetHeaderValueTest, SetContent) {
  835. Response res;
  836. res.set_content("html", "text/html");
  837. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  838. res.set_content("text", "text/plain");
  839. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  840. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  841. }
  842. TEST(GetHeaderValueTest, RegularValueInt) {
  843. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  845. EXPECT_EQ(100ull, val);
  846. }
  847. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  848. Headers headers = {{"Content-Length", "x"}};
  849. auto is_invalid_value = false;
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  851. is_invalid_value);
  852. EXPECT_EQ(0ull, val);
  853. EXPECT_TRUE(is_invalid_value);
  854. }
  855. TEST(GetHeaderValueTest, Range) {
  856. {
  857. Headers headers = {make_range_header({{1, -1}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=-1", val);
  865. }
  866. {
  867. Headers headers = {make_range_header({{1, 10}})};
  868. auto val = detail::get_header_value(headers, "Range", 0, 0);
  869. EXPECT_STREQ("bytes=1-10", val);
  870. }
  871. {
  872. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  873. auto val = detail::get_header_value(headers, "Range", 0, 0);
  874. EXPECT_STREQ("bytes=1-10, 100-", val);
  875. }
  876. {
  877. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  878. auto val = detail::get_header_value(headers, "Range", 0, 0);
  879. EXPECT_STREQ("bytes=1-10, 100-200", val);
  880. }
  881. {
  882. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  883. auto val = detail::get_header_value(headers, "Range", 0, 0);
  884. EXPECT_STREQ("bytes=0-0, -1", val);
  885. }
  886. }
  887. TEST(ParseHeaderValueTest, Range) {
  888. {
  889. Ranges ranges;
  890. auto ret = detail::parse_range_header("bytes=1-", ranges);
  891. EXPECT_TRUE(ret);
  892. EXPECT_EQ(1u, ranges.size());
  893. EXPECT_EQ(1u, ranges[0].first);
  894. EXPECT_EQ(-1, ranges[0].second);
  895. }
  896. {
  897. Ranges ranges;
  898. auto ret = detail::parse_range_header("bytes=-1", ranges);
  899. EXPECT_TRUE(ret);
  900. EXPECT_EQ(1u, ranges.size());
  901. EXPECT_EQ(-1, ranges[0].first);
  902. EXPECT_EQ(1u, ranges[0].second);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(1u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. }
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  915. EXPECT_FALSE(ret);
  916. }
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(2u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(-1, ranges[1].second);
  926. }
  927. {
  928. Ranges ranges;
  929. auto ret =
  930. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(3u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. EXPECT_EQ(100u, ranges[1].first);
  936. EXPECT_EQ(200u, ranges[1].second);
  937. EXPECT_EQ(300u, ranges[2].first);
  938. EXPECT_EQ(400u, ranges[2].second);
  939. }
  940. {
  941. Ranges ranges;
  942. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  955. EXPECT_TRUE(ranges.empty());
  956. }
  957. }
  958. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  966. #else
  967. EXPECT_TRUE(ret == detail::EncodingType::None);
  968. #endif
  969. }
  970. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  971. Request req;
  972. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  973. Response res;
  974. res.set_header("Content-Type", "text/plain");
  975. auto ret = detail::encoding_type(req, res);
  976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  978. #elif CPPHTTPLIB_ZLIB_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  980. #elif CPPHTTPLIB_ZSTD_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  982. #else
  983. EXPECT_TRUE(ret == detail::EncodingType::None);
  984. #endif
  985. }
  986. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  987. Request req;
  988. req.set_header("Accept-Encoding",
  989. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  995. #elif CPPHTTPLIB_ZLIB_SUPPORT
  996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  997. #elif CPPHTTPLIB_ZSTD_SUPPORT
  998. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  999. #else
  1000. EXPECT_TRUE(ret == detail::EncodingType::None);
  1001. #endif
  1002. }
  1003. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1004. // All supported encodings rejected with q=0 should return None
  1005. Request req;
  1006. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1007. Response res;
  1008. res.set_header("Content-Type", "text/plain");
  1009. auto ret = detail::encoding_type(req, res);
  1010. EXPECT_TRUE(ret == detail::EncodingType::None);
  1011. }
  1012. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1013. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1014. Request req;
  1015. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1016. Response res;
  1017. res.set_header("Content-Type", "text/plain");
  1018. auto ret = detail::encoding_type(req, res);
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. }
  1021. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1022. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1023. Request req;
  1024. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1025. Response res;
  1026. res.set_header("Content-Type", "text/plain");
  1027. auto ret = detail::encoding_type(req, res);
  1028. EXPECT_TRUE(ret == detail::EncodingType::None);
  1029. }
  1030. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1031. // RFC 7231: Accept-Encoding values are case-insensitive
  1032. Request req;
  1033. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1034. Response res;
  1035. res.set_header("Content-Type", "text/plain");
  1036. auto ret = detail::encoding_type(req, res);
  1037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1043. #else
  1044. EXPECT_TRUE(ret == detail::EncodingType::None);
  1045. #endif
  1046. }
  1047. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1048. // q value should determine priority, not hardcoded order
  1049. Request req;
  1050. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1051. Response res;
  1052. res.set_header("Content-Type", "text/plain");
  1053. auto ret = detail::encoding_type(req, res);
  1054. // gzip has highest q=1.0, so it should be selected even though
  1055. // br and zstd are also supported
  1056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1060. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1062. #else
  1063. EXPECT_TRUE(ret == detail::EncodingType::None);
  1064. #endif
  1065. }
  1066. TEST(BufferStreamTest, read) {
  1067. detail::BufferStream strm1;
  1068. Stream &strm = strm1;
  1069. EXPECT_EQ(5, strm.write("hello"));
  1070. char buf[512];
  1071. EXPECT_EQ(2, strm.read(buf, 2));
  1072. EXPECT_EQ('h', buf[0]);
  1073. EXPECT_EQ('e', buf[1]);
  1074. EXPECT_EQ(2, strm.read(buf, 2));
  1075. EXPECT_EQ('l', buf[0]);
  1076. EXPECT_EQ('l', buf[1]);
  1077. EXPECT_EQ(1, strm.read(buf, 1));
  1078. EXPECT_EQ('o', buf[0]);
  1079. EXPECT_EQ(0, strm.read(buf, 1));
  1080. }
  1081. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1082. auto host = "www.httpwatch.com";
  1083. auto ip = hosted_at(host);
  1084. EXPECT_EQ("23.96.13.243", ip);
  1085. std::vector<std::string> addrs;
  1086. hosted_at(host, addrs);
  1087. EXPECT_EQ(1u, addrs.size());
  1088. }
  1089. #if 0 // It depends on each test environment...
  1090. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1091. auto host = "www.youtube.com";
  1092. std::vector<std::string> addrs;
  1093. hosted_at(host, addrs);
  1094. EXPECT_EQ(20u, addrs.size());
  1095. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1096. EXPECT_TRUE(it != addrs.end());
  1097. }
  1098. #endif
  1099. class ChunkedEncodingTest : public ::testing::Test {
  1100. protected:
  1101. ChunkedEncodingTest()
  1102. : cli_(HOST, PORT)
  1103. #ifdef CPPHTTPLIB_SSL_ENABLED
  1104. ,
  1105. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1106. #endif
  1107. {
  1108. cli_.set_connection_timeout(2);
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. cli_.enable_server_certificate_verification(false);
  1111. #endif
  1112. }
  1113. virtual void SetUp() {
  1114. read_file("./image.jpg", image_data_);
  1115. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. svr_.Get(
  1119. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1120. res.set_chunked_content_provider(
  1121. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1122. size_t remaining = image_data_.size() - offset;
  1123. if (remaining == 0) {
  1124. sink.done();
  1125. } else {
  1126. constexpr size_t CHUNK_SIZE = 1024;
  1127. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1128. sink.write(&image_data_[offset], send_size);
  1129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1130. }
  1131. return true;
  1132. });
  1133. });
  1134. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1135. svr_.wait_until_ready();
  1136. }
  1137. virtual void TearDown() {
  1138. svr_.stop();
  1139. if (!request_threads_.empty()) {
  1140. std::this_thread::sleep_for(std::chrono::seconds(1));
  1141. for (auto &t : request_threads_) {
  1142. t.join();
  1143. }
  1144. }
  1145. t_.join();
  1146. }
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. SSLClient cli_;
  1149. SSLServer svr_;
  1150. #else
  1151. Client cli_;
  1152. Server svr_;
  1153. #endif
  1154. thread t_;
  1155. std::vector<thread> request_threads_;
  1156. std::string image_data_;
  1157. };
  1158. TEST_F(ChunkedEncodingTest, NormalGet) {
  1159. auto res = cli_.Get("/chunked");
  1160. ASSERT_TRUE(res);
  1161. std::string out;
  1162. read_file("./image.jpg", out);
  1163. EXPECT_EQ(StatusCode::OK_200, res->status);
  1164. EXPECT_EQ(out, res->body);
  1165. }
  1166. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1167. std::string body;
  1168. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1169. body.append(data, data_length);
  1170. return true;
  1171. });
  1172. ASSERT_TRUE(res);
  1173. std::string out;
  1174. read_file("./image.jpg", out);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. EXPECT_EQ(out, body);
  1177. }
  1178. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1179. std::string body;
  1180. auto res = cli_.Get(
  1181. "/chunked",
  1182. [&](const Response &response) {
  1183. EXPECT_EQ(StatusCode::OK_200, response.status);
  1184. return true;
  1185. },
  1186. [&](const char *data, size_t data_length) {
  1187. body.append(data, data_length);
  1188. return true;
  1189. });
  1190. ASSERT_TRUE(res);
  1191. std::string out;
  1192. read_file("./image.jpg", out);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. EXPECT_EQ(out, body);
  1195. }
  1196. TEST(RangeTest, FromHTTPBin_Online) {
  1197. auto host = "httpbingo.org";
  1198. auto path = std::string{"/range/32"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(5);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_TRUE(res);
  1210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. }
  1213. {
  1214. Headers headers = {make_range_header({{1, -1}})};
  1215. auto res = cli.Get(path, headers);
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1219. }
  1220. {
  1221. Headers headers = {make_range_header({{1, 10}})};
  1222. auto res = cli.Get(path, headers);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("bcdefghijk", res->body);
  1225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1226. }
  1227. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1228. // entire resource, while the original httpbin returned 200. Both are
  1229. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1230. {
  1231. Headers headers = {make_range_header({{0, 31}})};
  1232. auto res = cli.Get(path, headers);
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1235. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1236. res->status == StatusCode::PartialContent_206);
  1237. }
  1238. {
  1239. Headers headers = {make_range_header({{0, -1}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1243. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1244. res->status == StatusCode::PartialContent_206);
  1245. }
  1246. // go-httpbin returns 206 with clamped range for over-range requests,
  1247. // while the original httpbin returned 416. Both behaviors are observed
  1248. // in real servers, so we only verify the request succeeds.
  1249. {
  1250. Headers headers = {make_range_header({{0, 32}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. }
  1254. }
  1255. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1256. auto host = "unresolvableaddress.local";
  1257. auto path = std::string{"/"};
  1258. #ifdef CPPHTTPLIB_SSL_ENABLED
  1259. auto port = 443;
  1260. SSLClient cli(host, port);
  1261. #else
  1262. auto port = 80;
  1263. Client cli(host, port);
  1264. #endif
  1265. cli.set_connection_timeout(1);
  1266. {
  1267. auto res = cli.Get(path);
  1268. ASSERT_FALSE(res);
  1269. }
  1270. std::this_thread::sleep_for(std::chrono::seconds(8));
  1271. }
  1272. #if defined(__linux__) && defined(__GLIBC__) && \
  1273. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1274. // Forward declaration: in split builds split.py strips `inline` and moves the
  1275. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1276. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1277. // against the symbol in both header-only and split builds.
  1278. namespace httplib {
  1279. namespace detail {
  1280. int getaddrinfo_with_timeout(const char *node, const char *service,
  1281. const struct addrinfo *hints,
  1282. struct addrinfo **res, time_t timeout_sec);
  1283. } // namespace detail
  1284. } // namespace httplib
  1285. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1286. //
  1287. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1288. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1289. // gai_suspend() call hits the connection timeout the function calls
  1290. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1291. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1292. // still alive and still references the now-destroyed stack frame.
  1293. //
  1294. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1295. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1296. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1297. // and runs them in a container.
  1298. namespace {
  1299. bool should_run_issue_2431_tests() {
  1300. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1301. return v && *v && std::string(v) != "0";
  1302. }
  1303. std::string unique_unresolvable_host(int n) {
  1304. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1305. // glibc still asks the configured nameserver — which is exactly the path
  1306. // we want to exercise. A unique label per call avoids the resolver cache.
  1307. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1308. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1309. std::to_string(n) + ".invalid";
  1310. }
  1311. } // namespace
  1312. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1313. if (!should_run_issue_2431_tests()) {
  1314. GTEST_SKIP()
  1315. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1316. }
  1317. for (int i = 0; i < 8; ++i) {
  1318. struct addrinfo hints;
  1319. memset(&hints, 0, sizeof(hints));
  1320. hints.ai_family = AF_UNSPEC;
  1321. hints.ai_socktype = SOCK_STREAM;
  1322. auto host = unique_unresolvable_host(i);
  1323. struct addrinfo *result = nullptr;
  1324. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1325. &result, /*timeout_sec=*/1);
  1326. if (rc == 0 && result) { freeaddrinfo(result); }
  1327. }
  1328. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1329. // stack region they still believe holds their gaicb.
  1330. std::this_thread::sleep_for(std::chrono::seconds(3));
  1331. }
  1332. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1333. if (!should_run_issue_2431_tests()) {
  1334. GTEST_SKIP()
  1335. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1336. }
  1337. std::atomic<bool> stop{false};
  1338. std::vector<std::thread> threads;
  1339. for (int t = 0; t < 8; ++t) {
  1340. threads.emplace_back([t, &stop] {
  1341. int i = 0;
  1342. while (!stop.load(std::memory_order_relaxed)) {
  1343. struct addrinfo hints;
  1344. memset(&hints, 0, sizeof(hints));
  1345. hints.ai_family = AF_UNSPEC;
  1346. hints.ai_socktype = SOCK_STREAM;
  1347. auto host = unique_unresolvable_host(t * 100000 + i++);
  1348. struct addrinfo *result = nullptr;
  1349. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1350. &result, /*timeout_sec=*/1);
  1351. if (rc == 0 && result) { freeaddrinfo(result); }
  1352. }
  1353. });
  1354. }
  1355. std::this_thread::sleep_for(std::chrono::seconds(8));
  1356. stop.store(true, std::memory_order_relaxed);
  1357. for (auto &th : threads) {
  1358. th.join();
  1359. }
  1360. std::this_thread::sleep_for(std::chrono::seconds(3));
  1361. }
  1362. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1363. if (!should_run_issue_2431_tests()) {
  1364. GTEST_SKIP()
  1365. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1366. }
  1367. std::atomic<bool> stop{false};
  1368. std::vector<std::thread> threads;
  1369. for (int t = 0; t < 8; ++t) {
  1370. threads.emplace_back([t, &stop] {
  1371. int i = 0;
  1372. while (!stop.load(std::memory_order_relaxed)) {
  1373. auto host = unique_unresolvable_host(t * 100000 + i++);
  1374. Client cli(host, 80);
  1375. cli.set_connection_timeout(1, 0);
  1376. cli.set_read_timeout(1, 0);
  1377. cli.set_write_timeout(1, 0);
  1378. (void)cli.Get("/");
  1379. }
  1380. });
  1381. }
  1382. std::this_thread::sleep_for(std::chrono::seconds(8));
  1383. stop.store(true, std::memory_order_relaxed);
  1384. for (auto &th : threads) {
  1385. th.join();
  1386. }
  1387. std::this_thread::sleep_for(std::chrono::seconds(3));
  1388. }
  1389. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1390. TEST(ConnectionErrorTest, InvalidHost) {
  1391. auto host = "-abcde.com";
  1392. #ifdef CPPHTTPLIB_SSL_ENABLED
  1393. auto port = 443;
  1394. SSLClient cli(host, port);
  1395. #else
  1396. auto port = 80;
  1397. Client cli(host, port);
  1398. #endif
  1399. cli.set_connection_timeout(std::chrono::seconds(2));
  1400. auto res = cli.Get("/");
  1401. ASSERT_TRUE(!res);
  1402. EXPECT_EQ(Error::Connection, res.error());
  1403. }
  1404. TEST(ConnectionErrorTest, InvalidHost2) {
  1405. auto host = "httpcan.org/";
  1406. #ifdef CPPHTTPLIB_SSL_ENABLED
  1407. SSLClient cli(host);
  1408. #else
  1409. Client cli(host);
  1410. #endif
  1411. cli.set_connection_timeout(std::chrono::seconds(2));
  1412. auto res = cli.Get("/");
  1413. ASSERT_TRUE(!res);
  1414. EXPECT_EQ(Error::Connection, res.error());
  1415. }
  1416. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1417. auto host = "httpcan.org/";
  1418. #ifdef CPPHTTPLIB_SSL_ENABLED
  1419. SSLClient cli(host);
  1420. #else
  1421. Client cli(host);
  1422. #endif
  1423. cli.set_connection_timeout(std::chrono::seconds(2));
  1424. auto res = cli.Get("/");
  1425. ASSERT_TRUE(!res);
  1426. stringstream s;
  1427. s << "error code: " << res.error();
  1428. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1429. }
  1430. TEST(ConnectionErrorTest, InvalidPort) {
  1431. auto host = "localhost";
  1432. auto port = 44380;
  1433. #ifdef CPPHTTPLIB_SSL_ENABLED
  1434. SSLClient cli(host, port);
  1435. #else
  1436. Client cli(host, port);
  1437. #endif
  1438. cli.set_connection_timeout(std::chrono::seconds(2));
  1439. auto res = cli.Get("/");
  1440. ASSERT_TRUE(!res);
  1441. EXPECT_TRUE(Error::Connection == res.error() ||
  1442. Error::ConnectionTimeout == res.error());
  1443. }
  1444. TEST(ConnectionErrorTest, Timeout_Online) {
  1445. auto host = "google.com";
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 44380;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 8080;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(std::chrono::seconds(2));
  1454. // only probe one address type so that the error reason
  1455. // correlates to the timed-out IPv4, not the unsupported
  1456. // IPv6 connection attempt
  1457. cli.set_address_family(AF_INET);
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1461. }
  1462. TEST(CancelTest, NoCancel_Online) {
  1463. auto host = "httpbingo.org";
  1464. auto path = std::string{"/range/32"};
  1465. #ifdef CPPHTTPLIB_SSL_ENABLED
  1466. auto port = 443;
  1467. SSLClient cli(host, port);
  1468. #else
  1469. auto port = 80;
  1470. Client cli(host, port);
  1471. #endif
  1472. cli.set_connection_timeout(std::chrono::seconds(5));
  1473. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1479. // Use /bytes with a large payload so that the DownloadProgress callback
  1480. // (which only fires for Content-Length responses) is invoked before the
  1481. // entire body is received, giving cancellation a chance to fire.
  1482. auto host = "httpbingo.org";
  1483. auto path = std::string{"/bytes/524288"};
  1484. #ifdef CPPHTTPLIB_SSL_ENABLED
  1485. auto port = 443;
  1486. SSLClient cli(host, port);
  1487. #else
  1488. auto port = 80;
  1489. Client cli(host, port);
  1490. #endif
  1491. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. ASSERT_TRUE(!res);
  1494. EXPECT_EQ(Error::Canceled, res.error());
  1495. }
  1496. TEST(CancelTest, WithCancelLargePayload_Online) {
  1497. auto host = "httpbingo.org";
  1498. auto path = std::string{"/bytes/524288"};
  1499. #ifdef CPPHTTPLIB_SSL_ENABLED
  1500. auto port = 443;
  1501. SSLClient cli(host, port);
  1502. #else
  1503. auto port = 80;
  1504. Client cli(host, port);
  1505. #endif
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. uint32_t count = 0;
  1508. auto res =
  1509. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelPost) {
  1514. Server svr;
  1515. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1535. Server svr;
  1536. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadPost) {
  1555. Server svr;
  1556. svr.set_payload_max_length(200 * 1024 * 1024);
  1557. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content(LARGE_DATA, "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_payload_max_length(200 * 1024 * 1024);
  1569. cli.set_connection_timeout(std::chrono::seconds(5));
  1570. auto res =
  1571. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1572. "application/json", [](uint64_t, uint64_t) { return false; });
  1573. ASSERT_TRUE(!res);
  1574. EXPECT_EQ(Error::Canceled, res.error());
  1575. }
  1576. TEST(CancelTest, NoCancelPut) {
  1577. Server svr;
  1578. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content("Hello World!", "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_connection_timeout(std::chrono::seconds(5));
  1590. auto res =
  1591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1592. "application/json", [](uint64_t, uint64_t) { return true; });
  1593. ASSERT_TRUE(res);
  1594. EXPECT_EQ("Hello World!", res->body);
  1595. EXPECT_EQ(StatusCode::OK_200, res->status);
  1596. }
  1597. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1598. Server svr;
  1599. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1600. res.set_content("Hello World!", "text/plain");
  1601. });
  1602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. thread.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. Client cli(HOST, PORT);
  1610. cli.set_connection_timeout(std::chrono::seconds(5));
  1611. auto res =
  1612. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1613. "application/json", [](uint64_t, uint64_t) { return false; });
  1614. ASSERT_TRUE(!res);
  1615. EXPECT_EQ(Error::Canceled, res.error());
  1616. }
  1617. TEST(CancelTest, WithCancelLargePayloadPut) {
  1618. Server svr;
  1619. svr.set_payload_max_length(200 * 1024 * 1024);
  1620. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1621. res.set_content(LARGE_DATA, "text/plain");
  1622. });
  1623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1624. auto se = detail::scope_exit([&] {
  1625. svr.stop();
  1626. thread.join();
  1627. ASSERT_FALSE(svr.is_running());
  1628. });
  1629. svr.wait_until_ready();
  1630. Client cli(HOST, PORT);
  1631. cli.set_payload_max_length(200 * 1024 * 1024);
  1632. cli.set_connection_timeout(std::chrono::seconds(5));
  1633. auto res =
  1634. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1635. "application/json", [](uint64_t, uint64_t) { return false; });
  1636. ASSERT_TRUE(!res);
  1637. EXPECT_EQ(Error::Canceled, res.error());
  1638. }
  1639. TEST(CancelTest, NoCancelPatch) {
  1640. Server svr;
  1641. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1642. res.set_content("Hello World!", "text/plain");
  1643. });
  1644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1645. auto se = detail::scope_exit([&] {
  1646. svr.stop();
  1647. thread.join();
  1648. ASSERT_FALSE(svr.is_running());
  1649. });
  1650. svr.wait_until_ready();
  1651. Client cli(HOST, PORT);
  1652. cli.set_connection_timeout(std::chrono::seconds(5));
  1653. auto res =
  1654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1655. "application/json", [](uint64_t, uint64_t) { return true; });
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ("Hello World!", res->body);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1661. Server svr;
  1662. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1663. res.set_content("Hello World!", "text/plain");
  1664. });
  1665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1666. auto se = detail::scope_exit([&] {
  1667. svr.stop();
  1668. thread.join();
  1669. ASSERT_FALSE(svr.is_running());
  1670. });
  1671. svr.wait_until_ready();
  1672. Client cli(HOST, PORT);
  1673. cli.set_connection_timeout(std::chrono::seconds(5));
  1674. auto res =
  1675. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1676. "application/json", [](uint64_t, uint64_t) { return false; });
  1677. ASSERT_TRUE(!res);
  1678. EXPECT_EQ(Error::Canceled, res.error());
  1679. }
  1680. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1681. Server svr;
  1682. svr.set_payload_max_length(200 * 1024 * 1024);
  1683. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1684. res.set_content(LARGE_DATA, "text/plain");
  1685. });
  1686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. thread.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. Client cli(HOST, PORT);
  1694. cli.set_payload_max_length(200 * 1024 * 1024);
  1695. cli.set_connection_timeout(std::chrono::seconds(5));
  1696. auto res =
  1697. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1698. "application/json", [](uint64_t, uint64_t) { return false; });
  1699. ASSERT_TRUE(!res);
  1700. EXPECT_EQ(Error::Canceled, res.error());
  1701. }
  1702. TEST(CancelTest, NoCancelDelete) {
  1703. Server svr;
  1704. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1705. res.set_content("Hello World!", "text/plain");
  1706. });
  1707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1708. auto se = detail::scope_exit([&] {
  1709. svr.stop();
  1710. thread.join();
  1711. ASSERT_FALSE(svr.is_running());
  1712. });
  1713. svr.wait_until_ready();
  1714. Client cli(HOST, PORT);
  1715. cli.set_connection_timeout(std::chrono::seconds(5));
  1716. auto res =
  1717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1718. "application/json", [](uint64_t, uint64_t) { return true; });
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ("Hello World!", res->body);
  1721. EXPECT_EQ(StatusCode::OK_200, res->status);
  1722. }
  1723. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1724. Server svr;
  1725. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1726. res.set_content("Hello World!", "text/plain");
  1727. });
  1728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1729. auto se = detail::scope_exit([&] {
  1730. svr.stop();
  1731. thread.join();
  1732. ASSERT_FALSE(svr.is_running());
  1733. });
  1734. svr.wait_until_ready();
  1735. Client cli(HOST, PORT);
  1736. cli.set_connection_timeout(std::chrono::seconds(5));
  1737. auto res =
  1738. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1739. "application/json", [](uint64_t, uint64_t) { return false; });
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1744. Server svr;
  1745. svr.set_payload_max_length(200 * 1024 * 1024);
  1746. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content(LARGE_DATA, "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. Client cli(HOST, PORT);
  1757. cli.set_payload_max_length(200 * 1024 * 1024);
  1758. cli.set_connection_timeout(std::chrono::seconds(5));
  1759. auto res =
  1760. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1761. "application/json", [](uint64_t, uint64_t) { return false; });
  1762. ASSERT_TRUE(!res);
  1763. EXPECT_EQ(Error::Canceled, res.error());
  1764. }
  1765. static std::string remove_whitespace(const std::string &input) {
  1766. std::string output;
  1767. output.reserve(input.size());
  1768. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1769. [](unsigned char c) { return !std::isspace(c); });
  1770. return output;
  1771. }
  1772. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1773. auto host = "httpbingo.org";
  1774. auto path = std::string{"/basic-auth/hello/world"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. {
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1786. }
  1787. {
  1788. auto res =
  1789. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1790. ASSERT_TRUE(res);
  1791. auto body = remove_whitespace(res->body);
  1792. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1793. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. {
  1797. cli.set_basic_auth("hello", "world");
  1798. auto res = cli.Get(path);
  1799. ASSERT_TRUE(res);
  1800. auto body = remove_whitespace(res->body);
  1801. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1802. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1803. EXPECT_EQ(StatusCode::OK_200, res->status);
  1804. }
  1805. {
  1806. cli.set_basic_auth("hello", "bad");
  1807. auto res = cli.Get(path);
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1810. }
  1811. {
  1812. cli.set_basic_auth("bad", "world");
  1813. auto res = cli.Get(path);
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1816. }
  1817. }
  1818. #ifdef CPPHTTPLIB_SSL_ENABLED
  1819. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1820. auto host = "httpbingo.org";
  1821. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1822. auto paths = std::vector<std::string>{
  1823. "/digest-auth/auth/hello/world/MD5",
  1824. "/digest-auth/auth/hello/world/SHA-256",
  1825. };
  1826. auto port = 443;
  1827. SSLClient cli(host, port);
  1828. {
  1829. auto res = cli.Get(unauth_path);
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1832. }
  1833. {
  1834. cli.set_digest_auth("hello", "world");
  1835. for (const auto &path : paths) {
  1836. auto res = cli.Get(path.c_str());
  1837. ASSERT_TRUE(res);
  1838. auto body = remove_whitespace(res->body);
  1839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. cli.set_digest_auth("hello", "bad");
  1844. for (const auto &path : paths) {
  1845. auto res = cli.Get(path.c_str());
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1848. }
  1849. }
  1850. }
  1851. #endif
  1852. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1853. auto host = "google.com";
  1854. auto another_host = "example.com";
  1855. auto wrong_ip = "0.0.0.0";
  1856. #ifdef CPPHTTPLIB_SSL_ENABLED
  1857. SSLClient cli(host);
  1858. #else
  1859. Client cli(host);
  1860. #endif
  1861. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1862. auto res = cli.Get("/");
  1863. ASSERT_TRUE(res);
  1864. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1865. }
  1866. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1867. auto host = "google.com";
  1868. auto wrong_ip = "0.0.0.0";
  1869. #ifdef CPPHTTPLIB_SSL_ENABLED
  1870. SSLClient cli(host);
  1871. #else
  1872. Client cli(host);
  1873. #endif
  1874. cli.set_hostname_addr_map({{host, wrong_ip}});
  1875. auto res = cli.Get("/");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::Connection, res.error());
  1878. }
  1879. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1880. auto host = "httpbingo.org";
  1881. auto path = std::string{"/absolute-redirect/3"};
  1882. #ifdef CPPHTTPLIB_SSL_ENABLED
  1883. SSLClient cli(host);
  1884. #else
  1885. Client cli(host);
  1886. #endif
  1887. cli.set_follow_location(true);
  1888. auto res = cli.Get(path);
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::OK_200, res->status);
  1891. }
  1892. TEST(RedirectTest, Redirect_Online) {
  1893. auto host = "httpbingo.org";
  1894. auto path = std::string{"/redirect/3"};
  1895. #ifdef CPPHTTPLIB_SSL_ENABLED
  1896. SSLClient cli(host);
  1897. #else
  1898. Client cli(host);
  1899. #endif
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get(path);
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. }
  1905. TEST(RelativeRedirectTest, Redirect_Online) {
  1906. auto host = "httpbingo.org";
  1907. auto path = std::string{"/relative-redirect/3"};
  1908. #ifdef CPPHTTPLIB_SSL_ENABLED
  1909. SSLClient cli(host);
  1910. #else
  1911. Client cli(host);
  1912. #endif
  1913. cli.set_follow_location(true);
  1914. auto res = cli.Get(path);
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::OK_200, res->status);
  1917. }
  1918. TEST(TooManyRedirectTest, Redirect_Online) {
  1919. auto host = "httpbingo.org";
  1920. auto path = std::string{"/redirect/21"};
  1921. #ifdef CPPHTTPLIB_SSL_ENABLED
  1922. SSLClient cli(host);
  1923. #else
  1924. Client cli(host);
  1925. #endif
  1926. cli.set_follow_location(true);
  1927. auto res = cli.Get(path);
  1928. ASSERT_TRUE(!res);
  1929. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1930. }
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. TEST(YahooRedirectTest, Redirect_Online) {
  1933. Client cli("yahoo.com");
  1934. auto res = cli.Get("/");
  1935. ASSERT_TRUE(res);
  1936. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1937. cli.set_follow_location(true);
  1938. res = cli.Get("/");
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(StatusCode::OK_200, res->status);
  1941. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1942. }
  1943. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1944. #define REDIR_HOST "httpbingo.org"
  1945. #define REDIR_PATH "/redirect-to"
  1946. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1947. SSLClient cli(REDIR_HOST);
  1948. cli.set_follow_location(true);
  1949. auto res =
  1950. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. }
  1954. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1955. SSLClient cli(REDIR_HOST);
  1956. cli.set_follow_location(true);
  1957. Params params;
  1958. params.emplace("url", "http://example.com");
  1959. params.emplace("status_code", "302");
  1960. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. }
  1964. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1965. SSLClient cli(REDIR_HOST);
  1966. cli.set_follow_location(true);
  1967. Params params;
  1968. params.emplace("url", "http://example.com");
  1969. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. }
  1973. TEST(UrlWithSpace, Redirect_Online) {
  1974. SSLClient cli("edge.forgecdn.net");
  1975. cli.set_follow_location(true);
  1976. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(StatusCode::OK_200, res->status);
  1979. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1980. }
  1981. #endif
  1982. #if !defined(_WIN32) && !defined(_WIN64)
  1983. TEST(ReceiveSignals, Signal) {
  1984. auto setupSignalHandlers = []() {
  1985. struct sigaction act;
  1986. sigemptyset(&act.sa_mask);
  1987. act.sa_flags = SA_SIGINFO;
  1988. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1989. switch (sig) {
  1990. case SIGINT:
  1991. default: break;
  1992. }
  1993. };
  1994. ::sigaction(SIGINT, &act, nullptr);
  1995. };
  1996. Server svr;
  1997. int port = 0;
  1998. auto thread = std::thread([&]() {
  1999. setupSignalHandlers();
  2000. port = svr.bind_to_any_port(HOST);
  2001. svr.listen_after_bind();
  2002. });
  2003. auto se = detail::scope_exit([&] {
  2004. svr.stop();
  2005. thread.join();
  2006. ASSERT_FALSE(svr.is_running());
  2007. });
  2008. svr.wait_until_ready();
  2009. ASSERT_TRUE(svr.is_running());
  2010. pthread_kill(thread.native_handle(), SIGINT);
  2011. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2012. ASSERT_TRUE(svr.is_running());
  2013. }
  2014. #endif
  2015. TEST(RedirectToDifferentPort, Redirect) {
  2016. Server svr1;
  2017. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. int svr1_port = 0;
  2021. auto thread1 = std::thread([&]() {
  2022. svr1_port = svr1.bind_to_any_port(HOST);
  2023. svr1.listen_after_bind();
  2024. });
  2025. Server svr2;
  2026. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2027. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2028. });
  2029. int svr2_port = 0;
  2030. auto thread2 = std::thread([&]() {
  2031. svr2_port = svr2.bind_to_any_port(HOST);
  2032. svr2.listen_after_bind();
  2033. });
  2034. auto se = detail::scope_exit([&] {
  2035. svr2.stop();
  2036. thread2.join();
  2037. svr1.stop();
  2038. thread1.join();
  2039. ASSERT_FALSE(svr2.is_running());
  2040. ASSERT_FALSE(svr1.is_running());
  2041. });
  2042. svr1.wait_until_ready();
  2043. svr2.wait_until_ready();
  2044. Client cli("localhost", svr2_port);
  2045. cli.set_follow_location(true);
  2046. auto res = cli.Get("/2");
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::OK_200, res->status);
  2049. EXPECT_EQ("Hello World!", res->body);
  2050. }
  2051. static void
  2052. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2053. Server svr1;
  2054. std::string captured_authorization;
  2055. svr1.Get("/target", [&](const Request &req, Response &res) {
  2056. captured_authorization = req.get_header_value("Authorization");
  2057. res.set_content("OK", "text/plain");
  2058. });
  2059. int svr1_port = 0;
  2060. auto thread1 = std::thread([&]() {
  2061. svr1_port = svr1.bind_to_any_port(HOST);
  2062. svr1.listen_after_bind();
  2063. });
  2064. Server svr2;
  2065. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2066. res.set_redirect(
  2067. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2068. });
  2069. int svr2_port = 0;
  2070. auto thread2 = std::thread([&]() {
  2071. svr2_port = svr2.bind_to_any_port(HOST);
  2072. svr2.listen_after_bind();
  2073. });
  2074. auto se = detail::scope_exit([&] {
  2075. svr2.stop();
  2076. thread2.join();
  2077. svr1.stop();
  2078. thread1.join();
  2079. ASSERT_FALSE(svr2.is_running());
  2080. ASSERT_FALSE(svr1.is_running());
  2081. });
  2082. svr1.wait_until_ready();
  2083. svr2.wait_until_ready();
  2084. Client cli("localhost", svr2_port);
  2085. cli.set_follow_location(true);
  2086. set_auth(cli);
  2087. auto res = cli.Get("/redir");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2091. EXPECT_TRUE(captured_authorization.empty());
  2092. }
  2093. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2094. TestDoNotForwardCredentialsOnRedirect(
  2095. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2096. }
  2097. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2098. TestDoNotForwardCredentialsOnRedirect(
  2099. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2100. }
  2101. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2102. Server svr;
  2103. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2104. // Port number that overflows int — should not crash
  2105. res.set_redirect("http://localhost:99999999999999999999/target");
  2106. });
  2107. auto port = svr.bind_to_any_port(HOST);
  2108. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2109. auto se = detail::scope_exit([&] {
  2110. svr.stop();
  2111. thread.join();
  2112. ASSERT_FALSE(svr.is_running());
  2113. });
  2114. svr.wait_until_ready();
  2115. Client cli(HOST, port);
  2116. cli.set_follow_location(true);
  2117. auto res = cli.Get("/redir");
  2118. // Should fail gracefully, not crash (no valid response due to bad port)
  2119. EXPECT_FALSE(res);
  2120. }
  2121. TEST(RedirectFromPageWithContent, Redirect) {
  2122. Server svr;
  2123. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2124. res.set_content("___", "text/plain");
  2125. res.set_redirect("/2");
  2126. });
  2127. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2128. res.set_content("Hello World!", "text/plain");
  2129. });
  2130. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2131. auto se = detail::scope_exit([&] {
  2132. svr.stop();
  2133. th.join();
  2134. ASSERT_FALSE(svr.is_running());
  2135. });
  2136. svr.wait_until_ready();
  2137. {
  2138. Client cli("localhost", PORT);
  2139. cli.set_follow_location(true);
  2140. std::string body;
  2141. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2142. body.append(data, data_length);
  2143. return true;
  2144. });
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. EXPECT_EQ("Hello World!", body);
  2148. }
  2149. {
  2150. Client cli("localhost", PORT);
  2151. std::string body;
  2152. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2153. body.append(data, data_length);
  2154. return true;
  2155. });
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(StatusCode::Found_302, res->status);
  2158. EXPECT_EQ("___", body);
  2159. }
  2160. }
  2161. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2162. Server svr;
  2163. auto port_str = std::to_string(PORT);
  2164. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2165. auto expected_host = "[::1]:" + port_str;
  2166. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2167. res.set_content("___", "text/plain");
  2168. // res.set_redirect("/2");
  2169. res.set_redirect(redirect_url);
  2170. });
  2171. svr.Get("/2", [&](const Request &req, Response &res) {
  2172. auto host_header = req.headers.find("Host");
  2173. ASSERT_TRUE(host_header != req.headers.end());
  2174. EXPECT_EQ(expected_host, host_header->second);
  2175. res.set_content("Hello World!", "text/plain");
  2176. });
  2177. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. th.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2184. // actually starts anything, so the condition !svr.is_running() will
  2185. // always remain true, and the loop never stops.
  2186. // This basically counts how many milliseconds have passed since the
  2187. // call to svr.listen(), and if after 5 seconds nothing started yet
  2188. // aborts the test.
  2189. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2191. ASSERT_LT(milliseconds, 5000U);
  2192. }
  2193. {
  2194. Client cli("::1", PORT);
  2195. cli.set_follow_location(true);
  2196. std::string body;
  2197. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2198. body.append(data, data_length);
  2199. return true;
  2200. });
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::OK_200, res->status);
  2203. EXPECT_EQ("Hello World!", body);
  2204. }
  2205. {
  2206. Client cli("::1", PORT);
  2207. std::string body;
  2208. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2209. body.append(data, data_length);
  2210. return true;
  2211. });
  2212. ASSERT_TRUE(res);
  2213. EXPECT_EQ(StatusCode::Found_302, res->status);
  2214. EXPECT_EQ("___", body);
  2215. }
  2216. }
  2217. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2218. Server svr;
  2219. svr.Get("/foo", [](const Request &req, Response &res) {
  2220. auto a = req.params.find("a");
  2221. if (a != req.params.end()) {
  2222. res.set_content((*a).second, "text/plain");
  2223. res.status = StatusCode::OK_200;
  2224. } else {
  2225. res.status = StatusCode::BadRequest_400;
  2226. }
  2227. });
  2228. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. thread.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. {
  2236. Client cli(HOST, PORT);
  2237. cli.set_path_encode(false);
  2238. auto res = cli.Get("/foo?a=explicitly+encoded");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. // This expects it back with a space, as the `+` won't have been
  2242. // url-encoded, and server-side the params get decoded turning `+`
  2243. // into spaces.
  2244. EXPECT_EQ("explicitly encoded", res->body);
  2245. }
  2246. }
  2247. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2248. Server svr;
  2249. svr.Get("/", [](const Request &req, Response &) {
  2250. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. {
  2260. Client cli(HOST, PORT);
  2261. cli.set_path_encode(false);
  2262. auto res = cli.Get("/?something=%0A");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::OK_200, res->status);
  2265. }
  2266. }
  2267. TEST(BindServerTest, BindDualStack) {
  2268. Server svr;
  2269. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2270. res.set_content("Hello World!", "text/plain");
  2271. });
  2272. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2273. auto se = detail::scope_exit([&] {
  2274. svr.stop();
  2275. thread.join();
  2276. ASSERT_FALSE(svr.is_running());
  2277. });
  2278. svr.wait_until_ready();
  2279. {
  2280. Client cli("127.0.0.1", PORT);
  2281. auto res = cli.Get("/1");
  2282. ASSERT_TRUE(res);
  2283. EXPECT_EQ(StatusCode::OK_200, res->status);
  2284. EXPECT_EQ("Hello World!", res->body);
  2285. }
  2286. {
  2287. Client cli("::1", PORT);
  2288. auto res = cli.Get("/1");
  2289. ASSERT_TRUE(res);
  2290. EXPECT_EQ(StatusCode::OK_200, res->status);
  2291. EXPECT_EQ("Hello World!", res->body);
  2292. }
  2293. }
  2294. TEST(BindServerTest, BindAndListenSeparately) {
  2295. Server svr;
  2296. int port = svr.bind_to_any_port("0.0.0.0");
  2297. ASSERT_TRUE(svr.is_valid());
  2298. ASSERT_TRUE(port > 0);
  2299. svr.stop();
  2300. }
  2301. #ifdef CPPHTTPLIB_SSL_ENABLED
  2302. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2304. CLIENT_CA_CERT_DIR);
  2305. int port = svr.bind_to_any_port("0.0.0.0");
  2306. ASSERT_TRUE(svr.is_valid());
  2307. ASSERT_TRUE(port > 0);
  2308. svr.stop();
  2309. }
  2310. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2311. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2312. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2313. int port = svr.bind_to_any_port("0.0.0.0");
  2314. ASSERT_TRUE(svr.is_valid());
  2315. ASSERT_TRUE(port > 0);
  2316. svr.stop();
  2317. }
  2318. TEST(BindServerTest, UpdateCertsPem) {
  2319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2320. int port = svr.bind_to_any_port("0.0.0.0");
  2321. ASSERT_TRUE(svr.is_valid());
  2322. ASSERT_TRUE(port > 0);
  2323. // Read PEM files
  2324. std::string cert_pem, key_pem, ca_pem;
  2325. read_file(SERVER_CERT_FILE, cert_pem);
  2326. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2327. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2328. // Update server certificates using PEM API
  2329. ASSERT_TRUE(
  2330. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2331. ASSERT_TRUE(svr.is_valid());
  2332. svr.stop();
  2333. }
  2334. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2335. // Start server with client CA (enables client auth)
  2336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2337. ASSERT_TRUE(svr.is_valid());
  2338. bool handler_called = false;
  2339. svr.Get("/test", [&](const Request &req, Response &res) {
  2340. handler_called = true;
  2341. // Verify client certificate is present
  2342. auto cert = req.peer_cert();
  2343. EXPECT_TRUE(static_cast<bool>(cert));
  2344. res.set_content("ok", "text/plain");
  2345. });
  2346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. t.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. // Read PEM files
  2354. std::string cert_pem, key_pem, ca_pem;
  2355. read_file(SERVER_CERT_FILE, cert_pem);
  2356. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2357. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2358. // Update server certificates and client CA using PEM API while server running
  2359. ASSERT_TRUE(
  2360. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2361. // Connect with client certificate
  2362. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2363. cli.enable_server_certificate_verification(false);
  2364. cli.set_connection_timeout(30);
  2365. auto res = cli.Get("/test");
  2366. ASSERT_TRUE(res);
  2367. ASSERT_EQ(StatusCode::OK_200, res->status);
  2368. ASSERT_TRUE(handler_called);
  2369. EXPECT_EQ("ok", res->body);
  2370. }
  2371. #endif
  2372. TEST(ErrorHandlerTest, ContentLength) {
  2373. Server svr;
  2374. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2375. res.status = StatusCode::OK_200;
  2376. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2377. "text/html"); // <= Content-Length still 13
  2378. });
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.set_content("Hello World!\n", "text/plain");
  2381. res.status = 524;
  2382. });
  2383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2384. auto se = detail::scope_exit([&] {
  2385. svr.stop();
  2386. thread.join();
  2387. ASSERT_FALSE(svr.is_running());
  2388. });
  2389. svr.wait_until_ready();
  2390. {
  2391. Client cli(HOST, PORT);
  2392. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2393. ASSERT_TRUE(res);
  2394. EXPECT_EQ(StatusCode::OK_200, res->status);
  2395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2398. }
  2399. }
  2400. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2401. TEST(ExceptionTest, WithoutExceptionHandler) {
  2402. Server svr;
  2403. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2404. throw std::runtime_error("exception...");
  2405. });
  2406. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2407. throw std::runtime_error("exception\r\n...");
  2408. });
  2409. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2410. auto se = detail::scope_exit([&] {
  2411. svr.stop();
  2412. listen_thread.join();
  2413. ASSERT_FALSE(svr.is_running());
  2414. });
  2415. svr.wait_until_ready();
  2416. Client cli("localhost", PORT);
  2417. {
  2418. auto res = cli.Get("/exception");
  2419. ASSERT_TRUE(res);
  2420. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2421. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2422. }
  2423. {
  2424. auto res = cli.Get("/unknown");
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2427. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2428. }
  2429. }
  2430. TEST(ExceptionTest, WithExceptionHandler) {
  2431. Server svr;
  2432. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2433. std::exception_ptr ep) {
  2434. EXPECT_FALSE(ep == nullptr);
  2435. try {
  2436. std::rethrow_exception(ep);
  2437. } catch (std::exception &e) {
  2438. EXPECT_EQ("abc", std::string(e.what()));
  2439. } catch (...) {}
  2440. res.status = StatusCode::InternalServerError_500;
  2441. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2442. "text/html"); // <= Content-Length still 13 at this point
  2443. });
  2444. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2445. res.set_content("Hello World!\n", "text/plain");
  2446. throw std::runtime_error("abc");
  2447. });
  2448. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2449. auto se = detail::scope_exit([&] {
  2450. svr.stop();
  2451. thread.join();
  2452. ASSERT_FALSE(svr.is_running());
  2453. });
  2454. svr.wait_until_ready();
  2455. for (size_t i = 0; i < 10; i++) {
  2456. Client cli(HOST, PORT);
  2457. for (size_t j = 0; j < 100; j++) {
  2458. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2461. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2462. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2463. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2464. }
  2465. cli.set_keep_alive(true);
  2466. for (size_t j = 0; j < 100; j++) {
  2467. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2470. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2471. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2473. }
  2474. }
  2475. }
  2476. TEST(ExceptionTest, AndErrorHandler) {
  2477. Server svr;
  2478. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2479. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2480. });
  2481. svr.set_exception_handler(
  2482. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2483. EXPECT_FALSE(ep == nullptr);
  2484. try {
  2485. std::rethrow_exception(ep);
  2486. } catch (std::exception &e) {
  2487. res.set_content(e.what(), "text/html");
  2488. } catch (...) {}
  2489. res.status = StatusCode::InternalServerError_500;
  2490. });
  2491. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2492. throw std::runtime_error("EXCEPTION");
  2493. });
  2494. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2495. res.set_content("ERROR", "text/html");
  2496. res.status = StatusCode::InternalServerError_500;
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, PORT);
  2506. {
  2507. auto res = cli.Get("/exception");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2510. EXPECT_EQ("EXCEPTION", res->body);
  2511. }
  2512. {
  2513. auto res = cli.Get("/error");
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2516. EXPECT_EQ("ERROR", res->body);
  2517. }
  2518. {
  2519. auto res = cli.Get("/invalid");
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2522. EXPECT_EQ("NOT_FOUND", res->body);
  2523. }
  2524. }
  2525. #endif
  2526. TEST(NoContentTest, ContentLength) {
  2527. Server svr;
  2528. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2529. res.status = StatusCode::NoContent_204;
  2530. });
  2531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. thread.join();
  2535. ASSERT_FALSE(svr.is_running());
  2536. });
  2537. svr.wait_until_ready();
  2538. {
  2539. Client cli(HOST, PORT);
  2540. auto res = cli.Get("/hi");
  2541. ASSERT_TRUE(res);
  2542. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2543. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2544. }
  2545. }
  2546. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2549. ASSERT_TRUE(svr.is_valid());
  2550. #else
  2551. Server svr;
  2552. #endif
  2553. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2554. if (req.path == "/routing_handler") {
  2555. res.set_header("PRE_ROUTING", "on");
  2556. res.set_content("Routing Handler", "text/plain");
  2557. return httplib::Server::HandlerResponse::Handled;
  2558. }
  2559. return httplib::Server::HandlerResponse::Unhandled;
  2560. });
  2561. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2562. res.set_content("Error", "text/html");
  2563. });
  2564. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2565. if (req.path == "/routing_handler") {
  2566. res.set_header("POST_ROUTING", "on");
  2567. }
  2568. });
  2569. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2570. res.set_content("Hello World!\n", "text/plain");
  2571. });
  2572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. svr.wait_until_ready();
  2579. {
  2580. #ifdef CPPHTTPLIB_SSL_ENABLED
  2581. SSLClient cli(HOST, PORT);
  2582. cli.enable_server_certificate_verification(false);
  2583. #else
  2584. Client cli(HOST, PORT);
  2585. #endif
  2586. auto res = cli.Get("/routing_handler");
  2587. ASSERT_TRUE(res);
  2588. EXPECT_EQ(StatusCode::OK_200, res->status);
  2589. EXPECT_EQ("Routing Handler", res->body);
  2590. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2591. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2592. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2593. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2594. }
  2595. {
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. SSLClient cli(HOST, PORT);
  2598. cli.enable_server_certificate_verification(false);
  2599. #else
  2600. Client cli(HOST, PORT);
  2601. #endif
  2602. auto res = cli.Get("/hi");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(StatusCode::OK_200, res->status);
  2605. EXPECT_EQ("Hello World!\n", res->body);
  2606. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2607. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2608. }
  2609. {
  2610. #ifdef CPPHTTPLIB_SSL_ENABLED
  2611. SSLClient cli(HOST, PORT);
  2612. cli.enable_server_certificate_verification(false);
  2613. #else
  2614. Client cli(HOST, PORT);
  2615. #endif
  2616. auto res = cli.Get("/aaa");
  2617. ASSERT_TRUE(res);
  2618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2619. EXPECT_EQ("Error", res->body);
  2620. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2621. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2622. }
  2623. }
  2624. TEST(RequestHandlerTest, PreRequestHandler) {
  2625. auto route_path = "/user/:user";
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request &, Response &res) {
  2628. res.set_content("hi", "text/plain");
  2629. });
  2630. svr.Get(route_path, [](const Request &req, Response &res) {
  2631. res.set_content(req.path_params.at("user"), "text/plain");
  2632. });
  2633. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2634. if (req.matched_route == route_path) {
  2635. auto user = req.path_params.at("user");
  2636. if (user != "john") {
  2637. res.status = StatusCode::Forbidden_403;
  2638. res.set_content("error", "text/html");
  2639. return Server::HandlerResponse::Handled;
  2640. }
  2641. }
  2642. return Server::HandlerResponse::Unhandled;
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. {
  2653. auto res = cli.Get("/hi");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("hi", res->body);
  2657. }
  2658. {
  2659. auto res = cli.Get("/user/john");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. EXPECT_EQ("john", res->body);
  2663. }
  2664. {
  2665. auto res = cli.Get("/user/invalid-user");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2668. EXPECT_EQ("error", res->body);
  2669. }
  2670. }
  2671. TEST(UserDataTest, BasicOperations) {
  2672. httplib::UserData ud;
  2673. // Initially empty
  2674. EXPECT_FALSE(ud.has("key"));
  2675. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2676. // set and get
  2677. ud.set("key", 42);
  2678. EXPECT_TRUE(ud.has("key"));
  2679. auto *p = ud.get<int>("key");
  2680. ASSERT_NE(nullptr, p);
  2681. EXPECT_EQ(42, *p);
  2682. // Type mismatch → nullptr
  2683. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2684. // Overwrite with different type
  2685. ud.set("key", std::string("hello"));
  2686. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2687. auto *s = ud.get<std::string>("key");
  2688. ASSERT_NE(nullptr, s);
  2689. EXPECT_EQ("hello", *s);
  2690. // erase
  2691. ud.erase("key");
  2692. EXPECT_FALSE(ud.has("key"));
  2693. // clear
  2694. ud.set("a", 1);
  2695. ud.set("b", 2);
  2696. ud.clear();
  2697. EXPECT_FALSE(ud.has("a"));
  2698. EXPECT_FALSE(ud.has("b"));
  2699. }
  2700. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2701. struct AuthCtx {
  2702. std::string user_id;
  2703. };
  2704. Server svr;
  2705. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2706. res.user_data.set("auth", AuthCtx{"alice"});
  2707. return Server::HandlerResponse::Unhandled;
  2708. });
  2709. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2710. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2711. ASSERT_NE(nullptr, ctx);
  2712. res.set_content("Hello " + ctx->user_id, "text/plain");
  2713. });
  2714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2715. auto se = detail::scope_exit([&] {
  2716. svr.stop();
  2717. thread.join();
  2718. ASSERT_FALSE(svr.is_running());
  2719. });
  2720. svr.wait_until_ready();
  2721. Client cli(HOST, PORT);
  2722. auto res = cli.Get("/me");
  2723. ASSERT_TRUE(res);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. EXPECT_EQ("Hello alice", res->body);
  2726. }
  2727. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2728. struct RoleCtx {
  2729. std::string role;
  2730. };
  2731. Server svr;
  2732. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2733. res.user_data.set("role", RoleCtx{"admin"});
  2734. return Server::HandlerResponse::Unhandled;
  2735. });
  2736. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2737. auto *ctx = res.user_data.get<RoleCtx>("role");
  2738. ASSERT_NE(nullptr, ctx);
  2739. res.set_content(ctx->role, "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. auto res = cli.Get("/role");
  2750. ASSERT_TRUE(res);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. EXPECT_EQ("admin", res->body);
  2753. }
  2754. TEST(InvalidFormatTest, StatusCode) {
  2755. Server svr;
  2756. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2757. res.set_content("Hello World!\n", "text/plain");
  2758. res.status = 9999; // Status should be a three-digit code...
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. {
  2768. Client cli(HOST, PORT);
  2769. auto res = cli.Get("/hi");
  2770. ASSERT_FALSE(res);
  2771. }
  2772. }
  2773. TEST(URLFragmentTest, WithFragment) {
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2776. EXPECT_TRUE(req.target == "/hi");
  2777. });
  2778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2779. auto se = detail::scope_exit([&] {
  2780. svr.stop();
  2781. thread.join();
  2782. ASSERT_FALSE(svr.is_running());
  2783. });
  2784. svr.wait_until_ready();
  2785. {
  2786. Client cli(HOST, PORT);
  2787. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2788. EXPECT_TRUE(res);
  2789. EXPECT_EQ(StatusCode::OK_200, res->status);
  2790. res = cli.Get("/hi%23key1=val1=key2=val2");
  2791. EXPECT_TRUE(res);
  2792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2793. }
  2794. }
  2795. TEST(HeaderWriter, SetHeaderWriter) {
  2796. Server svr;
  2797. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2798. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2799. return detail::write_headers(strm, hdrs);
  2800. });
  2801. svr.Get("/hi", [](const Request &req, Response &res) {
  2802. auto it = req.headers.find("CustomClientHeader");
  2803. EXPECT_TRUE(it != req.headers.end());
  2804. EXPECT_EQ(it->second, "CustomClientValue");
  2805. res.set_content("Hello World!\n", "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. {
  2815. Client cli(HOST, PORT);
  2816. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2817. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2818. return detail::write_headers(strm, hdrs);
  2819. });
  2820. auto res = cli.Get("/hi");
  2821. EXPECT_TRUE(res);
  2822. EXPECT_EQ(StatusCode::OK_200, res->status);
  2823. auto it = res->headers.find("CustomServerHeader");
  2824. EXPECT_TRUE(it != res->headers.end());
  2825. EXPECT_EQ(it->second, "CustomServerValue");
  2826. }
  2827. }
  2828. class ServerTest : public ::testing::Test {
  2829. protected:
  2830. ServerTest()
  2831. : cli_(HOST, PORT)
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. ,
  2834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2835. #endif
  2836. {
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. cli_.enable_server_certificate_verification(false);
  2839. #endif
  2840. // Allow LARGE_DATA (100MB) responses
  2841. cli_.set_payload_max_length(200 * 1024 * 1024);
  2842. }
  2843. virtual void SetUp() {
  2844. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2845. svr_.set_payload_max_length(200 * 1024 * 1024);
  2846. svr_.set_mount_point("/", "./www");
  2847. svr_.set_mount_point("/mount", "./www2");
  2848. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2849. svr_.Get("/hi",
  2850. [&](const Request & /*req*/, Response &res) {
  2851. res.set_content("Hello World!", "text/plain");
  2852. })
  2853. .Get("/file_content",
  2854. [&](const Request & /*req*/, Response &res) {
  2855. res.set_file_content("./www/dir/test.html");
  2856. })
  2857. .Get("/file_content_with_content_type",
  2858. [&](const Request & /*req*/, Response &res) {
  2859. res.set_file_content("./www/file", "text/plain");
  2860. })
  2861. .Get("/invalid_file_content",
  2862. [&](const Request & /*req*/, Response &res) {
  2863. res.set_file_content("./www/dir/invalid_file_path");
  2864. })
  2865. .Get("/http_response_splitting",
  2866. [&](const Request & /*req*/, Response &res) {
  2867. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2868. EXPECT_EQ(0U, res.headers.size());
  2869. EXPECT_FALSE(res.has_header("a"));
  2870. res.set_header("a", "1\nSet-Cookie: a=1");
  2871. EXPECT_EQ(0U, res.headers.size());
  2872. EXPECT_FALSE(res.has_header("a"));
  2873. res.set_header("a", "1\rSet-Cookie: a=1");
  2874. EXPECT_EQ(0U, res.headers.size());
  2875. EXPECT_FALSE(res.has_header("a"));
  2876. res.set_header("a\r\nb", "0");
  2877. EXPECT_EQ(0U, res.headers.size());
  2878. EXPECT_FALSE(res.has_header("a"));
  2879. res.set_header("a\rb", "0");
  2880. EXPECT_EQ(0U, res.headers.size());
  2881. EXPECT_FALSE(res.has_header("a"));
  2882. res.set_header("a\nb", "0");
  2883. EXPECT_EQ(0U, res.headers.size());
  2884. EXPECT_FALSE(res.has_header("a"));
  2885. res.set_redirect("1\r\nSet-Cookie: a=1");
  2886. EXPECT_EQ(0U, res.headers.size());
  2887. EXPECT_FALSE(res.has_header("Location"));
  2888. })
  2889. .Get("/slow",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. std::this_thread::sleep_for(std::chrono::seconds(4));
  2892. res.set_content("slow", "text/plain");
  2893. })
  2894. #if 0
  2895. .Post("/slowpost",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. std::this_thread::sleep_for(std::chrono::seconds(2));
  2898. res.set_content("slow", "text/plain");
  2899. })
  2900. #endif
  2901. .Get("/remote_addr",
  2902. [&](const Request &req, Response &res) {
  2903. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2904. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2905. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2906. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2907. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2908. #endif
  2909. res.set_content(req.remote_addr, "text/plain");
  2910. })
  2911. .Get("/local_addr",
  2912. [&](const Request &req, Response &res) {
  2913. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2914. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2915. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2916. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2917. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2918. #endif
  2919. auto local_addr = req.local_addr;
  2920. auto local_port = std::to_string(req.local_port);
  2921. res.set_content(local_addr.append(":").append(local_port),
  2922. "text/plain");
  2923. })
  2924. .Get("/endwith%",
  2925. [&](const Request & /*req*/, Response &res) {
  2926. res.set_content("Hello World!", "text/plain");
  2927. })
  2928. .Get("/a\\+\\+b",
  2929. [&](const Request &req, Response &res) {
  2930. ASSERT_TRUE(req.has_param("a +b"));
  2931. auto val = req.get_param_value("a +b");
  2932. res.set_content(val, "text/plain");
  2933. })
  2934. .Get("/", [&](const Request & /*req*/,
  2935. Response &res) { res.set_redirect("/hi"); })
  2936. .Post("/1",
  2937. [](const Request & /*req*/, Response &res) {
  2938. res.set_redirect("/2", StatusCode::SeeOther_303);
  2939. })
  2940. .Get("/2",
  2941. [](const Request & /*req*/, Response &res) {
  2942. res.set_content("redirected.", "text/plain");
  2943. res.status = StatusCode::OK_200;
  2944. })
  2945. .Post("/person",
  2946. [&](const Request &req, Response &res) {
  2947. if (req.has_param("name") && req.has_param("note")) {
  2948. persons_[req.get_param_value("name")] =
  2949. req.get_param_value("note");
  2950. } else {
  2951. res.status = StatusCode::BadRequest_400;
  2952. }
  2953. })
  2954. .Put("/person",
  2955. [&](const Request &req, Response &res) {
  2956. if (req.has_param("name") && req.has_param("note")) {
  2957. persons_[req.get_param_value("name")] =
  2958. req.get_param_value("note");
  2959. } else {
  2960. res.status = StatusCode::BadRequest_400;
  2961. }
  2962. })
  2963. .Get("/person/(.*)",
  2964. [&](const Request &req, Response &res) {
  2965. string name = req.matches[1];
  2966. if (persons_.find(name) != persons_.end()) {
  2967. auto note = persons_[name];
  2968. res.set_content(note, "text/plain");
  2969. } else {
  2970. res.status = StatusCode::NotFound_404;
  2971. }
  2972. })
  2973. .Delete("/person",
  2974. [&](const Request &req, Response &res) {
  2975. if (req.has_param("name")) {
  2976. string name = req.get_param_value("name");
  2977. if (persons_.find(name) != persons_.end()) {
  2978. persons_.erase(name);
  2979. res.set_content("DELETED", "text/plain");
  2980. } else {
  2981. res.status = StatusCode::NotFound_404;
  2982. }
  2983. } else {
  2984. res.status = StatusCode::BadRequest_400;
  2985. }
  2986. })
  2987. .Post("/x-www-form-urlencoded-json",
  2988. [&](const Request &req, Response &res) {
  2989. auto json = req.get_param_value("json");
  2990. ASSERT_EQ(JSON_DATA, json);
  2991. res.set_content(json, "appliation/json");
  2992. res.status = StatusCode::OK_200;
  2993. })
  2994. .Get("/streamed-chunked",
  2995. [&](const Request & /*req*/, Response &res) {
  2996. res.set_chunked_content_provider(
  2997. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2998. sink.os << "123";
  2999. sink.os << "456";
  3000. sink.os << "789";
  3001. sink.done();
  3002. return true;
  3003. });
  3004. })
  3005. .Get("/streamed-chunked-with-prohibited-trailer",
  3006. [&](const Request & /*req*/, Response &res) {
  3007. auto i = new int(0);
  3008. // Declare both a prohibited trailer (Content-Length) and an
  3009. // allowed one
  3010. res.set_header("Trailer", "Content-Length, X-Allowed");
  3011. res.set_chunked_content_provider(
  3012. "text/plain",
  3013. [i](size_t /*offset*/, DataSink &sink) {
  3014. switch (*i) {
  3015. case 0: sink.os << "123"; break;
  3016. case 1: sink.os << "456"; break;
  3017. case 2: sink.os << "789"; break;
  3018. case 3: {
  3019. sink.done_with_trailer(
  3020. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3021. } break;
  3022. }
  3023. (*i)++;
  3024. return true;
  3025. },
  3026. [i](bool success) {
  3027. EXPECT_TRUE(success);
  3028. delete i;
  3029. });
  3030. })
  3031. .Get("/streamed-chunked2",
  3032. [&](const Request & /*req*/, Response &res) {
  3033. auto i = new int(0);
  3034. res.set_chunked_content_provider(
  3035. "text/plain",
  3036. [i](size_t /*offset*/, DataSink &sink) {
  3037. switch (*i) {
  3038. case 0: sink.os << "123"; break;
  3039. case 1: sink.os << "456"; break;
  3040. case 2: sink.os << "789"; break;
  3041. case 3: sink.done(); break;
  3042. }
  3043. (*i)++;
  3044. return true;
  3045. },
  3046. [i](bool success) {
  3047. EXPECT_TRUE(success);
  3048. delete i;
  3049. });
  3050. })
  3051. .Get("/streamed-chunked-with-trailer",
  3052. [&](const Request & /*req*/, Response &res) {
  3053. auto i = new int(0);
  3054. res.set_header("Trailer", "Dummy1, Dummy2");
  3055. res.set_chunked_content_provider(
  3056. "text/plain",
  3057. [i](size_t /*offset*/, DataSink &sink) {
  3058. switch (*i) {
  3059. case 0: sink.os << "123"; break;
  3060. case 1: sink.os << "456"; break;
  3061. case 2: sink.os << "789"; break;
  3062. case 3: {
  3063. sink.done_with_trailer(
  3064. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3065. } break;
  3066. }
  3067. (*i)++;
  3068. return true;
  3069. },
  3070. [i](bool success) {
  3071. EXPECT_TRUE(success);
  3072. delete i;
  3073. });
  3074. })
  3075. .Get("/streamed",
  3076. [&](const Request & /*req*/, Response &res) {
  3077. res.set_content_provider(
  3078. 6, "text/plain",
  3079. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3080. sink.os << (offset < 3 ? "a" : "b");
  3081. return true;
  3082. });
  3083. })
  3084. .Get("/streamed-with-range",
  3085. [&](const Request &req, Response &res) {
  3086. auto data = new std::string("abcdefg");
  3087. res.set_content_provider(
  3088. data->size(), "text/plain",
  3089. [data](size_t offset, size_t length, DataSink &sink) {
  3090. size_t DATA_CHUNK_SIZE = 4;
  3091. const auto &d = *data;
  3092. auto out_len =
  3093. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3094. auto ret =
  3095. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3096. EXPECT_TRUE(ret);
  3097. return true;
  3098. },
  3099. [data, &req](bool success) {
  3100. EXPECT_EQ(success, !req.has_param("error"));
  3101. delete data;
  3102. });
  3103. })
  3104. .Get("/streamed-cancel",
  3105. [&](const Request & /*req*/, Response &res) {
  3106. res.set_content_provider(
  3107. size_t(-1), "text/plain",
  3108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3109. sink.os << "data_chunk";
  3110. return true;
  3111. });
  3112. })
  3113. .Get("/regex-with-delimiter",
  3114. [&](const Request &req, Response & /*res*/) {
  3115. ASSERT_TRUE(req.has_param("key"));
  3116. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3117. })
  3118. .Get("/with-range",
  3119. [&](const Request & /*req*/, Response &res) {
  3120. res.set_content("abcdefg", "text/plain");
  3121. })
  3122. .Get("/test-start-time",
  3123. [&](const Request &req, Response & /*res*/) {
  3124. EXPECT_NE(req.start_time_,
  3125. std::chrono::steady_clock::time_point::min());
  3126. })
  3127. .Get("/with-range-customized-response",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.status = StatusCode::BadRequest_400;
  3130. res.set_content(JSON_DATA, "application/json");
  3131. })
  3132. .Post("/chunked",
  3133. [&](const Request &req, Response & /*res*/) {
  3134. EXPECT_EQ(req.body, "dechunked post body");
  3135. })
  3136. .Post("/large-chunked",
  3137. [&](const Request &req, Response & /*res*/) {
  3138. std::string expected(6 * 30 * 1024u, 'a');
  3139. EXPECT_EQ(req.body, expected);
  3140. })
  3141. .Post("/multipart",
  3142. [&](const Request &req, Response & /*res*/) {
  3143. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3144. req.form.get_field_count("text2") +
  3145. req.form.get_field_count("file3") +
  3146. req.form.get_field_count("file4"));
  3147. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3148. req.form.get_file_count("file2"));
  3149. ASSERT_TRUE(!req.form.has_file("???"));
  3150. ASSERT_TRUE(!req.form.has_field("???"));
  3151. ASSERT_TRUE(req.body.empty());
  3152. {
  3153. const auto &text = req.form.get_field("text1");
  3154. EXPECT_EQ("text default", text);
  3155. }
  3156. {
  3157. const auto &text = req.form.get_field("text2");
  3158. EXPECT_EQ("aωb", text);
  3159. }
  3160. {
  3161. const auto &file = req.form.get_file("file1");
  3162. EXPECT_EQ("hello.txt", file.filename);
  3163. EXPECT_EQ("text/plain", file.content_type);
  3164. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3165. }
  3166. {
  3167. const auto &file = req.form.get_file("file2");
  3168. EXPECT_EQ("world.json", file.filename);
  3169. EXPECT_EQ("application/json", file.content_type);
  3170. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3171. }
  3172. {
  3173. const auto &text = req.form.get_field("file3");
  3174. EXPECT_EQ(0u, text.size());
  3175. }
  3176. {
  3177. const auto &text = req.form.get_field("file4");
  3178. EXPECT_EQ(0u, text.size());
  3179. }
  3180. })
  3181. .Post("/multipart/multi_file_values",
  3182. [&](const Request &req, Response & /*res*/) {
  3183. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3184. req.form.get_field_count("multi_text1"));
  3185. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3186. ASSERT_TRUE(!req.form.has_file("???"));
  3187. ASSERT_TRUE(!req.form.has_field("???"));
  3188. ASSERT_TRUE(req.body.empty());
  3189. {
  3190. const auto &text = req.form.get_field("text");
  3191. EXPECT_EQ("default text", text);
  3192. }
  3193. {
  3194. const auto &text1_values = req.form.get_fields("multi_text1");
  3195. EXPECT_EQ(2u, text1_values.size());
  3196. EXPECT_EQ("aaaaa", text1_values[0]);
  3197. EXPECT_EQ("bbbbb", text1_values[1]);
  3198. }
  3199. {
  3200. const auto &file1_values = req.form.get_files("multi_file1");
  3201. EXPECT_EQ(2u, file1_values.size());
  3202. auto file1 = file1_values[0];
  3203. EXPECT_EQ(file1.filename, "hello.txt");
  3204. EXPECT_EQ(file1.content_type, "text/plain");
  3205. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3206. auto file2 = file1_values[1];
  3207. EXPECT_EQ(file2.filename, "world.json");
  3208. EXPECT_EQ(file2.content_type, "application/json");
  3209. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3210. }
  3211. })
  3212. .Post("/empty",
  3213. [&](const Request &req, Response &res) {
  3214. EXPECT_EQ(req.body, "");
  3215. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3216. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3217. res.set_content("empty", "text/plain");
  3218. })
  3219. .Post("/empty-no-content-type",
  3220. [&](const Request &req, Response &res) {
  3221. EXPECT_EQ(req.body, "");
  3222. EXPECT_FALSE(req.has_header("Content-Type"));
  3223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3224. res.set_content("empty-no-content-type", "text/plain");
  3225. })
  3226. .Post("/path-only",
  3227. [&](const Request &req, Response &res) {
  3228. EXPECT_EQ(req.body, "");
  3229. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3230. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3231. res.set_content("path-only", "text/plain");
  3232. })
  3233. .Post("/path-headers-only",
  3234. [&](const Request &req, Response &res) {
  3235. EXPECT_EQ(req.body, "");
  3236. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3237. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3238. EXPECT_EQ("world", req.get_header_value("hello"));
  3239. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3240. res.set_content("path-headers-only", "text/plain");
  3241. })
  3242. .Post("/post-large",
  3243. [&](const Request &req, Response &res) {
  3244. EXPECT_EQ(req.body, LARGE_DATA);
  3245. res.set_content(req.body, "text/plain");
  3246. })
  3247. .Post("/post-loopback",
  3248. [&](const Request &, Response &res,
  3249. ContentReader const &content_reader) {
  3250. std::string body;
  3251. content_reader([&](const char *data, size_t data_length) {
  3252. body.append(data, data_length);
  3253. return true;
  3254. });
  3255. res.set_content(body, "text/plain");
  3256. })
  3257. .Put("/put-loopback",
  3258. [&](const Request &, Response &res,
  3259. ContentReader const &content_reader) {
  3260. std::string body;
  3261. content_reader([&](const char *data, size_t data_length) {
  3262. body.append(data, data_length);
  3263. return true;
  3264. });
  3265. res.set_content(body, "text/plain");
  3266. })
  3267. .Patch("/patch-loopback",
  3268. [&](const Request &, Response &res,
  3269. ContentReader const &content_reader) {
  3270. std::string body;
  3271. content_reader([&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. res.set_content(body, "text/plain");
  3276. })
  3277. .Put("/empty-no-content-type",
  3278. [&](const Request &req, Response &res) {
  3279. EXPECT_EQ(req.body, "");
  3280. EXPECT_FALSE(req.has_header("Content-Type"));
  3281. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3282. res.set_content("empty-no-content-type", "text/plain");
  3283. })
  3284. .Put("/put",
  3285. [&](const Request &req, Response &res) {
  3286. EXPECT_EQ(req.body, "PUT");
  3287. res.set_content(req.body, "text/plain");
  3288. })
  3289. .Put("/put-large",
  3290. [&](const Request &req, Response &res) {
  3291. EXPECT_EQ(req.body, LARGE_DATA);
  3292. res.set_content(req.body, "text/plain");
  3293. })
  3294. .Patch("/patch",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(req.body, "PATCH");
  3297. res.set_content(req.body, "text/plain");
  3298. })
  3299. .Delete("/delete",
  3300. [&](const Request & /*req*/, Response &res) {
  3301. res.set_content("DELETE", "text/plain");
  3302. })
  3303. .Delete("/delete-body",
  3304. [&](const Request &req, Response &res) {
  3305. EXPECT_EQ(req.body, "content");
  3306. res.set_content(req.body, "text/plain");
  3307. })
  3308. .Options(R"(\*)",
  3309. [&](const Request & /*req*/, Response &res) {
  3310. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3311. })
  3312. .Get("/request-target",
  3313. [&](const Request &req, Response & /*res*/) {
  3314. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3315. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3316. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3317. })
  3318. .Get("/long-query-value",
  3319. [&](const Request &req, Response & /*res*/) {
  3320. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3321. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3322. })
  3323. .Get("/too-long-query-value",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3326. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3327. })
  3328. .Get("/array-param",
  3329. [&](const Request &req, Response & /*res*/) {
  3330. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3331. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3332. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3333. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3334. })
  3335. .Get("/array-param-values",
  3336. [&](const Request &req, Response & /*res*/) {
  3337. auto values = req.get_param_values("array");
  3338. EXPECT_EQ(3u, values.size());
  3339. EXPECT_EQ("value1", values[0]);
  3340. EXPECT_EQ("value2", values[1]);
  3341. EXPECT_EQ("value3", values[2]);
  3342. auto empty = req.get_param_values("nonexistent");
  3343. EXPECT_TRUE(empty.empty());
  3344. })
  3345. .Post("/validate-no-multiple-headers",
  3346. [&](const Request &req, Response & /*res*/) {
  3347. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3348. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3349. })
  3350. .Post("/content_receiver",
  3351. [&](const Request &req, Response &res,
  3352. const ContentReader &content_reader) {
  3353. if (req.is_multipart_form_data()) {
  3354. std::vector<FormData> items;
  3355. content_reader(
  3356. [&](const FormData &file) {
  3357. items.push_back(file);
  3358. return true;
  3359. },
  3360. [&](const char *data, size_t data_length) {
  3361. items.back().content.append(data, data_length);
  3362. return true;
  3363. });
  3364. EXPECT_EQ(5u, items.size());
  3365. {
  3366. const auto &file = get_file_value(items, "text1");
  3367. EXPECT_TRUE(file.filename.empty());
  3368. EXPECT_EQ("text default", file.content);
  3369. }
  3370. {
  3371. const auto &file = get_file_value(items, "text2");
  3372. EXPECT_TRUE(file.filename.empty());
  3373. EXPECT_EQ("aωb", file.content);
  3374. }
  3375. {
  3376. const auto &file = get_file_value(items, "file1");
  3377. EXPECT_EQ("hello.txt", file.filename);
  3378. EXPECT_EQ("text/plain", file.content_type);
  3379. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3380. }
  3381. {
  3382. const auto &file = get_file_value(items, "file2");
  3383. EXPECT_EQ("world.json", file.filename);
  3384. EXPECT_EQ("application/json", file.content_type);
  3385. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3386. }
  3387. {
  3388. const auto &file = get_file_value(items, "file3");
  3389. EXPECT_TRUE(file.filename.empty());
  3390. EXPECT_EQ("application/octet-stream", file.content_type);
  3391. EXPECT_EQ(0u, file.content.size());
  3392. }
  3393. } else {
  3394. std::string body;
  3395. content_reader([&](const char *data, size_t data_length) {
  3396. EXPECT_EQ(7U, data_length);
  3397. body.append(data, data_length);
  3398. return true;
  3399. });
  3400. EXPECT_EQ(body, "content");
  3401. res.set_content(body, "text/plain");
  3402. }
  3403. })
  3404. .Put("/content_receiver",
  3405. [&](const Request & /*req*/, Response &res,
  3406. const ContentReader &content_reader) {
  3407. std::string body;
  3408. content_reader([&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. EXPECT_EQ(body, "content");
  3413. res.set_content(body, "text/plain");
  3414. })
  3415. .Patch("/content_receiver",
  3416. [&](const Request & /*req*/, Response &res,
  3417. const ContentReader &content_reader) {
  3418. std::string body;
  3419. content_reader([&](const char *data, size_t data_length) {
  3420. body.append(data, data_length);
  3421. return true;
  3422. });
  3423. EXPECT_EQ(body, "content");
  3424. res.set_content(body, "text/plain");
  3425. })
  3426. .Post("/query-string-and-body",
  3427. [&](const Request &req, Response & /*res*/) {
  3428. ASSERT_TRUE(req.has_param("key"));
  3429. EXPECT_EQ(req.get_param_value("key"), "value");
  3430. EXPECT_EQ(req.body, "content");
  3431. })
  3432. .Get("/last-request",
  3433. [&](const Request &req, Response & /*res*/) {
  3434. EXPECT_EQ("close", req.get_header_value("Connection"));
  3435. })
  3436. .Get(R"(/redirect/(\d+))",
  3437. [&](const Request &req, Response &res) {
  3438. auto num = std::stoi(req.matches[1]) + 1;
  3439. std::string url = "/redirect/" + std::to_string(num);
  3440. res.set_redirect(url);
  3441. })
  3442. .Post("/binary",
  3443. [&](const Request &req, Response &res) {
  3444. EXPECT_EQ(4U, req.body.size());
  3445. EXPECT_EQ("application/octet-stream",
  3446. req.get_header_value("Content-Type"));
  3447. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3448. res.set_content(req.body, "application/octet-stream");
  3449. })
  3450. .Put("/binary",
  3451. [&](const Request &req, Response &res) {
  3452. EXPECT_EQ(4U, req.body.size());
  3453. EXPECT_EQ("application/octet-stream",
  3454. req.get_header_value("Content-Type"));
  3455. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3456. res.set_content(req.body, "application/octet-stream");
  3457. })
  3458. .Patch("/binary",
  3459. [&](const Request &req, Response &res) {
  3460. EXPECT_EQ(4U, req.body.size());
  3461. EXPECT_EQ("application/octet-stream",
  3462. req.get_header_value("Content-Type"));
  3463. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3464. res.set_content(req.body, "application/octet-stream");
  3465. })
  3466. .Delete("/binary",
  3467. [&](const Request &req, Response &res) {
  3468. EXPECT_EQ(4U, req.body.size());
  3469. EXPECT_EQ("application/octet-stream",
  3470. req.get_header_value("Content-Type"));
  3471. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3472. res.set_content(req.body, "application/octet-stream");
  3473. })
  3474. .Get("/issue1772",
  3475. [&](const Request & /*req*/, Response &res) {
  3476. res.status = 401;
  3477. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3478. })
  3479. .Delete("/issue609",
  3480. [](const httplib::Request &, httplib::Response &res,
  3481. const httplib::ContentReader &) {
  3482. res.set_content("ok", "text/plain");
  3483. })
  3484. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3485. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3486. .Get("/compress",
  3487. [&](const Request & /*req*/, Response &res) {
  3488. res.set_content(
  3489. "12345678901234567890123456789012345678901234567890123456789"
  3490. "01234567890123456789012345678901234567890",
  3491. "text/plain");
  3492. })
  3493. .Get("/compress-with-charset",
  3494. [&](const Request & /*req*/, Response &res) {
  3495. res.set_content(
  3496. "12345678901234567890123456789012345678901234567890123456789"
  3497. "01234567890123456789012345678901234567890",
  3498. "application/json; charset=utf-8");
  3499. })
  3500. .Get("/nocompress",
  3501. [&](const Request & /*req*/, Response &res) {
  3502. res.set_content(
  3503. "12345678901234567890123456789012345678901234567890123456789"
  3504. "01234567890123456789012345678901234567890",
  3505. "application/octet-stream");
  3506. })
  3507. .Post("/compress-multipart",
  3508. [&](const Request &req, Response & /*res*/) {
  3509. EXPECT_EQ(2u, req.form.fields.size());
  3510. ASSERT_TRUE(!req.form.has_field("???"));
  3511. {
  3512. const auto &text = req.form.get_field("key1");
  3513. EXPECT_EQ("test", text);
  3514. }
  3515. {
  3516. const auto &text = req.form.get_field("key2");
  3517. EXPECT_EQ("--abcdefg123", text);
  3518. }
  3519. })
  3520. #endif
  3521. ;
  3522. persons_["john"] = "programmer";
  3523. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3524. svr_.wait_until_ready();
  3525. }
  3526. virtual void TearDown() {
  3527. svr_.stop();
  3528. if (!request_threads_.empty()) {
  3529. std::this_thread::sleep_for(std::chrono::seconds(1));
  3530. for (auto &t : request_threads_) {
  3531. t.join();
  3532. }
  3533. }
  3534. t_.join();
  3535. }
  3536. map<string, string> persons_;
  3537. #ifdef CPPHTTPLIB_SSL_ENABLED
  3538. SSLClient cli_;
  3539. SSLServer svr_;
  3540. #else
  3541. Client cli_;
  3542. Server svr_;
  3543. #endif
  3544. thread t_;
  3545. std::vector<thread> request_threads_;
  3546. };
  3547. TEST_F(ServerTest, GetMethod200) {
  3548. auto res = cli_.Get("/hi");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ("HTTP/1.1", res->version);
  3551. EXPECT_EQ(StatusCode::OK_200, res->status);
  3552. EXPECT_EQ("OK", res->reason);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3555. EXPECT_EQ("Hello World!", res->body);
  3556. }
  3557. TEST_F(ServerTest, GetEmptyFile) {
  3558. auto res = cli_.Get("/empty_file");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3563. EXPECT_EQ("", res->body);
  3564. }
  3565. TEST_F(ServerTest, GetFileContent) {
  3566. auto res = cli_.Get("/file_content");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3570. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3571. EXPECT_EQ("test.html", res->body);
  3572. }
  3573. TEST_F(ServerTest, GetFileContentWithRange) {
  3574. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3578. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3579. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3580. EXPECT_EQ("est", res->body);
  3581. }
  3582. TEST_F(ServerTest, GetFileContentWithContentType) {
  3583. auto res = cli_.Get("/file_content_with_content_type");
  3584. ASSERT_TRUE(res);
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3587. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3588. EXPECT_EQ("file\n", res->body);
  3589. }
  3590. TEST_F(ServerTest, GetInvalidFileContent) {
  3591. auto res = cli_.Get("/invalid_file_content");
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3596. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3597. ASSERT_TRUE(res);
  3598. EXPECT_EQ("HTTP/1.1", res->version);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3601. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3602. EXPECT_EQ("Hello World!", res->body);
  3603. }
  3604. TEST_F(ServerTest, GetMethod302) {
  3605. auto res = cli_.Get("/");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(StatusCode::Found_302, res->status);
  3608. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3609. }
  3610. TEST_F(ServerTest, GetMethod302Redirect) {
  3611. cli_.set_follow_location(true);
  3612. auto res = cli_.Get("/");
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. EXPECT_EQ("Hello World!", res->body);
  3616. EXPECT_EQ("/hi", res->location);
  3617. }
  3618. TEST_F(ServerTest, GetMethod404) {
  3619. auto res = cli_.Get("/invalid");
  3620. ASSERT_TRUE(res);
  3621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3622. }
  3623. TEST_F(ServerTest, HeadMethod200) {
  3624. auto res = cli_.Head("/hi");
  3625. ASSERT_TRUE(res);
  3626. EXPECT_EQ(StatusCode::OK_200, res->status);
  3627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3628. EXPECT_TRUE(res->body.empty());
  3629. }
  3630. TEST_F(ServerTest, HeadMethod200Static) {
  3631. auto res = cli_.Head("/mount/dir/index.html");
  3632. ASSERT_TRUE(res);
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3635. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3636. EXPECT_TRUE(res->body.empty());
  3637. }
  3638. TEST_F(ServerTest, HeadMethod404) {
  3639. auto res = cli_.Head("/invalid");
  3640. ASSERT_TRUE(res);
  3641. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3642. EXPECT_TRUE(res->body.empty());
  3643. }
  3644. TEST_F(ServerTest, GetMethodPersonJohn) {
  3645. auto res = cli_.Get("/person/john");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("programmer", res->body);
  3650. }
  3651. TEST_F(ServerTest, PostMethod1) {
  3652. auto res = cli_.Get("/person/john1");
  3653. ASSERT_TRUE(res);
  3654. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3655. res = cli_.Post("/person", "name=john1&note=coder",
  3656. "application/x-www-form-urlencoded");
  3657. ASSERT_TRUE(res);
  3658. ASSERT_EQ(StatusCode::OK_200, res->status);
  3659. res = cli_.Get("/person/john1");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3663. ASSERT_EQ("coder", res->body);
  3664. }
  3665. TEST_F(ServerTest, PostMethod2) {
  3666. auto res = cli_.Get("/person/john2");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3669. Params params;
  3670. params.emplace("name", "john2");
  3671. params.emplace("note", "coder");
  3672. res = cli_.Post("/person", params);
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. res = cli_.Get("/person/john2");
  3676. ASSERT_TRUE(res);
  3677. ASSERT_EQ(StatusCode::OK_200, res->status);
  3678. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3679. ASSERT_EQ("coder", res->body);
  3680. }
  3681. TEST_F(ServerTest, PutMethod3) {
  3682. auto res = cli_.Get("/person/john3");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3685. Params params;
  3686. params.emplace("name", "john3");
  3687. params.emplace("note", "coder");
  3688. res = cli_.Put("/person", params);
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. res = cli_.Get("/person/john3");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3695. ASSERT_EQ("coder", res->body);
  3696. }
  3697. TEST_F(ServerTest, DeleteMethod1) {
  3698. auto res = cli_.Get("/person/john4");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3701. Params params;
  3702. params.emplace("name", "john4");
  3703. params.emplace("note", "coder");
  3704. res = cli_.Post("/person", params);
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. res = cli_.Get("/person/john4");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3711. ASSERT_EQ("coder", res->body);
  3712. Params delete_params;
  3713. delete_params.emplace("name", "john4");
  3714. res = cli_.Delete("/person", delete_params);
  3715. ASSERT_TRUE(res);
  3716. ASSERT_EQ(StatusCode::OK_200, res->status);
  3717. ASSERT_EQ("DELETED", res->body);
  3718. res = cli_.Get("/person/john4");
  3719. ASSERT_TRUE(res);
  3720. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3721. }
  3722. TEST_F(ServerTest, DeleteMethod2) {
  3723. auto res = cli_.Get("/person/john5");
  3724. ASSERT_TRUE(res);
  3725. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3726. Params params;
  3727. params.emplace("name", "john5");
  3728. params.emplace("note", "developer");
  3729. res = cli_.Post("/person", params);
  3730. ASSERT_TRUE(res);
  3731. ASSERT_EQ(StatusCode::OK_200, res->status);
  3732. res = cli_.Get("/person/john5");
  3733. ASSERT_TRUE(res);
  3734. ASSERT_EQ(StatusCode::OK_200, res->status);
  3735. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3736. ASSERT_EQ("developer", res->body);
  3737. Params delete_params;
  3738. delete_params.emplace("name", "john5");
  3739. Headers headers;
  3740. headers.emplace("Custom-Header", "test-value");
  3741. res = cli_.Delete("/person", headers, delete_params);
  3742. ASSERT_TRUE(res);
  3743. ASSERT_EQ(StatusCode::OK_200, res->status);
  3744. ASSERT_EQ("DELETED", res->body);
  3745. res = cli_.Get("/person/john5");
  3746. ASSERT_TRUE(res);
  3747. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, DeleteMethod3) {
  3750. auto res = cli_.Get("/person/john6");
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3753. Params params;
  3754. params.emplace("name", "john6");
  3755. params.emplace("note", "tester");
  3756. res = cli_.Post("/person", params);
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::OK_200, res->status);
  3759. res = cli_.Get("/person/john6");
  3760. ASSERT_TRUE(res);
  3761. ASSERT_EQ(StatusCode::OK_200, res->status);
  3762. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3763. ASSERT_EQ("tester", res->body);
  3764. Params delete_params;
  3765. delete_params.emplace("name", "john6");
  3766. Headers headers;
  3767. headers.emplace("Custom-Header", "test-value");
  3768. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ("DELETED", res->body);
  3772. res = cli_.Get("/person/john6");
  3773. ASSERT_TRUE(res);
  3774. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3777. Params params;
  3778. params.emplace("json", JSON_DATA);
  3779. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3780. ASSERT_TRUE(res);
  3781. ASSERT_EQ(StatusCode::OK_200, res->status);
  3782. ASSERT_EQ(JSON_DATA, res->body);
  3783. }
  3784. TEST_F(ServerTest, PostEmptyContent) {
  3785. auto res = cli_.Post("/empty", "", "text/plain");
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::OK_200, res->status);
  3788. ASSERT_EQ("empty", res->body);
  3789. }
  3790. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3791. auto res = cli_.Post("/empty-no-content-type");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ("empty-no-content-type", res->body);
  3795. }
  3796. TEST_F(ServerTest, PostPathOnly) {
  3797. auto res = cli_.Post("/path-only");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::OK_200, res->status);
  3800. ASSERT_EQ("path-only", res->body);
  3801. }
  3802. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3803. auto res = cli_.Post("/path-headers-only",
  3804. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3805. ASSERT_TRUE(res);
  3806. ASSERT_EQ(StatusCode::OK_200, res->status);
  3807. ASSERT_EQ("path-headers-only", res->body);
  3808. }
  3809. TEST_F(ServerTest, PostLarge) {
  3810. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. EXPECT_EQ(LARGE_DATA, res->body);
  3814. }
  3815. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3816. auto res = cli_.Put("/empty-no-content-type");
  3817. ASSERT_TRUE(res);
  3818. ASSERT_EQ(StatusCode::OK_200, res->status);
  3819. ASSERT_EQ("empty-no-content-type", res->body);
  3820. }
  3821. TEST_F(ServerTest, GetMethodDir) {
  3822. auto res = cli_.Get("/dir/");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3826. auto body = R"(<html>
  3827. <head>
  3828. </head>
  3829. <body>
  3830. <a href="/dir/test.html">Test</a>
  3831. <a href="/hi">hi</a>
  3832. </body>
  3833. </html>
  3834. )";
  3835. EXPECT_EQ(body, res->body);
  3836. }
  3837. TEST_F(ServerTest, GetMethodDirTest) {
  3838. auto res = cli_.Get("/dir/test.html");
  3839. ASSERT_TRUE(res);
  3840. EXPECT_EQ(StatusCode::OK_200, res->status);
  3841. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3842. EXPECT_EQ("test.html", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3845. auto res = cli_.Get("/dir/../dir/test.html");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ("test.html", res->body);
  3850. }
  3851. TEST_F(ServerTest, GetMethodInvalidPath) {
  3852. auto res = cli_.Get("/dir/../test.html");
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3855. }
  3856. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3857. auto res = cli_.Get("/../www/dir/test.html");
  3858. ASSERT_TRUE(res);
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. }
  3861. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3862. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3865. }
  3866. TEST_F(ServerTest, GetMethodDirMountTest) {
  3867. auto res = cli_.Get("/mount/dir/test.html");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3871. EXPECT_EQ("test.html", res->body);
  3872. }
  3873. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3874. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::OK_200, res->status);
  3877. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3878. EXPECT_EQ("test.html", res->body);
  3879. }
  3880. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3881. auto res = cli_.Get("/mount/dir/../test.html");
  3882. ASSERT_TRUE(res);
  3883. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3884. }
  3885. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3886. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3889. }
  3890. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3891. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3894. }
  3895. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3896. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3899. }
  3900. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3901. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3904. }
  3905. TEST_F(ServerTest, PostMethod303) {
  3906. auto res = cli_.Post("/1", "body", "text/plain");
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3909. EXPECT_EQ("/2", res->get_header_value("Location"));
  3910. }
  3911. TEST_F(ServerTest, PostMethod303Redirect) {
  3912. cli_.set_follow_location(true);
  3913. auto res = cli_.Post("/1", "body", "text/plain");
  3914. ASSERT_TRUE(res);
  3915. EXPECT_EQ(StatusCode::OK_200, res->status);
  3916. EXPECT_EQ("redirected.", res->body);
  3917. EXPECT_EQ("/2", res->location);
  3918. }
  3919. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3920. auto res = cli_.Get("/dir/test.abcde");
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3924. EXPECT_EQ("abcde", res->body);
  3925. }
  3926. TEST_F(ServerTest, StaticFileRange) {
  3927. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3930. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3931. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(true, res->has_header("Content-Range"));
  3933. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3934. EXPECT_EQ(std::string("cd"), res->body);
  3935. }
  3936. TEST_F(ServerTest, StaticFileRanges) {
  3937. auto res =
  3938. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3941. EXPECT_TRUE(
  3942. res->get_header_value("Content-Type")
  3943. .find(
  3944. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3945. 0);
  3946. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3947. }
  3948. TEST_F(ServerTest, StaticFileRangeHead) {
  3949. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3952. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3953. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3954. EXPECT_EQ(true, res->has_header("Content-Range"));
  3955. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3956. }
  3957. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3958. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3962. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3963. EXPECT_EQ(true, res->has_header("Content-Range"));
  3964. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3965. res->get_header_value("Content-Range"));
  3966. EXPECT_EQ("LAST\n", res->body);
  3967. }
  3968. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3969. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3974. EXPECT_EQ(true, res->has_header("Content-Range"));
  3975. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3976. }
  3977. TEST_F(ServerTest, StaticFileBigFile) {
  3978. auto res = cli_.Get("/dir/1MB.txt");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3982. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3983. }
  3984. TEST_F(ServerTest, InvalidBaseDirMount) {
  3985. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3986. }
  3987. TEST_F(ServerTest, Binary) {
  3988. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3989. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3990. "application/octet-stream");
  3991. ASSERT_TRUE(res);
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_EQ(4U, res->body.size());
  3994. res = cli_.Put("/binary", binary.data(), binary.size(),
  3995. "application/octet-stream");
  3996. ASSERT_TRUE(res);
  3997. ASSERT_EQ(StatusCode::OK_200, res->status);
  3998. ASSERT_EQ(4U, res->body.size());
  3999. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4000. "application/octet-stream");
  4001. ASSERT_TRUE(res);
  4002. ASSERT_EQ(StatusCode::OK_200, res->status);
  4003. ASSERT_EQ(4U, res->body.size());
  4004. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4005. "application/octet-stream");
  4006. ASSERT_TRUE(res);
  4007. ASSERT_EQ(StatusCode::OK_200, res->status);
  4008. ASSERT_EQ(4U, res->body.size());
  4009. }
  4010. TEST_F(ServerTest, BinaryString) {
  4011. auto binary = std::string("\x00\x01\x02\x03", 4);
  4012. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4013. ASSERT_TRUE(res);
  4014. ASSERT_EQ(StatusCode::OK_200, res->status);
  4015. ASSERT_EQ(4U, res->body.size());
  4016. res = cli_.Put("/binary", binary, "application/octet-stream");
  4017. ASSERT_TRUE(res);
  4018. ASSERT_EQ(StatusCode::OK_200, res->status);
  4019. ASSERT_EQ(4U, res->body.size());
  4020. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ(4U, res->body.size());
  4024. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::OK_200, res->status);
  4027. ASSERT_EQ(4U, res->body.size());
  4028. }
  4029. TEST_F(ServerTest, EmptyRequest) {
  4030. auto res = cli_.Get("");
  4031. ASSERT_TRUE(!res);
  4032. EXPECT_EQ(Error::Connection, res.error());
  4033. }
  4034. TEST_F(ServerTest, LongRequest) {
  4035. std::string request;
  4036. for (size_t i = 0; i < 545; i++) {
  4037. request += "/TooLongRequest";
  4038. }
  4039. request += "OK";
  4040. auto res = cli_.Get(request.c_str());
  4041. ASSERT_TRUE(res);
  4042. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4043. }
  4044. TEST_F(ServerTest, TooLongRequest) {
  4045. std::string request;
  4046. for (size_t i = 0; i < 546; i++) {
  4047. request += "/TooLongRequest";
  4048. }
  4049. request += "_NG";
  4050. auto start = std::chrono::high_resolution_clock::now();
  4051. cli_.set_keep_alive(true);
  4052. auto res = cli_.Get(request.c_str());
  4053. auto end = std::chrono::high_resolution_clock::now();
  4054. auto elapsed =
  4055. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4056. .count();
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4059. EXPECT_LE(elapsed, 1000);
  4060. EXPECT_EQ("close", res->get_header_value("Connection"));
  4061. EXPECT_FALSE(cli_.is_socket_open());
  4062. }
  4063. TEST_F(ServerTest, AlmostTooLongRequest) {
  4064. // test for #2046 - URI length check shouldn't include other content on req
  4065. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4066. // leading /, space, HTTP/1.1)
  4067. std::string request =
  4068. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4069. auto res = cli_.Get(request.c_str());
  4070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4072. }
  4073. TEST_F(ServerTest, LongHeader) {
  4074. Request req;
  4075. req.method = "GET";
  4076. req.path = "/hi";
  4077. std::string host_and_port;
  4078. host_and_port += HOST;
  4079. host_and_port += ":";
  4080. host_and_port += std::to_string(PORT);
  4081. req.headers.emplace("Host", host_and_port.c_str());
  4082. req.headers.emplace("Accept", "*/*");
  4083. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4084. req.headers.emplace(
  4085. "Header-Name",
  4086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4114. "@@@@@@@@@@@@@@@@");
  4115. auto res = std::make_shared<Response>();
  4116. auto error = Error::Success;
  4117. auto ret = cli_.send(req, *res, error);
  4118. ASSERT_TRUE(ret);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. }
  4121. TEST_F(ServerTest, LongQueryValue) {
  4122. auto start = std::chrono::high_resolution_clock::now();
  4123. cli_.set_keep_alive(true);
  4124. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4125. auto end = std::chrono::high_resolution_clock::now();
  4126. auto elapsed =
  4127. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4128. .count();
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4131. EXPECT_LE(elapsed, 1000);
  4132. EXPECT_EQ("close", res->get_header_value("Connection"));
  4133. EXPECT_FALSE(cli_.is_socket_open());
  4134. }
  4135. TEST_F(ServerTest, TooLongQueryValue) {
  4136. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4137. ASSERT_FALSE(res);
  4138. EXPECT_EQ(Error::Read, res.error());
  4139. }
  4140. TEST_F(ServerTest, TooLongHeader) {
  4141. Request req;
  4142. req.method = "GET";
  4143. req.path = "/hi";
  4144. std::string host_and_port;
  4145. host_and_port += HOST;
  4146. host_and_port += ":";
  4147. host_and_port += std::to_string(PORT);
  4148. req.headers.emplace("Host", host_and_port.c_str());
  4149. req.headers.emplace("Accept", "*/*");
  4150. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4151. req.headers.emplace(
  4152. "Header-Name",
  4153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4181. "@@@@@@@@@@@@@@@@@");
  4182. auto res = std::make_shared<Response>();
  4183. auto error = Error::Success;
  4184. auto ret = cli_.send(req, *res, error);
  4185. ASSERT_TRUE(ret);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. }
  4188. TEST_F(ServerTest, HeaderCountAtLimit) {
  4189. // Test with headers just under the 100 limit
  4190. httplib::Headers headers;
  4191. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4192. // This should keep us just under the 100 header limit
  4193. for (int i = 0; i < 95; i++) {
  4194. std::string name = "X-Test-Header-" + std::to_string(i);
  4195. std::string value = "value" + std::to_string(i);
  4196. headers.emplace(name, value);
  4197. }
  4198. // This should work fine as we're under the limit
  4199. auto res = cli_.Get("/hi", headers);
  4200. EXPECT_TRUE(res);
  4201. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4202. }
  4203. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4204. // Test with many headers to exceed the 100 limit
  4205. httplib::Headers headers;
  4206. // Add 150 headers to definitely exceed the 100 limit
  4207. for (int i = 0; i < 150; i++) {
  4208. std::string name = "X-Test-Header-" + std::to_string(i);
  4209. std::string value = "value" + std::to_string(i);
  4210. headers.emplace(name, value);
  4211. }
  4212. // This should fail due to exceeding header count limit
  4213. cli_.set_keep_alive(true);
  4214. auto res = cli_.Get("/hi", headers);
  4215. // The server should respond with 400 Bad Request
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4218. EXPECT_EQ("close", res->get_header_value("Connection"));
  4219. EXPECT_FALSE(cli_.is_socket_open());
  4220. }
  4221. TEST_F(ServerTest, PercentEncoding) {
  4222. auto res = cli_.Get("/e%6edwith%");
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::OK_200, res->status);
  4225. }
  4226. TEST_F(ServerTest, PercentEncodingUnicode) {
  4227. auto res = cli_.Get("/e%u006edwith%");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST_F(ServerTest, InvalidPercentEncoding) {
  4232. auto res = cli_.Get("/%endwith%");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4235. }
  4236. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4237. auto res = cli_.Get("/%uendwith%");
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4240. }
  4241. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4242. auto res = cli_.Get("/hello?aaa=bbb%");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4245. }
  4246. TEST_F(ServerTest, PlusSignEncoding) {
  4247. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("a +b", res->body);
  4251. }
  4252. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4253. // This test simulates a potential DoS attack using many headers
  4254. // to verify our security fix prevents memory exhaustion
  4255. httplib::Headers attack_headers;
  4256. // Attempt to add many headers like an attacker would (200 headers to far
  4257. // exceed limit)
  4258. for (int i = 0; i < 200; i++) {
  4259. std::string name = "X-Attack-Header-" + std::to_string(i);
  4260. std::string value = "attack_payload_" + std::to_string(i);
  4261. attack_headers.emplace(name, value);
  4262. }
  4263. // Try to POST with excessive headers
  4264. cli_.set_keep_alive(true);
  4265. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4266. // Should either fail or return 400 Bad Request due to security limit
  4267. if (res) {
  4268. // If we get a response, it should be 400 Bad Request
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ("close", res->get_header_value("Connection"));
  4271. }
  4272. EXPECT_FALSE(cli_.is_socket_open());
  4273. }
  4274. TEST_F(ServerTest, MultipartFormData) {
  4275. UploadFormDataItems items = {
  4276. {"text1", "text default", "", ""},
  4277. {"text2", "aωb", "", ""},
  4278. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4279. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4280. {"file3", "", "", "application/octet-stream"},
  4281. {"file4", "", "", " application/json tmp-string "}};
  4282. auto res = cli_.Post("/multipart", items);
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. }
  4286. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4287. UploadFormDataItems items = {
  4288. {"text", "default text", "", ""},
  4289. {"multi_text1", "aaaaa", "", ""},
  4290. {"multi_text1", "bbbbb", "", ""},
  4291. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4292. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4293. "application/json"},
  4294. };
  4295. auto res = cli_.Post("/multipart/multi_file_values", items);
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. }
  4299. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4300. auto res = cli_.Get("/hi");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4304. EXPECT_EQ("Hello World!", res->body);
  4305. }
  4306. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4307. Request req;
  4308. req.method = "POST";
  4309. req.path = "/chunked";
  4310. std::string host_and_port;
  4311. host_and_port += HOST;
  4312. host_and_port += ":";
  4313. host_and_port += std::to_string(PORT);
  4314. req.headers.emplace("Host", host_and_port.c_str());
  4315. req.headers.emplace("Accept", "*/*");
  4316. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4317. req.headers.emplace("Content-Type", "text/plain");
  4318. req.headers.emplace("Content-Length", "0");
  4319. req.headers.emplace(
  4320. "Transfer-Encoding",
  4321. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4322. // Client does not chunk, so make a chunked body manually.
  4323. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4324. auto res = std::make_shared<Response>();
  4325. auto error = Error::Success;
  4326. auto ret = cli_.send(req, *res, error);
  4327. ASSERT_TRUE(ret);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. }
  4330. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4331. // rather than treat them as valid lengths.
  4332. template <typename ClientT>
  4333. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4334. Request req;
  4335. req.method = "POST";
  4336. req.path = "/chunked";
  4337. std::string host_and_port;
  4338. host_and_port += HOST;
  4339. host_and_port += ":";
  4340. host_and_port += std::to_string(PORT);
  4341. req.headers.emplace("Host", host_and_port.c_str());
  4342. req.headers.emplace("Content-Length", "0");
  4343. req.headers.emplace("Transfer-Encoding", "chunked");
  4344. req.body = body;
  4345. auto res = std::make_shared<Response>();
  4346. auto error = Error::Success;
  4347. ASSERT_TRUE(cli.send(req, *res, error));
  4348. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4349. }
  4350. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4351. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4352. }
  4353. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4354. expect_chunked_body_rejected(
  4355. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4356. }
  4357. TEST_F(ServerTest, GetStreamed2) {
  4358. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4361. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4362. EXPECT_EQ(true, res->has_header("Content-Range"));
  4363. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4364. EXPECT_EQ(std::string("ab"), res->body);
  4365. }
  4366. TEST_F(ServerTest, GetStreamed) {
  4367. auto res = cli_.Get("/streamed");
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4371. EXPECT_EQ(std::string("aaabbb"), res->body);
  4372. }
  4373. TEST_F(ServerTest, GetStreamedWithRange1) {
  4374. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4377. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4378. EXPECT_EQ(true, res->has_header("Content-Range"));
  4379. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4380. EXPECT_EQ(std::string("def"), res->body);
  4381. }
  4382. TEST_F(ServerTest, GetStreamedWithRange2) {
  4383. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4386. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4389. EXPECT_EQ(std::string("bcdefg"), res->body);
  4390. }
  4391. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4392. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4393. ASSERT_TRUE(res);
  4394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4395. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4396. EXPECT_EQ(true, res->has_header("Content-Range"));
  4397. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4398. EXPECT_EQ(std::string("efg"), res->body);
  4399. }
  4400. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4401. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4404. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4405. EXPECT_EQ(false, res->has_header("Content-Range"));
  4406. EXPECT_EQ(0U, res->body.size());
  4407. }
  4408. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4409. auto res = cli_.Get("/streamed-with-range",
  4410. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4411. "92233720368547758079223372036854775807"}});
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4414. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4415. EXPECT_EQ(false, res->has_header("Content-Range"));
  4416. EXPECT_EQ(0U, res->body.size());
  4417. }
  4418. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4419. auto res = cli_.Get(
  4420. "/with-range",
  4421. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4422. {"Accept-Encoding", ""}});
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4425. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4426. EXPECT_EQ(true, res->has_header("Content-Range"));
  4427. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4428. EXPECT_EQ(std::string("abcdefg"), res->body);
  4429. }
  4430. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4431. auto res = cli_.Get("/with-range", {
  4432. {"Range", "bytes=0-"},
  4433. {"Accept-Encoding", ""},
  4434. });
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4437. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4438. EXPECT_EQ(true, res->has_header("Content-Range"));
  4439. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4440. EXPECT_EQ(std::string("abcdefg"), res->body);
  4441. }
  4442. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4443. auto res =
  4444. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4445. ASSERT_TRUE(res);
  4446. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4447. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4448. EXPECT_EQ(false, res->has_header("Content-Range"));
  4449. EXPECT_EQ(267U, res->body.size());
  4450. // Check that both range contents are present
  4451. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4452. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4453. // Check that Content-Range headers are present for both ranges
  4454. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4455. std::string::npos);
  4456. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4457. std::string::npos);
  4458. }
  4459. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4460. Ranges ranges;
  4461. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4462. ranges.emplace_back(0, -1);
  4463. }
  4464. auto res =
  4465. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4466. ASSERT_TRUE(res);
  4467. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4468. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4469. EXPECT_EQ(false, res->has_header("Content-Range"));
  4470. EXPECT_EQ(0U, res->body.size());
  4471. }
  4472. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4473. auto res =
  4474. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4475. ASSERT_TRUE(res);
  4476. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4477. EXPECT_EQ(5U, res->body.size());
  4478. // Check that overlapping ranges are coalesced into a single range
  4479. EXPECT_EQ("bcdef", res->body);
  4480. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4481. // Should be single range, not multipart
  4482. EXPECT_TRUE(res->has_header("Content-Range"));
  4483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4484. }
  4485. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4486. auto res =
  4487. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4488. ASSERT_TRUE(res);
  4489. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4490. EXPECT_EQ(268U, res->body.size());
  4491. // Check that both range contents are present
  4492. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4493. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4494. // Check that Content-Range headers are present for both ranges
  4495. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4496. std::string::npos);
  4497. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4498. std::string::npos);
  4499. }
  4500. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4501. auto res =
  4502. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4503. ASSERT_TRUE(res);
  4504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4505. EXPECT_EQ(269U, res->body.size());
  4506. // Check that both duplicate range contents are present
  4507. size_t first_abc = res->body.find("abc\r\n");
  4508. EXPECT_TRUE(first_abc != std::string::npos);
  4509. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4510. EXPECT_TRUE(second_abc != std::string::npos);
  4511. // Check that Content-Range headers are present for both ranges
  4512. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4513. EXPECT_TRUE(first_range != std::string::npos);
  4514. size_t second_range =
  4515. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4516. EXPECT_TRUE(second_range != std::string::npos);
  4517. }
  4518. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4519. auto res = cli_.Get("/streamed-with-range?error",
  4520. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4523. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4524. EXPECT_EQ(false, res->has_header("Content-Range"));
  4525. EXPECT_EQ(0U, res->body.size());
  4526. }
  4527. TEST_F(ServerTest, GetStreamedEndless) {
  4528. uint64_t offset = 0;
  4529. auto res = cli_.Get("/streamed-cancel",
  4530. [&](const char * /*data*/, uint64_t data_length) {
  4531. if (offset < 100) {
  4532. offset += data_length;
  4533. return true;
  4534. }
  4535. return false;
  4536. });
  4537. ASSERT_TRUE(!res);
  4538. EXPECT_EQ(Error::Canceled, res.error());
  4539. }
  4540. TEST_F(ServerTest, ClientStop) {
  4541. std::atomic_size_t count{4};
  4542. std::vector<std::thread> threads;
  4543. for (auto i = count.load(); i != 0; --i) {
  4544. threads.emplace_back([&]() {
  4545. auto res = cli_.Get("/streamed-cancel",
  4546. [&](const char *, uint64_t) { return true; });
  4547. --count;
  4548. ASSERT_TRUE(!res);
  4549. EXPECT_TRUE(res.error() == Error::Canceled ||
  4550. res.error() == Error::Read || res.error() == Error::Write);
  4551. });
  4552. }
  4553. std::this_thread::sleep_for(std::chrono::seconds(2));
  4554. while (count != 0) {
  4555. cli_.stop();
  4556. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4557. }
  4558. for (auto &t : threads) {
  4559. t.join();
  4560. }
  4561. }
  4562. TEST_F(ServerTest, GetWithRange1) {
  4563. auto res = cli_.Get("/with-range", {
  4564. make_range_header({{3, 5}}),
  4565. {"Accept-Encoding", ""},
  4566. });
  4567. ASSERT_TRUE(res);
  4568. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4569. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4570. EXPECT_EQ(true, res->has_header("Content-Range"));
  4571. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4572. EXPECT_EQ(std::string("def"), res->body);
  4573. }
  4574. TEST_F(ServerTest, GetWithRange2) {
  4575. auto res = cli_.Get("/with-range", {
  4576. make_range_header({{1, -1}}),
  4577. {"Accept-Encoding", ""},
  4578. });
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4581. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4582. EXPECT_EQ(true, res->has_header("Content-Range"));
  4583. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4584. EXPECT_EQ(std::string("bcdefg"), res->body);
  4585. }
  4586. TEST_F(ServerTest, GetWithRange3) {
  4587. auto res = cli_.Get("/with-range", {
  4588. make_range_header({{0, 0}}),
  4589. {"Accept-Encoding", ""},
  4590. });
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4593. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4594. EXPECT_EQ(true, res->has_header("Content-Range"));
  4595. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4596. EXPECT_EQ(std::string("a"), res->body);
  4597. }
  4598. TEST_F(ServerTest, GetWithRange4) {
  4599. auto res = cli_.Get("/with-range", {
  4600. make_range_header({{-1, 2}}),
  4601. {"Accept-Encoding", ""},
  4602. });
  4603. ASSERT_TRUE(res);
  4604. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4605. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4606. EXPECT_EQ(true, res->has_header("Content-Range"));
  4607. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4608. EXPECT_EQ(std::string("fg"), res->body);
  4609. }
  4610. TEST_F(ServerTest, GetWithRange5) {
  4611. auto res = cli_.Get("/with-range", {
  4612. make_range_header({{0, 5}}),
  4613. {"Accept-Encoding", ""},
  4614. });
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4617. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4618. EXPECT_EQ(true, res->has_header("Content-Range"));
  4619. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4620. EXPECT_EQ(std::string("abcdef"), res->body);
  4621. }
  4622. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4623. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4624. ASSERT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4626. }
  4627. TEST_F(ServerTest, GetWithRangeMultipart) {
  4628. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4631. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4632. EXPECT_EQ(false, res->has_header("Content-Range"));
  4633. EXPECT_EQ(267U, res->body.size());
  4634. }
  4635. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4636. auto res =
  4637. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4640. }
  4641. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4642. auto res = cli_.Get("/with-range-customized-response",
  4643. {{make_range_header({{1, 2}})}});
  4644. ASSERT_TRUE(res);
  4645. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4646. EXPECT_EQ(true, res->has_header("Content-Length"));
  4647. EXPECT_EQ(false, res->has_header("Content-Range"));
  4648. EXPECT_EQ(JSON_DATA, res->body);
  4649. }
  4650. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4651. auto res = cli_.Get("/with-range-customized-response",
  4652. {{make_range_header({{1, 2}, {4, 5}})}});
  4653. ASSERT_TRUE(res);
  4654. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4655. EXPECT_EQ(true, res->has_header("Content-Length"));
  4656. EXPECT_EQ(false, res->has_header("Content-Range"));
  4657. EXPECT_EQ(JSON_DATA, res->body);
  4658. }
  4659. TEST_F(ServerTest, Issue1772) {
  4660. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4661. ASSERT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4663. }
  4664. TEST_F(ServerTest, Issue609) {
  4665. auto res = cli_.Delete("/issue609");
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ(std::string("ok"), res->body);
  4669. }
  4670. TEST_F(ServerTest, GetStreamedChunked) {
  4671. auto res = cli_.Get("/streamed-chunked");
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. EXPECT_EQ(std::string("123456789"), res->body);
  4675. }
  4676. TEST_F(ServerTest, GetStreamedChunked2) {
  4677. auto res = cli_.Get("/streamed-chunked2");
  4678. ASSERT_TRUE(res);
  4679. EXPECT_EQ(StatusCode::OK_200, res->status);
  4680. EXPECT_EQ(std::string("123456789"), res->body);
  4681. }
  4682. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4683. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4684. ASSERT_TRUE(res);
  4685. EXPECT_EQ(StatusCode::OK_200, res->status);
  4686. EXPECT_EQ(std::string("123456789"), res->body);
  4687. EXPECT_TRUE(res->has_header("Trailer"));
  4688. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4689. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4690. // Trailers are now stored separately from headers (security fix)
  4691. EXPECT_EQ(2U, res->trailers.size());
  4692. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4693. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4694. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4695. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4696. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4697. // Verify trailers are NOT in headers (security verification)
  4698. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4699. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4700. }
  4701. TEST_F(ServerTest, LargeChunkedPost) {
  4702. Request req;
  4703. req.method = "POST";
  4704. req.path = "/large-chunked";
  4705. std::string host_and_port;
  4706. host_and_port += HOST;
  4707. host_and_port += ":";
  4708. host_and_port += std::to_string(PORT);
  4709. req.headers.emplace("Host", host_and_port.c_str());
  4710. req.headers.emplace("Accept", "*/*");
  4711. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4712. req.headers.emplace("Content-Type", "text/plain");
  4713. req.headers.emplace("Content-Length", "0");
  4714. req.headers.emplace("Transfer-Encoding", "chunked");
  4715. std::string long_string(30 * 1024u, 'a');
  4716. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4717. // Attempt to make a large enough post to exceed OS buffers, to test that
  4718. // the server handles short reads if the full chunk data isn't available.
  4719. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4720. auto res = std::make_shared<Response>();
  4721. auto error = Error::Success;
  4722. auto ret = cli_.send(req, *res, error);
  4723. ASSERT_TRUE(ret);
  4724. EXPECT_EQ(StatusCode::OK_200, res->status);
  4725. }
  4726. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4727. auto res = cli_.Get("/remote_addr");
  4728. ASSERT_TRUE(res);
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4731. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4732. }
  4733. TEST_F(ServerTest, GetMethodLocalAddr) {
  4734. auto res = cli_.Get("/local_addr");
  4735. ASSERT_TRUE(res);
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4738. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4739. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4740. }
  4741. TEST_F(ServerTest, HTTPResponseSplitting) {
  4742. auto res = cli_.Get("/http_response_splitting");
  4743. ASSERT_TRUE(res);
  4744. EXPECT_EQ(StatusCode::OK_200, res->status);
  4745. }
  4746. TEST_F(ServerTest, SlowRequest) {
  4747. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4748. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4749. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4750. }
  4751. #if 0
  4752. TEST_F(ServerTest, SlowPost) {
  4753. char buffer[64 * 1024];
  4754. memset(buffer, 0x42, sizeof(buffer));
  4755. auto res = cli_.Post(
  4756. "/slowpost", 64 * 1024 * 1024,
  4757. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4758. auto ret = sink.write(buffer, sizeof(buffer));
  4759. EXPECT_TRUE(ret);
  4760. return true;
  4761. },
  4762. "text/plain");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. }
  4766. TEST_F(ServerTest, SlowPostFail) {
  4767. char buffer[64 * 1024];
  4768. memset(buffer, 0x42, sizeof(buffer));
  4769. cli_.set_write_timeout(std::chrono::seconds(0));
  4770. auto res = cli_.Post(
  4771. "/slowpost", 64 * 1024 * 1024,
  4772. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4773. sink.write(buffer, sizeof(buffer));
  4774. return true;
  4775. },
  4776. "text/plain");
  4777. ASSERT_TRUE(!res);
  4778. EXPECT_EQ(Error::Write, res.error());
  4779. }
  4780. #endif
  4781. TEST_F(ServerTest, Put) {
  4782. auto res = cli_.Put("/put", "PUT", "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PUT", res->body);
  4786. }
  4787. TEST_F(ServerTest, PutWithContentProvider) {
  4788. auto res = cli_.Put(
  4789. "/put", 3,
  4790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4791. sink.os << "PUT";
  4792. return true;
  4793. },
  4794. "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("PUT", res->body);
  4798. }
  4799. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4800. auto res = cli_.Post(
  4801. "/post", 42,
  4802. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4803. return false;
  4804. },
  4805. "text/plain");
  4806. ASSERT_TRUE(!res);
  4807. EXPECT_EQ(Error::Canceled, res.error());
  4808. }
  4809. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4810. auto res = cli_.Put(
  4811. "/put",
  4812. [](size_t /*offset*/, DataSink &sink) {
  4813. sink.os << "PUT";
  4814. sink.done();
  4815. return true;
  4816. },
  4817. "text/plain");
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. EXPECT_EQ("PUT", res->body);
  4821. }
  4822. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4823. auto res = cli_.Post(
  4824. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4825. "text/plain");
  4826. ASSERT_TRUE(!res);
  4827. EXPECT_EQ(Error::Canceled, res.error());
  4828. }
  4829. TEST_F(ServerTest, PostLoopBack) {
  4830. std::string body;
  4831. auto res = cli_.Post(
  4832. "/post-loopback", 9,
  4833. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4834. EXPECT_EQ(9u, length);
  4835. sink.write("123", 3);
  4836. sink.write("456", 3);
  4837. sink.write("789", 3);
  4838. return true;
  4839. },
  4840. "text/plain",
  4841. [&body](const char *data, size_t data_length) {
  4842. body.append(data, data_length);
  4843. return true;
  4844. });
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. EXPECT_EQ("123456789", body);
  4848. }
  4849. TEST_F(ServerTest, PutLoopBack) {
  4850. std::string body;
  4851. auto res = cli_.Put(
  4852. "/put-loopback", 9,
  4853. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4854. EXPECT_EQ(9u, length);
  4855. sink.write("123", 3);
  4856. sink.write("456", 3);
  4857. sink.write("789", 3);
  4858. return true;
  4859. },
  4860. "text/plain",
  4861. [&body](const char *data, size_t data_length) {
  4862. body.append(data, data_length);
  4863. return true;
  4864. });
  4865. ASSERT_TRUE(res);
  4866. EXPECT_EQ(StatusCode::OK_200, res->status);
  4867. EXPECT_EQ("123456789", body);
  4868. }
  4869. TEST_F(ServerTest, PatchLoopBack) {
  4870. std::string body;
  4871. auto res = cli_.Patch(
  4872. "/patch-loopback", 9,
  4873. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4874. EXPECT_EQ(9u, length);
  4875. sink.write("123", 3);
  4876. sink.write("456", 3);
  4877. sink.write("789", 3);
  4878. return true;
  4879. },
  4880. "text/plain",
  4881. [&body](const char *data, size_t data_length) {
  4882. body.append(data, data_length);
  4883. return true;
  4884. });
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. EXPECT_EQ("123456789", body);
  4888. }
  4889. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4890. std::string body;
  4891. auto res = cli_.Post(
  4892. "/post-loopback",
  4893. [](size_t /*offset*/, DataSink &sink) {
  4894. sink.write("123", 3);
  4895. sink.write("456", 3);
  4896. sink.write("789", 3);
  4897. sink.done();
  4898. return true;
  4899. },
  4900. "text/plain",
  4901. [&body](const char *data, size_t data_length) {
  4902. body.append(data, data_length);
  4903. return true;
  4904. });
  4905. ASSERT_TRUE(res);
  4906. EXPECT_EQ(StatusCode::OK_200, res->status);
  4907. EXPECT_EQ("123456789", body);
  4908. }
  4909. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4910. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4911. cli_.set_compress(true);
  4912. auto res = cli_.Put(
  4913. "/put", 3,
  4914. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4915. sink.os << "PUT";
  4916. return true;
  4917. },
  4918. "text/plain");
  4919. ASSERT_TRUE(res);
  4920. EXPECT_EQ(StatusCode::OK_200, res->status);
  4921. EXPECT_EQ("PUT", res->body);
  4922. }
  4923. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4924. cli_.set_compress(true);
  4925. auto res = cli_.Post(
  4926. "/post", 42,
  4927. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4928. return false;
  4929. },
  4930. "text/plain");
  4931. ASSERT_TRUE(!res);
  4932. EXPECT_EQ(Error::Canceled, res.error());
  4933. }
  4934. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4935. cli_.set_compress(true);
  4936. auto res = cli_.Put(
  4937. "/put",
  4938. [](size_t /*offset*/, DataSink &sink) {
  4939. sink.os << "PUT";
  4940. sink.done();
  4941. return true;
  4942. },
  4943. "text/plain");
  4944. ASSERT_TRUE(res);
  4945. EXPECT_EQ(StatusCode::OK_200, res->status);
  4946. EXPECT_EQ("PUT", res->body);
  4947. }
  4948. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4949. cli_.set_compress(true);
  4950. auto res = cli_.Post(
  4951. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4952. "text/plain");
  4953. ASSERT_TRUE(!res);
  4954. EXPECT_EQ(Error::Canceled, res.error());
  4955. }
  4956. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4957. cli_.set_compress(true);
  4958. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4959. ASSERT_TRUE(res);
  4960. EXPECT_EQ(StatusCode::OK_200, res->status);
  4961. EXPECT_EQ(LARGE_DATA, res->body);
  4962. }
  4963. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4964. #ifdef CPPHTTPLIB_SSL_ENABLED
  4965. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4966. Client cli(s.c_str());
  4967. cli.enable_server_certificate_verification(false);
  4968. #else
  4969. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4970. Client cli(s.c_str());
  4971. #endif
  4972. cli.set_compress(true);
  4973. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ(LARGE_DATA, res->body);
  4977. // The compressed size should be less than a 10th of the original. May vary
  4978. // depending on the zlib library.
  4979. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4980. static_cast<uint64_t>(10 * 1024 * 1024));
  4981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4982. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4983. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4984. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4985. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4986. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4987. #endif
  4988. }
  4989. TEST_F(ServerTest, PutContentWithDeflate) {
  4990. cli_.set_compress(false);
  4991. Headers headers;
  4992. headers.emplace("Content-Encoding", "deflate");
  4993. // PUT in deflate format:
  4994. auto res = cli_.Put("/put", headers,
  4995. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4996. ASSERT_TRUE(res);
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("PUT", res->body);
  4999. }
  5000. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5001. Headers headers;
  5002. headers.emplace("Accept-Encoding", "gzip, deflate");
  5003. auto res = cli_.Get("/streamed-chunked", headers);
  5004. ASSERT_TRUE(res);
  5005. EXPECT_EQ(StatusCode::OK_200, res->status);
  5006. EXPECT_EQ(std::string("123456789"), res->body);
  5007. }
  5008. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5009. Headers headers;
  5010. headers.emplace("Accept-Encoding", "gzip, deflate");
  5011. auto res = cli_.Get("/streamed-chunked2", headers);
  5012. ASSERT_TRUE(res);
  5013. EXPECT_EQ(StatusCode::OK_200, res->status);
  5014. EXPECT_EQ(std::string("123456789"), res->body);
  5015. }
  5016. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5017. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5018. ASSERT_TRUE(res);
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. }
  5021. TEST(GzipDecompressor, ChunkedDecompression) {
  5022. std::string data;
  5023. for (size_t i = 0; i < 32 * 1024; ++i) {
  5024. data.push_back(static_cast<char>('a' + i % 26));
  5025. }
  5026. std::string compressed_data;
  5027. {
  5028. httplib::detail::gzip_compressor compressor;
  5029. bool result = compressor.compress(
  5030. data.data(), data.size(),
  5031. /*last=*/true,
  5032. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5033. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5034. compressed_data_size);
  5035. return true;
  5036. });
  5037. ASSERT_TRUE(result);
  5038. }
  5039. std::string decompressed_data;
  5040. {
  5041. httplib::detail::gzip_decompressor decompressor;
  5042. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5043. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5044. size_t chunk_size = 130;
  5045. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5046. chunk_begin += chunk_size) {
  5047. size_t current_chunk_size =
  5048. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5049. bool result = decompressor.decompress(
  5050. compressed_data.data() + chunk_begin, current_chunk_size,
  5051. [&](const char *decompressed_data_chunk,
  5052. size_t decompressed_data_chunk_size) {
  5053. decompressed_data.insert(decompressed_data.size(),
  5054. decompressed_data_chunk,
  5055. decompressed_data_chunk_size);
  5056. return true;
  5057. });
  5058. ASSERT_TRUE(result);
  5059. }
  5060. }
  5061. ASSERT_EQ(data, decompressed_data);
  5062. }
  5063. TEST(GzipDecompressor, DeflateDecompression) {
  5064. std::string original_text = "Raw deflate without gzip";
  5065. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5066. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5067. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5068. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5069. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5070. std::string decompressed_data;
  5071. {
  5072. httplib::detail::gzip_decompressor decompressor;
  5073. bool result = decompressor.decompress(
  5074. compressed_data.data(), compressed_data.size(),
  5075. [&](const char *decompressed_data_chunk,
  5076. size_t decompressed_data_chunk_size) {
  5077. decompressed_data.insert(decompressed_data.size(),
  5078. decompressed_data_chunk,
  5079. decompressed_data_chunk_size);
  5080. return true;
  5081. });
  5082. ASSERT_TRUE(result);
  5083. }
  5084. ASSERT_EQ(original_text, decompressed_data);
  5085. }
  5086. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5087. std::string original_text = "Raw deflate without gzip";
  5088. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5089. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5090. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5091. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5092. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5093. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5094. std::string decompressed_data;
  5095. {
  5096. httplib::detail::gzip_decompressor decompressor;
  5097. bool result = decompressor.decompress(
  5098. compressed_data.data(), compressed_data.size(),
  5099. [&](const char *decompressed_data_chunk,
  5100. size_t decompressed_data_chunk_size) {
  5101. decompressed_data.insert(decompressed_data.size(),
  5102. decompressed_data_chunk,
  5103. decompressed_data_chunk_size);
  5104. return true;
  5105. });
  5106. ASSERT_TRUE(result);
  5107. }
  5108. ASSERT_EQ(original_text, decompressed_data);
  5109. }
  5110. #endif
  5111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5112. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5113. Headers headers;
  5114. headers.emplace("Accept-Encoding", "br");
  5115. auto res = cli_.Get("/streamed-chunked", headers);
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ(std::string("123456789"), res->body);
  5119. }
  5120. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5121. Headers headers;
  5122. headers.emplace("Accept-Encoding", "br");
  5123. auto res = cli_.Get("/streamed-chunked2", headers);
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ(std::string("123456789"), res->body);
  5127. }
  5128. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5129. cli_.set_compress(true);
  5130. auto res = cli_.Put(
  5131. "/put", 3,
  5132. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5133. sink.os << "PUT";
  5134. return true;
  5135. },
  5136. "text/plain");
  5137. ASSERT_TRUE(res);
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("PUT", res->body);
  5140. }
  5141. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5142. cli_.set_compress(true);
  5143. auto res = cli_.Put(
  5144. "/put",
  5145. [](size_t /*offset*/, DataSink &sink) {
  5146. sink.os << "PUT";
  5147. sink.done();
  5148. return true;
  5149. },
  5150. "text/plain");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("PUT", res->body);
  5154. }
  5155. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5156. cli_.set_compress(true);
  5157. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5158. ASSERT_TRUE(res);
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. EXPECT_EQ(LARGE_DATA, res->body);
  5161. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5162. }
  5163. #endif
  5164. TEST_F(ServerTest, Patch) {
  5165. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5166. ASSERT_TRUE(res);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. EXPECT_EQ("PATCH", res->body);
  5169. }
  5170. TEST_F(ServerTest, Delete) {
  5171. auto res = cli_.Delete("/delete");
  5172. ASSERT_TRUE(res);
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. EXPECT_EQ("DELETE", res->body);
  5175. }
  5176. TEST_F(ServerTest, DeleteContentReceiver) {
  5177. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5178. ASSERT_TRUE(res);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("content", res->body);
  5181. }
  5182. TEST_F(ServerTest, Options) {
  5183. auto res = cli_.Options("*");
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::OK_200, res->status);
  5186. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5187. EXPECT_TRUE(res->body.empty());
  5188. }
  5189. TEST_F(ServerTest, URL) {
  5190. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5191. ASSERT_TRUE(res);
  5192. EXPECT_EQ(StatusCode::OK_200, res->status);
  5193. }
  5194. TEST_F(ServerTest, ArrayParam) {
  5195. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5196. ASSERT_TRUE(res);
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. }
  5199. TEST_F(ServerTest, ArrayParamValues) {
  5200. auto res =
  5201. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5202. ASSERT_TRUE(res);
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. }
  5205. TEST_F(ServerTest, NoMultipleHeaders) {
  5206. Headers headers = {{"Content-Length", "5"}};
  5207. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5208. "text/plain");
  5209. ASSERT_TRUE(res);
  5210. EXPECT_EQ(StatusCode::OK_200, res->status);
  5211. }
  5212. TEST_F(ServerTest, PostContentReceiver) {
  5213. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5214. ASSERT_TRUE(res);
  5215. ASSERT_EQ(StatusCode::OK_200, res->status);
  5216. ASSERT_EQ("content", res->body);
  5217. }
  5218. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5219. UploadFormDataItems items = {
  5220. {"text1", "text default", "", ""},
  5221. {"text2", "aωb", "", ""},
  5222. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5223. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5224. {"file3", "", "", "application/octet-stream"},
  5225. };
  5226. auto res = cli_.Post("/content_receiver", items);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. }
  5230. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5231. UploadFormDataItems items = {
  5232. {"text1", "text default", "", ""},
  5233. {"text2", "aωb", "", ""},
  5234. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5235. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5236. {"file3", "", "", "application/octet-stream"},
  5237. };
  5238. auto boundary = std::string("+++++");
  5239. std::string body;
  5240. for (const auto &item : items) {
  5241. body += "--" + boundary + "\r\n";
  5242. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5243. if (!item.filename.empty()) {
  5244. body += "; filename=\"" + item.filename + "\"";
  5245. }
  5246. body += "\r\n";
  5247. if (!item.content_type.empty()) {
  5248. body += "Content-Type: " + item.content_type + "\r\n";
  5249. }
  5250. body += "\r\n";
  5251. body += item.content + "\r\n";
  5252. }
  5253. body += "--" + boundary + "--\r\n";
  5254. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5255. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5256. ASSERT_TRUE(res);
  5257. EXPECT_EQ(StatusCode::OK_200, res->status);
  5258. }
  5259. TEST_F(ServerTest, PostContentReceiverGzip) {
  5260. cli_.set_compress(true);
  5261. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5262. ASSERT_TRUE(res);
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. ASSERT_EQ("content", res->body);
  5265. }
  5266. TEST_F(ServerTest, PutContentReceiver) {
  5267. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5268. ASSERT_TRUE(res);
  5269. ASSERT_EQ(StatusCode::OK_200, res->status);
  5270. ASSERT_EQ("content", res->body);
  5271. }
  5272. TEST_F(ServerTest, PatchContentReceiver) {
  5273. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5274. ASSERT_TRUE(res);
  5275. ASSERT_EQ(StatusCode::OK_200, res->status);
  5276. ASSERT_EQ("content", res->body);
  5277. }
  5278. template <typename ClientType>
  5279. void TestWithHeadersAndContentReceiver(
  5280. ClientType &cli,
  5281. std::function<Result(ClientType &, const std::string &, const Headers &,
  5282. const std::string &, const std::string &,
  5283. ContentReceiver, DownloadProgress)>
  5284. request_func) {
  5285. Headers headers;
  5286. headers.emplace("X-Custom-Header", "test-value");
  5287. std::string received_body;
  5288. auto res = request_func(
  5289. cli, "/content_receiver", headers, "content", "application/json",
  5290. [&](const char *data, size_t data_length) {
  5291. received_body.append(data, data_length);
  5292. return true;
  5293. },
  5294. nullptr);
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("content", received_body);
  5298. }
  5299. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5300. #ifdef CPPHTTPLIB_SSL_ENABLED
  5301. using ClientT = SSLClient;
  5302. #else
  5303. using ClientT = Client;
  5304. #endif
  5305. TestWithHeadersAndContentReceiver<ClientT>(
  5306. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5307. const std::string &body, const std::string &content_type,
  5308. ContentReceiver receiver, DownloadProgress progress) {
  5309. return cli.Post(path, headers, body, content_type, receiver, progress);
  5310. });
  5311. }
  5312. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5313. #ifdef CPPHTTPLIB_SSL_ENABLED
  5314. using ClientT = SSLClient;
  5315. #else
  5316. using ClientT = Client;
  5317. #endif
  5318. TestWithHeadersAndContentReceiver<ClientT>(
  5319. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5320. const std::string &body, const std::string &content_type,
  5321. ContentReceiver receiver, DownloadProgress progress) {
  5322. return cli.Put(path, headers, body, content_type, receiver, progress);
  5323. });
  5324. }
  5325. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5326. #ifdef CPPHTTPLIB_SSL_ENABLED
  5327. using ClientT = SSLClient;
  5328. #else
  5329. using ClientT = Client;
  5330. #endif
  5331. TestWithHeadersAndContentReceiver<ClientT>(
  5332. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5333. const std::string &body, const std::string &content_type,
  5334. ContentReceiver receiver, DownloadProgress progress) {
  5335. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5336. });
  5337. }
  5338. template <typename ClientType>
  5339. void TestWithHeadersAndContentReceiverWithProgress(
  5340. ClientType &cli,
  5341. std::function<Result(ClientType &, const std::string &, const Headers &,
  5342. const std::string &, const std::string &,
  5343. ContentReceiver, DownloadProgress)>
  5344. request_func) {
  5345. Headers headers;
  5346. headers.emplace("X-Test-Header", "progress-test");
  5347. std::string received_body;
  5348. auto progress_called = false;
  5349. auto res = request_func(
  5350. cli, "/content_receiver", headers, "content", "text/plain",
  5351. [&](const char *data, size_t data_length) {
  5352. received_body.append(data, data_length);
  5353. return true;
  5354. },
  5355. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5356. progress_called = true;
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(res);
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. EXPECT_EQ("content", received_body);
  5362. EXPECT_TRUE(progress_called);
  5363. }
  5364. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5365. #ifdef CPPHTTPLIB_SSL_ENABLED
  5366. using ClientT = SSLClient;
  5367. #else
  5368. using ClientT = Client;
  5369. #endif
  5370. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5371. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5372. const std::string &body, const std::string &content_type,
  5373. ContentReceiver receiver, DownloadProgress progress) {
  5374. return cli.Post(path, headers, body, content_type, receiver, progress);
  5375. });
  5376. }
  5377. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5378. #ifdef CPPHTTPLIB_SSL_ENABLED
  5379. using ClientT = SSLClient;
  5380. #else
  5381. using ClientT = Client;
  5382. #endif
  5383. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5384. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5385. const std::string &body, const std::string &content_type,
  5386. ContentReceiver receiver, DownloadProgress progress) {
  5387. return cli.Put(path, headers, body, content_type, receiver, progress);
  5388. });
  5389. }
  5390. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5391. #ifdef CPPHTTPLIB_SSL_ENABLED
  5392. using ClientT = SSLClient;
  5393. #else
  5394. using ClientT = Client;
  5395. #endif
  5396. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5397. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5398. const std::string &body, const std::string &content_type,
  5399. ContentReceiver receiver, DownloadProgress progress) {
  5400. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5401. });
  5402. }
  5403. template <typename ClientType>
  5404. void TestWithHeadersAndContentReceiverError(
  5405. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5406. const Headers &, const std::string &,
  5407. const std::string &, ContentReceiver)>
  5408. request_func) {
  5409. Headers headers;
  5410. headers.emplace("X-Error-Test", "true");
  5411. std::string received_body;
  5412. auto receiver_failed = false;
  5413. auto res =
  5414. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5415. [&](const char *data, size_t data_length) {
  5416. received_body.append(data, data_length);
  5417. receiver_failed = true;
  5418. return false;
  5419. });
  5420. ASSERT_FALSE(res);
  5421. EXPECT_TRUE(receiver_failed);
  5422. }
  5423. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5424. #ifdef CPPHTTPLIB_SSL_ENABLED
  5425. using ClientT = SSLClient;
  5426. #else
  5427. using ClientT = Client;
  5428. #endif
  5429. TestWithHeadersAndContentReceiverError<ClientT>(
  5430. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5431. const std::string &body, const std::string &content_type,
  5432. ContentReceiver receiver) {
  5433. return cli.Post(path, headers, body, content_type, receiver);
  5434. });
  5435. }
  5436. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5437. #ifdef CPPHTTPLIB_SSL_ENABLED
  5438. using ClientT = SSLClient;
  5439. #else
  5440. using ClientT = Client;
  5441. #endif
  5442. TestWithHeadersAndContentReceiverError<ClientT>(
  5443. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5444. const std::string &body, const std::string &content_type,
  5445. ContentReceiver receiver) {
  5446. return cli.Put(path, headers, body, content_type, receiver);
  5447. });
  5448. }
  5449. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5450. #ifdef CPPHTTPLIB_SSL_ENABLED
  5451. using ClientT = SSLClient;
  5452. #else
  5453. using ClientT = Client;
  5454. #endif
  5455. TestWithHeadersAndContentReceiverError<ClientT>(
  5456. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5457. const std::string &body, const std::string &content_type,
  5458. ContentReceiver receiver) {
  5459. return cli.Patch(path, headers, body, content_type, receiver);
  5460. });
  5461. }
  5462. TEST_F(ServerTest, PostQueryStringAndBody) {
  5463. auto res =
  5464. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5465. ASSERT_TRUE(res);
  5466. ASSERT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. TEST_F(ServerTest, HTTP2Magic) {
  5469. Request req;
  5470. req.method = "PRI";
  5471. req.path = "*";
  5472. req.body = "SM";
  5473. auto res = std::make_shared<Response>();
  5474. auto error = Error::Success;
  5475. auto ret = cli_.send(req, *res, error);
  5476. ASSERT_TRUE(ret);
  5477. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5478. }
  5479. TEST_F(ServerTest, KeepAlive) {
  5480. auto res = cli_.Get("/hi");
  5481. ASSERT_TRUE(res);
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5484. EXPECT_EQ("Hello World!", res->body);
  5485. res = cli_.Get("/hi");
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5489. EXPECT_EQ("Hello World!", res->body);
  5490. res = cli_.Get("/hi");
  5491. ASSERT_TRUE(res);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5494. EXPECT_EQ("Hello World!", res->body);
  5495. res = cli_.Get("/not-exist");
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5498. res = cli_.Post("/empty", "", "text/plain");
  5499. ASSERT_TRUE(res);
  5500. EXPECT_EQ(StatusCode::OK_200, res->status);
  5501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("empty", res->body);
  5503. EXPECT_EQ("close", res->get_header_value("Connection"));
  5504. res = cli_.Post(
  5505. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5510. EXPECT_EQ("empty", res->body);
  5511. cli_.set_keep_alive(false);
  5512. res = cli_.Get("/last-request");
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_EQ("close", res->get_header_value("Connection"));
  5516. }
  5517. TEST_F(ServerTest, TooManyRedirect) {
  5518. cli_.set_follow_location(true);
  5519. auto res = cli_.Get("/redirect/0");
  5520. ASSERT_TRUE(!res);
  5521. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5522. }
  5523. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5524. Request req;
  5525. req.method = "FOOBAR";
  5526. req.path = "/hi";
  5527. cli_.set_keep_alive(true);
  5528. auto res = cli_.send(req);
  5529. ASSERT_TRUE(res);
  5530. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5531. EXPECT_EQ("close", res->get_header_value("Connection"));
  5532. EXPECT_FALSE(cli_.is_socket_open());
  5533. }
  5534. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5535. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5536. TEST_F(ServerTest, Gzip) {
  5537. Headers headers;
  5538. headers.emplace("Accept-Encoding", "gzip, deflate");
  5539. auto res = cli_.Get("/compress", headers);
  5540. ASSERT_TRUE(res);
  5541. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5543. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5545. "7890123456789012345678901234567890",
  5546. res->body);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. }
  5549. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5550. Headers headers;
  5551. headers.emplace("Accept-Encoding", "gzip, deflate");
  5552. auto res = cli_.Get("/compress-with-charset", headers);
  5553. ASSERT_TRUE(res);
  5554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5555. EXPECT_EQ("application/json; charset=utf-8",
  5556. res->get_header_value("Content-Type"));
  5557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5558. "7890123456789012345678901234567890",
  5559. res->body);
  5560. EXPECT_EQ(StatusCode::OK_200, res->status);
  5561. }
  5562. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5563. Headers headers;
  5564. headers.emplace("Accept-Encoding", "");
  5565. auto res = cli_.Get("/compress", headers);
  5566. ASSERT_TRUE(res);
  5567. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5569. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5571. "7890123456789012345678901234567890",
  5572. res->body);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, GzipWithContentReceiver) {
  5576. Headers headers;
  5577. headers.emplace("Accept-Encoding", "gzip, deflate");
  5578. std::string body;
  5579. auto res = cli_.Get("/compress", headers,
  5580. [&](const char *data, uint64_t data_length) {
  5581. EXPECT_EQ(100U, data_length);
  5582. body.append(data, data_length);
  5583. return true;
  5584. });
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5587. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5588. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5589. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5590. "7890123456789012345678901234567890",
  5591. body);
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. }
  5594. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5595. Headers headers;
  5596. headers.emplace("Accept-Encoding", "gzip, deflate");
  5597. cli_.set_decompress(false);
  5598. auto res = cli_.Get("/compress", headers);
  5599. ASSERT_TRUE(res);
  5600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(33U, res->body.size());
  5604. EXPECT_EQ(StatusCode::OK_200, res->status);
  5605. }
  5606. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "");
  5609. std::string body;
  5610. auto res = cli_.Get("/compress", headers,
  5611. [&](const char *data, uint64_t data_length) {
  5612. EXPECT_EQ(100U, data_length);
  5613. body.append(data, data_length);
  5614. return true;
  5615. });
  5616. ASSERT_TRUE(res);
  5617. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5618. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5619. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5620. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5621. "7890123456789012345678901234567890",
  5622. body);
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. }
  5625. TEST_F(ServerTest, NoGzip) {
  5626. Headers headers;
  5627. headers.emplace("Accept-Encoding", "gzip, deflate");
  5628. auto res = cli_.Get("/nocompress", headers);
  5629. ASSERT_TRUE(res);
  5630. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5631. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5634. "7890123456789012345678901234567890",
  5635. res->body);
  5636. EXPECT_EQ(StatusCode::OK_200, res->status);
  5637. }
  5638. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5639. Headers headers;
  5640. headers.emplace("Accept-Encoding", "gzip, deflate");
  5641. std::string body;
  5642. auto res = cli_.Get("/nocompress", headers,
  5643. [&](const char *data, uint64_t data_length) {
  5644. EXPECT_EQ(100U, data_length);
  5645. body.append(data, data_length);
  5646. return true;
  5647. });
  5648. ASSERT_TRUE(res);
  5649. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5650. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5651. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5652. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5653. "7890123456789012345678901234567890",
  5654. body);
  5655. EXPECT_EQ(StatusCode::OK_200, res->status);
  5656. }
  5657. TEST_F(ServerTest, MultipartFormDataGzip) {
  5658. UploadFormDataItems items = {
  5659. {"key1", "test", "", ""},
  5660. {"key2", "--abcdefg123", "", ""},
  5661. };
  5662. cli_.set_compress(true);
  5663. auto res = cli_.Post("/compress-multipart", items);
  5664. ASSERT_TRUE(res);
  5665. EXPECT_EQ(StatusCode::OK_200, res->status);
  5666. }
  5667. #endif
  5668. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5669. TEST_F(ServerTest, Brotli) {
  5670. Headers headers;
  5671. headers.emplace("Accept-Encoding", "br");
  5672. auto res = cli_.Get("/compress", headers);
  5673. ASSERT_TRUE(res);
  5674. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5675. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5676. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5677. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5678. "7890123456789012345678901234567890",
  5679. res->body);
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. }
  5682. #endif
  5683. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5684. TEST_F(ServerTest, Zstd) {
  5685. Headers headers;
  5686. headers.emplace("Accept-Encoding", "zstd");
  5687. auto res = cli_.Get("/compress", headers);
  5688. ASSERT_TRUE(res);
  5689. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5690. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5691. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5692. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5693. "7890123456789012345678901234567890",
  5694. res->body);
  5695. EXPECT_EQ(StatusCode::OK_200, res->status);
  5696. }
  5697. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5698. Headers headers;
  5699. headers.emplace("Accept-Encoding", "");
  5700. auto res = cli_.Get("/compress", headers);
  5701. ASSERT_TRUE(res);
  5702. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5704. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5705. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5706. "7890123456789012345678901234567890",
  5707. res->body);
  5708. EXPECT_EQ(StatusCode::OK_200, res->status);
  5709. }
  5710. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5711. Headers headers;
  5712. headers.emplace("Accept-Encoding", "zstd");
  5713. std::string body;
  5714. auto res = cli_.Get("/compress", headers,
  5715. [&](const char *data, uint64_t data_length) {
  5716. EXPECT_EQ(100U, data_length);
  5717. body.append(data, data_length);
  5718. return true;
  5719. });
  5720. ASSERT_TRUE(res);
  5721. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5722. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5723. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5724. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5725. "7890123456789012345678901234567890",
  5726. body);
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. }
  5729. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5730. Headers headers;
  5731. headers.emplace("Accept-Encoding", "zstd");
  5732. cli_.set_decompress(false);
  5733. auto res = cli_.Get("/compress", headers);
  5734. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5735. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5736. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5737. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5738. ASSERT_TRUE(res);
  5739. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5741. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. ASSERT_EQ(26U, res->body.size());
  5744. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5745. 0);
  5746. }
  5747. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5748. Headers headers;
  5749. headers.emplace("Accept-Encoding", "");
  5750. std::string body;
  5751. auto res = cli_.Get("/compress", headers,
  5752. [&](const char *data, uint64_t data_length) {
  5753. EXPECT_EQ(100U, data_length);
  5754. body.append(data, data_length);
  5755. return true;
  5756. });
  5757. ASSERT_TRUE(res);
  5758. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5760. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5761. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5762. "7890123456789012345678901234567890",
  5763. body);
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. }
  5766. TEST_F(ServerTest, NoZstd) {
  5767. Headers headers;
  5768. headers.emplace("Accept-Encoding", "zstd");
  5769. auto res = cli_.Get("/nocompress", headers);
  5770. ASSERT_TRUE(res);
  5771. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5772. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5773. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5774. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5775. "7890123456789012345678901234567890",
  5776. res->body);
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. }
  5779. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5780. Headers headers;
  5781. headers.emplace("Accept-Encoding", "zstd");
  5782. std::string body;
  5783. auto res = cli_.Get("/nocompress", headers,
  5784. [&](const char *data, uint64_t data_length) {
  5785. EXPECT_EQ(100U, data_length);
  5786. body.append(data, data_length);
  5787. return true;
  5788. });
  5789. ASSERT_TRUE(res);
  5790. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5791. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5792. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5793. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5794. "7890123456789012345678901234567890",
  5795. body);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. // TODO: How to enable zstd ??
  5799. TEST_F(ServerTest, MultipartFormDataZstd) {
  5800. UploadFormDataItems items = {
  5801. {"key1", "test", "", ""},
  5802. {"key2", "--abcdefg123", "", ""},
  5803. };
  5804. Headers headers;
  5805. headers.emplace("Accept-Encoding", "zstd");
  5806. cli_.set_compress(true);
  5807. auto res = cli_.Post("/compress-multipart", headers, items);
  5808. ASSERT_TRUE(res);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. }
  5811. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5812. Headers headers;
  5813. headers.emplace("Accept-Encoding", "zstd");
  5814. cli_.set_compress(true);
  5815. auto res = cli_.Put(
  5816. "/put", headers, 3,
  5817. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5818. sink.os << "PUT";
  5819. return true;
  5820. },
  5821. "text/plain");
  5822. ASSERT_TRUE(res);
  5823. EXPECT_EQ(StatusCode::OK_200, res->status);
  5824. EXPECT_EQ("PUT", res->body);
  5825. }
  5826. // Pre-compression logging tests
  5827. TEST_F(ServerTest, PreCompressionLogging) {
  5828. // Test data for compression (matches the actual /compress endpoint content)
  5829. const std::string test_content =
  5830. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5831. "3456789012345678901234567890";
  5832. // Variables to capture logging data
  5833. std::string pre_compression_body;
  5834. std::string pre_compression_content_type;
  5835. std::string pre_compression_content_encoding;
  5836. std::string post_compression_body;
  5837. std::string post_compression_content_type;
  5838. std::string post_compression_content_encoding;
  5839. // Set up pre-compression logger
  5840. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5841. const Response &res) {
  5842. pre_compression_body = res.body;
  5843. pre_compression_content_type = res.get_header_value("Content-Type");
  5844. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5845. });
  5846. // Set up post-compression logger
  5847. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5848. post_compression_body = res.body;
  5849. post_compression_content_type = res.get_header_value("Content-Type");
  5850. post_compression_content_encoding =
  5851. res.get_header_value("Content-Encoding");
  5852. });
  5853. // Test with gzip compression
  5854. Headers headers;
  5855. headers.emplace("Accept-Encoding", "gzip");
  5856. auto res = cli_.Get("/compress", headers);
  5857. // Verify response was compressed
  5858. ASSERT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5861. // Verify pre-compression logger captured uncompressed content
  5862. EXPECT_EQ(test_content, pre_compression_body);
  5863. EXPECT_EQ("text/plain", pre_compression_content_type);
  5864. EXPECT_TRUE(pre_compression_content_encoding
  5865. .empty()); // No encoding header before compression
  5866. // Verify post-compression logger captured compressed content
  5867. EXPECT_NE(test_content,
  5868. post_compression_body); // Should be different after compression
  5869. EXPECT_EQ("text/plain", post_compression_content_type);
  5870. EXPECT_EQ("gzip", post_compression_content_encoding);
  5871. // Verify compressed content is smaller
  5872. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5873. }
  5874. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5875. const std::string test_content =
  5876. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5877. "3456789012345678901234567890";
  5878. std::string pre_compression_body;
  5879. std::string post_compression_body;
  5880. svr_.set_pre_compression_logger(
  5881. [&](const Request & /*req*/, const Response &res) {
  5882. pre_compression_body = res.body;
  5883. });
  5884. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5885. post_compression_body = res.body;
  5886. });
  5887. Headers headers;
  5888. headers.emplace("Accept-Encoding", "br");
  5889. auto res = cli_.Get("/compress", headers);
  5890. ASSERT_TRUE(res);
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5893. // Verify pre-compression content is uncompressed
  5894. EXPECT_EQ(test_content, pre_compression_body);
  5895. // Verify post-compression content is compressed
  5896. EXPECT_NE(test_content, post_compression_body);
  5897. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5898. }
  5899. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5900. const std::string test_content =
  5901. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5902. "3456789012345678901234567890";
  5903. std::string pre_compression_body;
  5904. std::string post_compression_body;
  5905. svr_.set_pre_compression_logger(
  5906. [&](const Request & /*req*/, const Response &res) {
  5907. pre_compression_body = res.body;
  5908. });
  5909. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5910. post_compression_body = res.body;
  5911. });
  5912. // Request without compression (use /nocompress endpoint)
  5913. Headers headers;
  5914. auto res = cli_.Get("/nocompress", headers);
  5915. ASSERT_TRUE(res);
  5916. EXPECT_EQ(StatusCode::OK_200, res->status);
  5917. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5918. // Pre-compression logger should not be called when no compression is applied
  5919. EXPECT_TRUE(
  5920. pre_compression_body.empty()); // Pre-compression logger not called
  5921. EXPECT_EQ(
  5922. test_content,
  5923. post_compression_body); // Post-compression logger captures final content
  5924. }
  5925. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5926. const std::string test_content =
  5927. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5928. "3456789012345678901234567890";
  5929. std::string pre_compression_body;
  5930. bool pre_logger_called = false;
  5931. // Set only pre-compression logger
  5932. svr_.set_pre_compression_logger(
  5933. [&](const Request & /*req*/, const Response &res) {
  5934. pre_compression_body = res.body;
  5935. pre_logger_called = true;
  5936. });
  5937. Headers headers;
  5938. headers.emplace("Accept-Encoding", "gzip");
  5939. auto res = cli_.Get("/compress", headers);
  5940. ASSERT_TRUE(res);
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5943. // Verify pre-compression logger was called
  5944. EXPECT_TRUE(pre_logger_called);
  5945. EXPECT_EQ(test_content, pre_compression_body);
  5946. }
  5947. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5948. {
  5949. // Test with Expect: 100-continue header - success case
  5950. // Server returns 100 Continue, client sends body, server returns 200 OK
  5951. Request req;
  5952. req.method = "POST";
  5953. req.path = "/post-large";
  5954. req.set_header("Expect", "100-continue");
  5955. req.body = LARGE_DATA;
  5956. Response res;
  5957. auto error = Error::Success;
  5958. cli_.set_keep_alive(true);
  5959. auto ret = cli_.send(req, res, error);
  5960. EXPECT_TRUE(ret);
  5961. EXPECT_EQ(StatusCode::OK_200, res.status);
  5962. EXPECT_EQ(LARGE_DATA, res.body);
  5963. }
  5964. {
  5965. // Test with Expect: 100-continue header - error case
  5966. // Client should not send the body when server returns an error
  5967. Request req;
  5968. req.method = "POST";
  5969. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5970. req.set_header("Expect", "100-continue");
  5971. req.body = LARGE_DATA;
  5972. Response res;
  5973. auto error = Error::Success;
  5974. auto start = std::chrono::high_resolution_clock::now();
  5975. cli_.set_keep_alive(true);
  5976. auto ret = cli_.send(req, res, error);
  5977. auto end = std::chrono::high_resolution_clock::now();
  5978. auto elapsed =
  5979. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5980. .count();
  5981. // With Expect: 100-continue, request completes successfully but with error
  5982. EXPECT_TRUE(ret);
  5983. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5984. EXPECT_EQ("close", res.get_header_value("Connection"));
  5985. EXPECT_FALSE(cli_.is_socket_open());
  5986. EXPECT_LE(elapsed, 2000);
  5987. }
  5988. {
  5989. // Send an extra GET request to ensure error recovery without hanging
  5990. Request req;
  5991. req.method = "GET";
  5992. req.path = "/hi";
  5993. auto start = std::chrono::high_resolution_clock::now();
  5994. auto res = cli_.send(req);
  5995. auto end = std::chrono::high_resolution_clock::now();
  5996. auto elapsed =
  5997. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5998. .count();
  5999. ASSERT_TRUE(res);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. EXPECT_EQ("Hello World!", res->body);
  6002. EXPECT_LE(elapsed, 500);
  6003. }
  6004. }
  6005. TEST(ZstdDecompressor, ChunkedDecompression) {
  6006. std::string data;
  6007. for (size_t i = 0; i < 32 * 1024; ++i) {
  6008. data.push_back(static_cast<char>('a' + i % 26));
  6009. }
  6010. std::string compressed_data;
  6011. {
  6012. httplib::detail::zstd_compressor compressor;
  6013. bool result = compressor.compress(
  6014. data.data(), data.size(),
  6015. /*last=*/true,
  6016. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6017. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6018. compressed_data_size);
  6019. return true;
  6020. });
  6021. ASSERT_TRUE(result);
  6022. }
  6023. std::string decompressed_data;
  6024. {
  6025. httplib::detail::zstd_decompressor decompressor;
  6026. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6027. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6028. size_t chunk_size = 130;
  6029. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6030. chunk_begin += chunk_size) {
  6031. size_t current_chunk_size =
  6032. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6033. bool result = decompressor.decompress(
  6034. compressed_data.data() + chunk_begin, current_chunk_size,
  6035. [&](const char *decompressed_data_chunk,
  6036. size_t decompressed_data_chunk_size) {
  6037. decompressed_data.insert(decompressed_data.size(),
  6038. decompressed_data_chunk,
  6039. decompressed_data_chunk_size);
  6040. return true;
  6041. });
  6042. ASSERT_TRUE(result);
  6043. }
  6044. }
  6045. ASSERT_EQ(data, decompressed_data);
  6046. }
  6047. TEST(ZstdDecompressor, Decompress) {
  6048. std::string original_text = "Compressed with ZSTD";
  6049. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6050. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6051. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6052. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6053. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6054. std::string decompressed_data;
  6055. {
  6056. httplib::detail::zstd_decompressor decompressor;
  6057. bool result = decompressor.decompress(
  6058. compressed_data.data(), compressed_data.size(),
  6059. [&](const char *decompressed_data_chunk,
  6060. size_t decompressed_data_chunk_size) {
  6061. decompressed_data.insert(decompressed_data.size(),
  6062. decompressed_data_chunk,
  6063. decompressed_data_chunk_size);
  6064. return true;
  6065. });
  6066. ASSERT_TRUE(result);
  6067. }
  6068. ASSERT_EQ(original_text, decompressed_data);
  6069. }
  6070. #endif
  6071. // Sends a raw request to a server listening at HOST:PORT.
  6072. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6073. std::string *resp = nullptr) {
  6074. auto error = Error::Success;
  6075. auto client_sock = detail::create_client_socket(
  6076. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6077. /*connection_timeout_sec=*/5, 0,
  6078. /*read_timeout_sec=*/5, 0,
  6079. /*write_timeout_sec=*/5, 0, std::string(), error);
  6080. if (client_sock == INVALID_SOCKET) { return false; }
  6081. auto ret = detail::process_client_socket(
  6082. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6083. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6084. if (req.size() !=
  6085. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6086. return false;
  6087. }
  6088. char buf[512];
  6089. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6090. while (line_reader.getline()) {
  6091. if (resp) { *resp += line_reader.ptr(); }
  6092. }
  6093. return true;
  6094. });
  6095. detail::close_socket(client_sock);
  6096. return ret;
  6097. }
  6098. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6099. Server svr;
  6100. std::string header_value;
  6101. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6102. header_value = req.get_header_value("foo");
  6103. res.set_content("ok", "text/plain");
  6104. });
  6105. thread t = thread([&] { svr.listen(HOST, PORT); });
  6106. auto se = detail::scope_exit([&] {
  6107. svr.stop();
  6108. t.join();
  6109. ASSERT_FALSE(svr.is_running());
  6110. });
  6111. svr.wait_until_ready();
  6112. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6113. // like characters are not treated the same - use vertical tab and escape.
  6114. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6115. "foo: \t \v bar \x1B\t \r\n"
  6116. "Connection: close\r\n"
  6117. "\r\n";
  6118. std::string res;
  6119. ASSERT_TRUE(send_request(5, req, &res));
  6120. EXPECT_EQ(header_value, "");
  6121. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6122. }
  6123. // Sends a raw request and verifies that there isn't a crash or exception.
  6124. static void test_raw_request(const std::string &req,
  6125. std::string *out = nullptr) {
  6126. Server svr;
  6127. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6128. res.set_content("ok", "text/plain");
  6129. });
  6130. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6131. res.set_content("ok", "text/plain");
  6132. });
  6133. svr.Get("/header_field_value_check",
  6134. [&](const Request & /*req*/, Response &res) {
  6135. res.set_content("ok", "text/plain");
  6136. });
  6137. // Server read timeout must be longer than the client read timeout for the
  6138. // bug to reproduce, probably to force the server to process a request
  6139. // without a trailing blank line.
  6140. const time_t client_read_timeout_sec = 1;
  6141. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6142. bool listen_thread_ok = false;
  6143. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6144. auto se = detail::scope_exit([&] {
  6145. svr.stop();
  6146. t.join();
  6147. ASSERT_FALSE(svr.is_running());
  6148. EXPECT_TRUE(listen_thread_ok);
  6149. });
  6150. svr.wait_until_ready();
  6151. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6152. }
  6153. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6154. // A certain header line causes an exception if the header property is parsed
  6155. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6156. test_raw_request(
  6157. "GET /hi HTTP/1.1\r\n"
  6158. " : "
  6159. " "
  6160. " ");
  6161. }
  6162. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6163. // A certain header line causes an exception if the header property *name* is
  6164. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6165. // greedy matcher and requires backtracking when there are a lot of ":"
  6166. // characters.
  6167. // This occurs with libc++ but not libstdc++.
  6168. test_raw_request(
  6169. "GET /hi HTTP/1.1\r\n"
  6170. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6171. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6172. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6173. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6174. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6175. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6176. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6177. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6178. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6179. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6180. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6181. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6182. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6183. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6184. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6185. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6186. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6187. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6188. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6189. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6190. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6191. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6192. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6193. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6194. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6195. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6196. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6197. "&&&%%%");
  6198. }
  6199. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6200. // Make sure this doesn't crash the server.
  6201. // In a previous version of the header line regex, the "\r" rendered the line
  6202. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6203. // a new position where the leading white space ended and the field value
  6204. // began.
  6205. // The crash occurs with libc++ but not libstdc++.
  6206. test_raw_request("GET /hi HTTP/1.1\r\n"
  6207. "a:" +
  6208. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6209. "\r\n"
  6210. "\r\n");
  6211. }
  6212. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6213. std::string out;
  6214. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6215. "Content-Type: text/plain\r\n"
  6216. "Transfer-Encoding: chunked\r\n"
  6217. "\r\n"
  6218. "nothex\r\n",
  6219. &out);
  6220. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6221. }
  6222. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6223. std::string out;
  6224. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6225. "Content-Type: text/plain\r\n"
  6226. "Transfer-Encoding: chunked\r\n"
  6227. "\r\n"
  6228. "3\r\n"
  6229. "xyz\r\n"
  6230. "NaN\r\n",
  6231. &out);
  6232. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6233. }
  6234. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6235. std::string out;
  6236. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6237. "Content-Type: text/plain\r\n"
  6238. "Transfer-Encoding: chunked\r\n"
  6239. "\r\n"
  6240. // Length is too large for 64 bits.
  6241. "1ffffffffffffffff\r\n"
  6242. "xyz\r\n",
  6243. &out);
  6244. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6245. }
  6246. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6247. test_raw_request("GET /hi HTTP/1.1\r\n"
  6248. "Content-Type: text/plain\r\n\r");
  6249. }
  6250. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6251. std::string out;
  6252. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6253. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6254. }
  6255. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6256. Server svr;
  6257. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6258. EXPECT_TRUE(!req.remote_addr.empty());
  6259. });
  6260. thread t = thread([&] { svr.listen(HOST, PORT); });
  6261. auto se = detail::scope_exit([&] {
  6262. svr.stop();
  6263. t.join();
  6264. ASSERT_FALSE(svr.is_running());
  6265. });
  6266. svr.wait_until_ready();
  6267. // Send an invalid request line to trigger Bad Request
  6268. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6269. std::string out;
  6270. ASSERT_TRUE(send_request(5, bad_req, &out));
  6271. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6272. }
  6273. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6274. std::string out;
  6275. std::string request(
  6276. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6277. test_raw_request(request, &out);
  6278. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6279. }
  6280. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6281. std::string out;
  6282. std::string request(
  6283. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6284. test_raw_request(request, &out);
  6285. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6286. }
  6287. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6288. std::string out;
  6289. std::string request(
  6290. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6291. test_raw_request(request, &out);
  6292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6293. }
  6294. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6295. std::string out;
  6296. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6297. "Test: \r\n\r\n",
  6298. &out);
  6299. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6300. }
  6301. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6302. Server svr;
  6303. std::string x_custom;
  6304. std::string cookie;
  6305. std::string xff;
  6306. std::string x_unicode;
  6307. std::string x_iis;
  6308. svr.Get("/check", [&](const Request &req, Response &res) {
  6309. x_custom = req.get_header_value("X-Custom");
  6310. cookie = req.get_header_value("Cookie");
  6311. xff = req.get_header_value("X-Forwarded-For");
  6312. x_unicode = req.get_header_value("X-Unicode");
  6313. x_iis = req.get_header_value("X-IIS");
  6314. res.set_content("ok", "text/plain");
  6315. });
  6316. thread t = thread([&] { svr.listen(HOST, PORT); });
  6317. auto se = detail::scope_exit([&] {
  6318. svr.stop();
  6319. t.join();
  6320. ASSERT_FALSE(svr.is_running());
  6321. });
  6322. svr.wait_until_ready();
  6323. const std::string req = "GET /check HTTP/1.1\r\n"
  6324. "Host: localhost\r\n"
  6325. "X-Custom: a%0D%0AInjected: b\r\n"
  6326. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6327. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6328. "X-Unicode: %E3%81%82\r\n"
  6329. "X-IIS: %u00E9\r\n"
  6330. "Connection: close\r\n"
  6331. "\r\n";
  6332. std::string res;
  6333. ASSERT_TRUE(send_request(5, req, &res));
  6334. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6335. // Every value must be returned verbatim (wire form), with no decoding.
  6336. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6337. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6338. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6339. EXPECT_EQ("%E3%81%82", x_unicode);
  6340. EXPECT_EQ("%u00E9", x_iis);
  6341. }
  6342. // Applications that previously relied on automatic percent-decoding can
  6343. // reproduce the old behavior by explicitly calling decode_path_component()
  6344. // or, for RFC 3986 conformance, decode_uri_component().
  6345. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6346. Server svr;
  6347. std::string decoded;
  6348. svr.Get("/check", [&](const Request &req, Response &res) {
  6349. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6350. res.set_content("ok", "text/plain");
  6351. });
  6352. thread t = thread([&] { svr.listen(HOST, PORT); });
  6353. auto se = detail::scope_exit([&] {
  6354. svr.stop();
  6355. t.join();
  6356. ASSERT_FALSE(svr.is_running());
  6357. });
  6358. svr.wait_until_ready();
  6359. const std::string req = "GET /check HTTP/1.1\r\n"
  6360. "Host: localhost\r\n"
  6361. "X-Custom: hello%20world\r\n"
  6362. "Connection: close\r\n"
  6363. "\r\n";
  6364. std::string res;
  6365. ASSERT_TRUE(send_request(5, req, &res));
  6366. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6367. EXPECT_EQ("hello world", decoded);
  6368. }
  6369. // Regression test for #2033. Browsers send Referer values that include
  6370. // percent-encoded characters such as %0A inside the URL. Decoding the
  6371. // header value would either trip the post-decode CR/LF/NUL guard (the
  6372. // original bug, returning 400) or, after that guard was relaxed, silently
  6373. // store a literal LF — both unacceptable. The wire form must round-trip.
  6374. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6375. Server svr;
  6376. std::string referer;
  6377. svr.Get("/check", [&](const Request &req, Response &res) {
  6378. referer = req.get_header_value("Referer");
  6379. res.set_content("ok", "text/plain");
  6380. });
  6381. thread t = thread([&] { svr.listen(HOST, PORT); });
  6382. auto se = detail::scope_exit([&] {
  6383. svr.stop();
  6384. t.join();
  6385. ASSERT_FALSE(svr.is_running());
  6386. });
  6387. svr.wait_until_ready();
  6388. const std::string req = "GET /check HTTP/1.1\r\n"
  6389. "Host: localhost\r\n"
  6390. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6391. "Connection: close\r\n"
  6392. "\r\n";
  6393. std::string res;
  6394. ASSERT_TRUE(send_request(5, req, &res));
  6395. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6396. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6397. }
  6398. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6399. Server svr;
  6400. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6401. res.set_header("Cache-Control", "no-cache");
  6402. res.set_chunked_content_provider(
  6403. "text/event-stream", [](size_t offset, DataSink &sink) {
  6404. std::string s = "data:";
  6405. s += std::to_string(offset);
  6406. s += "\n\n";
  6407. auto ret = sink.write(s.data(), s.size());
  6408. EXPECT_TRUE(ret);
  6409. std::this_thread::sleep_for(std::chrono::seconds(1));
  6410. return true;
  6411. });
  6412. });
  6413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6414. svr.wait_until_ready();
  6415. Client client(HOST, PORT);
  6416. const Headers headers = {{"Accept", "text/event-stream"}};
  6417. auto get_thread = std::thread([&client, &headers]() {
  6418. auto res = client.Get(
  6419. "/events", headers,
  6420. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6421. });
  6422. auto se = detail::scope_exit([&] {
  6423. svr.stop();
  6424. get_thread.join();
  6425. listen_thread.join();
  6426. ASSERT_FALSE(svr.is_running());
  6427. });
  6428. // Give GET time to get a few messages.
  6429. std::this_thread::sleep_for(std::chrono::seconds(2));
  6430. }
  6431. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6432. httplib::Server svr;
  6433. svr.Post("/hi",
  6434. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6435. res.status = StatusCode::OK_200;
  6436. });
  6437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6438. svr.wait_until_ready();
  6439. Client cli(HOST, PORT);
  6440. auto res = cli.Post("/hi", "data", "text/plain");
  6441. ASSERT_TRUE(res);
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. svr.stop();
  6444. thread.join();
  6445. ASSERT_FALSE(svr.is_running());
  6446. res = cli.Post("/hi", "data", "text/plain");
  6447. ASSERT_FALSE(res);
  6448. }
  6449. TEST(ServerStopTest, ListenFailure) {
  6450. Server svr;
  6451. auto t = thread([&]() {
  6452. auto ret = svr.listen("????", PORT);
  6453. EXPECT_FALSE(ret);
  6454. });
  6455. svr.wait_until_ready();
  6456. svr.stop();
  6457. t.join();
  6458. }
  6459. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6460. TEST(ServerStopTest, Decommision) {
  6461. Server svr;
  6462. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6463. for (int i = 0; i < 4; i++) {
  6464. auto is_even = !(i % 2);
  6465. std::thread t{[&] {
  6466. try {
  6467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6468. if (is_even) {
  6469. throw std::runtime_error("Some thing that happens to go wrong.");
  6470. }
  6471. svr.listen(HOST, PORT);
  6472. } catch (...) { svr.decommission(); }
  6473. }};
  6474. svr.wait_until_ready();
  6475. // Server is up
  6476. {
  6477. Client cli(HOST, PORT);
  6478. auto res = cli.Get("/hi");
  6479. if (is_even) {
  6480. EXPECT_FALSE(res);
  6481. } else {
  6482. EXPECT_TRUE(res);
  6483. EXPECT_EQ("hi...", res->body);
  6484. }
  6485. }
  6486. svr.stop();
  6487. t.join();
  6488. // Server is down...
  6489. {
  6490. Client cli(HOST, PORT);
  6491. auto res = cli.Get("/hi");
  6492. EXPECT_FALSE(res);
  6493. }
  6494. }
  6495. }
  6496. #endif
  6497. // Helper function for string body upload progress tests
  6498. template <typename SetupHandler, typename ClientCall>
  6499. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6500. ClientCall &&client_call,
  6501. const string &body) {
  6502. Server svr;
  6503. setup_handler(svr);
  6504. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6505. auto se = detail::scope_exit([&] {
  6506. svr.stop();
  6507. t.join();
  6508. });
  6509. svr.wait_until_ready();
  6510. Client cli(HOST, PORT);
  6511. vector<uint64_t> progress_values;
  6512. bool progress_called = false;
  6513. auto res =
  6514. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6515. progress_values.push_back(current);
  6516. progress_called = true;
  6517. return true;
  6518. });
  6519. ASSERT_TRUE(res);
  6520. EXPECT_EQ(200, res->status);
  6521. EXPECT_TRUE(progress_called);
  6522. }
  6523. TEST(UploadProgressTest, PostStringBodyBasic) {
  6524. TestStringBodyUploadProgress(
  6525. [](Server &svr) {
  6526. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6527. res.set_content("received", "text/plain");
  6528. });
  6529. },
  6530. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6531. return cli.Post("/test", body, "text/plain", progress_callback);
  6532. },
  6533. "test data for upload progress");
  6534. }
  6535. TEST(UploadProgressTest, PutStringBodyBasic) {
  6536. TestStringBodyUploadProgress(
  6537. [](Server &svr) {
  6538. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6539. res.set_content("put received", "text/plain");
  6540. });
  6541. },
  6542. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6543. return cli.Put("/test", body, "text/plain", progress_callback);
  6544. },
  6545. "put test data for upload progress");
  6546. }
  6547. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6548. TestStringBodyUploadProgress(
  6549. [](Server &svr) {
  6550. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6551. res.set_content("patch received", "text/plain");
  6552. });
  6553. },
  6554. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6555. return cli.Patch("/test", body, "text/plain", progress_callback);
  6556. },
  6557. "patch test data for upload progress");
  6558. }
  6559. // Helper function for content provider upload progress tests
  6560. template <typename SetupHandler, typename ClientCall>
  6561. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6562. ClientCall &&client_call) {
  6563. Server svr;
  6564. setup_handler(svr);
  6565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6566. auto se = detail::scope_exit([&] {
  6567. svr.stop();
  6568. t.join();
  6569. });
  6570. svr.wait_until_ready();
  6571. Client cli(HOST, PORT);
  6572. vector<uint64_t> progress_values;
  6573. auto res =
  6574. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6575. progress_values.push_back(current);
  6576. return true;
  6577. });
  6578. ASSERT_TRUE(res);
  6579. EXPECT_EQ(200, res->status);
  6580. EXPECT_FALSE(progress_values.empty());
  6581. }
  6582. TEST(UploadProgressTest, PostContentProviderProgress) {
  6583. TestContentProviderUploadProgress(
  6584. [](Server &svr) {
  6585. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6586. res.set_content("provider received", "text/plain");
  6587. });
  6588. },
  6589. [](Client &cli, UploadProgress progress_callback) {
  6590. return cli.Post(
  6591. "/test", 10,
  6592. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6593. sink.os << "test data";
  6594. return true;
  6595. },
  6596. "text/plain", progress_callback);
  6597. });
  6598. }
  6599. // Helper function for multipart upload progress tests
  6600. template <typename SetupHandler, typename ClientCall>
  6601. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6602. ClientCall &&client_call,
  6603. const string &endpoint) {
  6604. Server svr;
  6605. setup_handler(svr);
  6606. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6607. auto se = detail::scope_exit([&] {
  6608. svr.stop();
  6609. t.join();
  6610. });
  6611. svr.wait_until_ready();
  6612. Client cli(HOST, PORT);
  6613. vector<uint64_t> progress_values;
  6614. UploadFormDataItems items = {
  6615. {"field1", "value1", "", ""},
  6616. {"field2", "longer value for progress tracking test", "", ""},
  6617. {"file1", "file content data for upload progress", "test.txt",
  6618. "text/plain"}};
  6619. auto res = client_call(cli, endpoint, items,
  6620. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6621. progress_values.push_back(current);
  6622. return true;
  6623. });
  6624. ASSERT_TRUE(res);
  6625. EXPECT_EQ(200, res->status);
  6626. EXPECT_FALSE(progress_values.empty());
  6627. }
  6628. TEST(UploadProgressTest, PostMultipartProgress) {
  6629. TestMultipartUploadProgress(
  6630. [](Server &svr) {
  6631. svr.Post("/multipart", [](const Request &req, Response &res) {
  6632. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6633. res.set_content("multipart received", "text/plain");
  6634. });
  6635. },
  6636. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6637. UploadProgress progress_callback) {
  6638. return cli.Post(endpoint, items, progress_callback);
  6639. },
  6640. "/multipart");
  6641. }
  6642. // Helper function for basic download progress tests
  6643. template <typename SetupHandler, typename ClientCall>
  6644. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6645. ClientCall &&client_call, const string &endpoint,
  6646. size_t expected_content_size) {
  6647. Server svr;
  6648. setup_handler(svr);
  6649. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6650. auto se = detail::scope_exit([&] {
  6651. svr.stop();
  6652. t.join();
  6653. });
  6654. svr.wait_until_ready();
  6655. Client cli(HOST, PORT);
  6656. vector<uint64_t> progress_values;
  6657. auto res = client_call(cli, endpoint,
  6658. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6659. progress_values.push_back(current);
  6660. return true;
  6661. });
  6662. ASSERT_TRUE(res);
  6663. EXPECT_EQ(200, res->status);
  6664. EXPECT_FALSE(progress_values.empty());
  6665. EXPECT_EQ(expected_content_size, res->body.size());
  6666. }
  6667. TEST(DownloadProgressTest, GetBasic) {
  6668. TestBasicDownloadProgress(
  6669. [](Server &svr) {
  6670. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6671. string content(1000, 'D');
  6672. res.set_content(content, "text/plain");
  6673. });
  6674. },
  6675. [](Client &cli, const string &endpoint,
  6676. DownloadProgress progress_callback) {
  6677. return cli.Get(endpoint, progress_callback);
  6678. },
  6679. "/download", 1000u);
  6680. }
  6681. // Helper function for content receiver download progress tests
  6682. template <typename SetupHandler, typename ClientCall>
  6683. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6684. ClientCall &&client_call,
  6685. const string &endpoint,
  6686. size_t expected_content_size) {
  6687. Server svr;
  6688. setup_handler(svr);
  6689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6690. auto se = detail::scope_exit([&] {
  6691. svr.stop();
  6692. t.join();
  6693. });
  6694. svr.wait_until_ready();
  6695. Client cli(HOST, PORT);
  6696. vector<uint64_t> progress_values;
  6697. string received_body;
  6698. auto res = client_call(
  6699. cli, endpoint,
  6700. [&](const char *data, size_t data_length) -> bool {
  6701. received_body.append(data, data_length);
  6702. return true;
  6703. },
  6704. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6705. progress_values.push_back(current);
  6706. return true;
  6707. });
  6708. ASSERT_TRUE(res);
  6709. EXPECT_EQ(200, res->status);
  6710. EXPECT_FALSE(progress_values.empty());
  6711. EXPECT_EQ(expected_content_size, received_body.size());
  6712. EXPECT_TRUE(res->body.empty());
  6713. }
  6714. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6715. TestContentReceiverDownloadProgress(
  6716. [](Server &svr) {
  6717. svr.Get("/download-receiver",
  6718. [](const Request & /*req*/, Response &res) {
  6719. string content(2000, 'R');
  6720. res.set_content(content, "text/plain");
  6721. });
  6722. },
  6723. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6724. DownloadProgress progress_callback) {
  6725. return cli.Get(endpoint, content_receiver, progress_callback);
  6726. },
  6727. "/download-receiver", 2000u);
  6728. }
  6729. TEST(StreamingTest, NoContentLengthStreaming) {
  6730. Server svr;
  6731. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6732. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6733. if (offset < 6) {
  6734. sink.os << (offset < 3 ? "a" : "b");
  6735. } else {
  6736. sink.done();
  6737. }
  6738. return true;
  6739. });
  6740. });
  6741. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6742. auto listen_se = detail::scope_exit([&] {
  6743. svr.stop();
  6744. listen_thread.join();
  6745. ASSERT_FALSE(svr.is_running());
  6746. });
  6747. svr.wait_until_ready();
  6748. Client client(HOST, PORT);
  6749. auto get_thread = std::thread([&client]() {
  6750. std::string s;
  6751. auto res =
  6752. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6753. s += std::string(data, len);
  6754. return true;
  6755. });
  6756. ASSERT_TRUE(res);
  6757. EXPECT_EQ(StatusCode::OK_200, res->status);
  6758. EXPECT_EQ("aaabbb", s);
  6759. });
  6760. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6761. // Give GET time to get a few messages.
  6762. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6763. }
  6764. TEST(MountTest, Unmount) {
  6765. Server svr;
  6766. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6767. auto se = detail::scope_exit([&] {
  6768. svr.stop();
  6769. listen_thread.join();
  6770. ASSERT_FALSE(svr.is_running());
  6771. });
  6772. svr.wait_until_ready();
  6773. Client cli("localhost", PORT);
  6774. svr.set_mount_point("/mount2", "./www2");
  6775. auto res = cli.Get("/");
  6776. ASSERT_TRUE(res);
  6777. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6778. res = cli.Get("/mount2/dir/test.html");
  6779. ASSERT_TRUE(res);
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. svr.set_mount_point("/", "./www");
  6782. res = cli.Get("/dir/");
  6783. ASSERT_TRUE(res);
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. svr.remove_mount_point("/");
  6786. res = cli.Get("/dir/");
  6787. ASSERT_TRUE(res);
  6788. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6789. svr.remove_mount_point("/mount2");
  6790. res = cli.Get("/mount2/dir/test.html");
  6791. ASSERT_TRUE(res);
  6792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6793. }
  6794. TEST(MountTest, Redicect) {
  6795. Server svr;
  6796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6797. auto se = detail::scope_exit([&] {
  6798. svr.stop();
  6799. listen_thread.join();
  6800. ASSERT_FALSE(svr.is_running());
  6801. });
  6802. svr.set_mount_point("/", "./www");
  6803. svr.wait_until_ready();
  6804. Client cli("localhost", PORT);
  6805. auto res = cli.Get("/dir/");
  6806. ASSERT_TRUE(res);
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. res = cli.Get("/dir");
  6809. ASSERT_TRUE(res);
  6810. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6811. res = cli.Get("/file");
  6812. ASSERT_TRUE(res);
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. res = cli.Get("/file/");
  6815. ASSERT_TRUE(res);
  6816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6817. cli.set_follow_location(true);
  6818. res = cli.Get("/dir");
  6819. ASSERT_TRUE(res);
  6820. EXPECT_EQ(StatusCode::OK_200, res->status);
  6821. }
  6822. TEST(MountTest, MultibytesPathName) {
  6823. Server svr;
  6824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. listen_thread.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. });
  6830. svr.set_mount_point("/", "./www");
  6831. svr.wait_until_ready();
  6832. Client cli("localhost", PORT);
  6833. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6834. ASSERT_TRUE(res);
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6837. }
  6838. #ifdef _WIN32
  6839. // Issue #2435: mmap::open() must succeed even when another handle holds
  6840. // the file open for writing (e.g. an active log file).
  6841. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6842. const char *path = "mmap_concurrent_writer_test.txt";
  6843. const char *content = "hello";
  6844. {
  6845. std::ofstream f(path, std::ios::binary);
  6846. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6847. }
  6848. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6849. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6850. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6851. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6852. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6853. detail::mmap m(path);
  6854. ASSERT_TRUE(m.is_open());
  6855. EXPECT_EQ(strlen(content), m.size());
  6856. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6857. }
  6858. #endif
  6859. TEST(KeepAliveTest, ReadTimeout) {
  6860. Server svr;
  6861. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6862. std::this_thread::sleep_for(std::chrono::seconds(2));
  6863. res.set_content("a", "text/plain");
  6864. });
  6865. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6866. res.set_content("b", "text/plain");
  6867. });
  6868. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6869. auto se = detail::scope_exit([&] {
  6870. svr.stop();
  6871. listen_thread.join();
  6872. ASSERT_FALSE(svr.is_running());
  6873. });
  6874. svr.wait_until_ready();
  6875. Client cli("localhost", PORT);
  6876. cli.set_keep_alive(true);
  6877. cli.set_read_timeout(std::chrono::seconds(1));
  6878. auto resa = cli.Get("/a");
  6879. ASSERT_FALSE(resa);
  6880. EXPECT_EQ(Error::Read, resa.error());
  6881. auto resb = cli.Get("/b");
  6882. ASSERT_TRUE(resb);
  6883. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6884. EXPECT_EQ("b", resb->body);
  6885. }
  6886. TEST(KeepAliveTest, MaxCount) {
  6887. size_t keep_alive_max_count = 3;
  6888. Server svr;
  6889. svr.set_keep_alive_max_count(keep_alive_max_count);
  6890. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6891. res.set_content("Hello World!", "text/plain");
  6892. });
  6893. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6894. auto se = detail::scope_exit([&] {
  6895. svr.stop();
  6896. listen_thread.join();
  6897. ASSERT_FALSE(svr.is_running());
  6898. });
  6899. svr.wait_until_ready();
  6900. Client cli(HOST, PORT);
  6901. cli.set_keep_alive(true);
  6902. for (size_t i = 0; i < 5; i++) {
  6903. auto result = cli.Get("/hi");
  6904. ASSERT_TRUE(result);
  6905. EXPECT_EQ(StatusCode::OK_200, result->status);
  6906. if (i == keep_alive_max_count - 1) {
  6907. EXPECT_EQ("close", result->get_header_value("Connection"));
  6908. } else {
  6909. EXPECT_FALSE(result->has_header("Connection"));
  6910. }
  6911. }
  6912. }
  6913. TEST(KeepAliveTest, Issue1041) {
  6914. Server svr;
  6915. svr.set_keep_alive_timeout(3);
  6916. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6917. res.set_content("Hello World!", "text/plain");
  6918. });
  6919. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6920. auto se = detail::scope_exit([&] {
  6921. svr.stop();
  6922. listen_thread.join();
  6923. ASSERT_FALSE(svr.is_running());
  6924. });
  6925. svr.wait_until_ready();
  6926. Client cli(HOST, PORT);
  6927. cli.set_keep_alive(true);
  6928. auto result = cli.Get("/hi");
  6929. ASSERT_TRUE(result);
  6930. EXPECT_EQ(StatusCode::OK_200, result->status);
  6931. std::this_thread::sleep_for(std::chrono::seconds(5));
  6932. result = cli.Get("/hi");
  6933. ASSERT_TRUE(result);
  6934. EXPECT_EQ(StatusCode::OK_200, result->status);
  6935. }
  6936. TEST(KeepAliveTest, Issue1959) {
  6937. Server svr;
  6938. svr.set_keep_alive_timeout(5);
  6939. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6940. res.set_content("a", "text/plain");
  6941. });
  6942. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6943. auto se = detail::scope_exit([&] {
  6944. if (!svr.is_running()) return;
  6945. svr.stop();
  6946. listen_thread.join();
  6947. ASSERT_FALSE(svr.is_running());
  6948. });
  6949. svr.wait_until_ready();
  6950. Client cli("localhost", PORT);
  6951. cli.set_keep_alive(true);
  6952. using namespace std::chrono;
  6953. auto start = steady_clock::now();
  6954. cli.Get("/a");
  6955. svr.stop();
  6956. listen_thread.join();
  6957. auto end = steady_clock::now();
  6958. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6959. EXPECT_LT(elapsed, 5000);
  6960. }
  6961. #ifdef CPPHTTPLIB_SSL_ENABLED
  6962. TEST(KeepAliveTest, SSLClientReconnection) {
  6963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6964. ASSERT_TRUE(svr.is_valid());
  6965. svr.set_keep_alive_timeout(1);
  6966. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6967. res.set_content("Hello World!", "text/plain");
  6968. });
  6969. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6970. auto se = detail::scope_exit([&] {
  6971. svr.stop();
  6972. listen_thread.join();
  6973. ASSERT_FALSE(svr.is_running());
  6974. });
  6975. svr.wait_until_ready();
  6976. SSLClient cli(HOST, PORT);
  6977. cli.enable_server_certificate_verification(false);
  6978. cli.set_keep_alive(true);
  6979. auto result = cli.Get("/hi");
  6980. ASSERT_TRUE(result);
  6981. EXPECT_EQ(StatusCode::OK_200, result->status);
  6982. result = cli.Get("/hi");
  6983. ASSERT_TRUE(result);
  6984. EXPECT_EQ(StatusCode::OK_200, result->status);
  6985. std::this_thread::sleep_for(std::chrono::seconds(2));
  6986. // Recoonect
  6987. result = cli.Get("/hi");
  6988. ASSERT_TRUE(result);
  6989. EXPECT_EQ(StatusCode::OK_200, result->status);
  6990. result = cli.Get("/hi");
  6991. ASSERT_TRUE(result);
  6992. EXPECT_EQ(StatusCode::OK_200, result->status);
  6993. }
  6994. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6996. ASSERT_TRUE(svr.is_valid());
  6997. svr.set_keep_alive_timeout(1);
  6998. std::string content = "reconnect";
  6999. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7000. res.set_content("Hello World!", "text/plain");
  7001. });
  7002. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7003. auto se = detail::scope_exit([&] {
  7004. svr.stop();
  7005. listen_thread.join();
  7006. ASSERT_FALSE(svr.is_running());
  7007. });
  7008. svr.wait_until_ready();
  7009. SSLClient cli(HOST, PORT);
  7010. cli.enable_server_certificate_verification(false);
  7011. cli.set_keep_alive(true);
  7012. auto result = cli.Post(
  7013. "/hi", content.size(),
  7014. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7015. sink.write(content.c_str(), content.size());
  7016. return true;
  7017. },
  7018. "text/plain");
  7019. ASSERT_TRUE(result);
  7020. EXPECT_EQ(200, result->status);
  7021. std::this_thread::sleep_for(std::chrono::seconds(2));
  7022. // Recoonect
  7023. result = cli.Post(
  7024. "/hi", content.size(),
  7025. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7026. sink.write(content.c_str(), content.size());
  7027. return true;
  7028. },
  7029. "text/plain");
  7030. ASSERT_TRUE(result);
  7031. EXPECT_EQ(200, result->status);
  7032. result = cli.Post(
  7033. "/hi", content.size(),
  7034. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7035. sink.write(content.c_str(), content.size());
  7036. return true;
  7037. },
  7038. "text/plain");
  7039. ASSERT_TRUE(result);
  7040. EXPECT_EQ(200, result->status);
  7041. }
  7042. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7043. using namespace httplib::tls;
  7044. {
  7045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7046. ASSERT_TRUE(svr.is_valid());
  7047. svr.Get("/sni", [&](const Request &req, Response &res) {
  7048. std::string expected = req.sni();
  7049. EXPECT_EQ(expected, req.get_param_value("expected"));
  7050. res.set_content("ok", "text/plain");
  7051. });
  7052. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7053. auto se = detail::scope_exit([&] {
  7054. svr.stop();
  7055. listen_thread.join();
  7056. ASSERT_FALSE(svr.is_running());
  7057. });
  7058. svr.wait_until_ready();
  7059. {
  7060. SSLClient cli("localhost", PORT);
  7061. cli.enable_server_certificate_verification(false);
  7062. auto res = cli.Get("/sni?expected=localhost");
  7063. ASSERT_TRUE(res);
  7064. }
  7065. {
  7066. SSLClient cli("::1", PORT);
  7067. cli.enable_server_certificate_verification(false);
  7068. auto res = cli.Get("/sni?expected=");
  7069. // NOTE: This may fail if the server is listening on IPv4 only
  7070. // (e.g., when localhost resolves to 127.0.0.1 only)
  7071. if (res) {
  7072. EXPECT_EQ(StatusCode::OK_200, res->status);
  7073. } else {
  7074. EXPECT_EQ(Error::Connection, res.error());
  7075. }
  7076. }
  7077. }
  7078. }
  7079. #endif
  7080. TEST(ClientProblemDetectionTest, ContentProvider) {
  7081. Server svr;
  7082. size_t content_length = 1024 * 1024;
  7083. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7084. res.set_content_provider(
  7085. content_length, "text/plain",
  7086. [&](size_t offset, size_t length, DataSink &sink) {
  7087. auto out_len = std::min(length, static_cast<size_t>(1024));
  7088. std::string out(out_len, '@');
  7089. sink.write(out.data(), out_len);
  7090. return offset < 4096;
  7091. },
  7092. [](bool success) { ASSERT_FALSE(success); });
  7093. });
  7094. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7095. res.set_content_provider(
  7096. 0, "text/plain",
  7097. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7098. EXPECT_TRUE(false);
  7099. return true;
  7100. },
  7101. [](bool success) { ASSERT_FALSE(success); });
  7102. });
  7103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7104. auto se = detail::scope_exit([&] {
  7105. svr.stop();
  7106. listen_thread.join();
  7107. ASSERT_FALSE(svr.is_running());
  7108. });
  7109. svr.wait_until_ready();
  7110. Client cli("localhost", PORT);
  7111. {
  7112. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7113. size_t /*data_length*/) { return false; });
  7114. ASSERT_FALSE(res);
  7115. }
  7116. {
  7117. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7118. size_t /*data_length*/) { return false; });
  7119. ASSERT_TRUE(res);
  7120. }
  7121. }
  7122. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7123. Server svr;
  7124. svr.set_error_handler([](Request const &, Response &res) -> void {
  7125. res.set_chunked_content_provider(
  7126. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7127. sink.os << "hello";
  7128. sink.os << "world";
  7129. sink.done();
  7130. return true;
  7131. });
  7132. });
  7133. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7134. auto se = detail::scope_exit([&] {
  7135. svr.stop();
  7136. listen_thread.join();
  7137. ASSERT_FALSE(svr.is_running());
  7138. });
  7139. svr.wait_until_ready();
  7140. Client cli("localhost", PORT);
  7141. auto res = cli.Get("/");
  7142. ASSERT_TRUE(res);
  7143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7144. EXPECT_EQ("helloworld", res->body);
  7145. }
  7146. TEST(LongPollingTest, ClientCloseDetection) {
  7147. Server svr;
  7148. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7149. res.set_chunked_content_provider(
  7150. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7151. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7152. sink.os << "hello";
  7153. auto count = 10;
  7154. while (count > 0 && sink.is_writable()) {
  7155. this_thread::sleep_for(chrono::milliseconds(10));
  7156. count--;
  7157. }
  7158. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7159. return true;
  7160. });
  7161. });
  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. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7171. EXPECT_EQ("hello", string(data, data_length));
  7172. return false; // close the socket immediately.
  7173. });
  7174. ASSERT_FALSE(res);
  7175. }
  7176. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7177. Server svr;
  7178. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7179. res.set_chunked_content_provider(
  7180. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7181. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7182. sink.os << "hello";
  7183. EXPECT_TRUE(sink.os.good());
  7184. // Wait for the client to close the connection
  7185. auto count = 10;
  7186. while (count > 0 && sink.is_writable()) {
  7187. this_thread::sleep_for(chrono::milliseconds(10));
  7188. count--;
  7189. }
  7190. // After client disconnect, write repeatedly until the socket
  7191. // write actually fails (small writes may be absorbed by the
  7192. // kernel buffer)
  7193. std::string chunk(1024, 'x');
  7194. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7195. sink.os << chunk;
  7196. }
  7197. EXPECT_TRUE(sink.os.fail());
  7198. return true;
  7199. });
  7200. });
  7201. auto port = svr.bind_to_any_port("localhost");
  7202. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7203. auto se = detail::scope_exit([&] {
  7204. svr.stop();
  7205. listen_thread.join();
  7206. ASSERT_FALSE(svr.is_running());
  7207. });
  7208. svr.wait_until_ready();
  7209. Client cli("localhost", port);
  7210. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7211. EXPECT_EQ("hello", string(data, data_length));
  7212. return false; // close the socket immediately.
  7213. });
  7214. ASSERT_FALSE(res);
  7215. }
  7216. TEST(GetWithParametersTest, GetWithParameters) {
  7217. Server svr;
  7218. svr.Get("/", [&](const Request &req, Response &) {
  7219. EXPECT_EQ("world", req.get_param_value("hello"));
  7220. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7221. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7222. });
  7223. svr.Get("/params", [&](const Request &req, Response &) {
  7224. EXPECT_EQ("world", req.get_param_value("hello"));
  7225. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7226. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7227. });
  7228. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7229. EXPECT_EQ("resource-id", req.matches[1]);
  7230. EXPECT_EQ("foo", req.get_param_value("param1"));
  7231. EXPECT_EQ("bar", req.get_param_value("param2"));
  7232. });
  7233. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7234. EXPECT_EQ("user-id", req.path_params.at("id"));
  7235. EXPECT_EQ("foo", req.get_param_value("param1"));
  7236. EXPECT_EQ("bar", req.get_param_value("param2"));
  7237. });
  7238. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7239. auto se = detail::scope_exit([&] {
  7240. svr.stop();
  7241. listen_thread.join();
  7242. ASSERT_FALSE(svr.is_running());
  7243. });
  7244. svr.wait_until_ready();
  7245. {
  7246. Client cli(HOST, PORT);
  7247. Params params;
  7248. params.emplace("hello", "world");
  7249. params.emplace("hello2", "world2");
  7250. params.emplace("hello3", "world3");
  7251. auto res = cli.Get("/", params, Headers{});
  7252. ASSERT_TRUE(res);
  7253. EXPECT_EQ(StatusCode::OK_200, res->status);
  7254. }
  7255. {
  7256. Client cli(HOST, PORT);
  7257. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7258. ASSERT_TRUE(res);
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. }
  7261. {
  7262. Client cli(HOST, PORT);
  7263. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7264. ASSERT_TRUE(res);
  7265. EXPECT_EQ(StatusCode::OK_200, res->status);
  7266. }
  7267. {
  7268. Client cli(HOST, PORT);
  7269. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7270. ASSERT_TRUE(res);
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. }
  7273. }
  7274. TEST(GetWithParametersTest, GetWithParameters2) {
  7275. Server svr;
  7276. svr.Get("/", [&](const Request &req, Response &res) {
  7277. auto text = req.get_param_value("hello");
  7278. res.set_content(text, "text/plain");
  7279. });
  7280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7281. auto se = detail::scope_exit([&] {
  7282. svr.stop();
  7283. listen_thread.join();
  7284. ASSERT_FALSE(svr.is_running());
  7285. });
  7286. svr.wait_until_ready();
  7287. Client cli("localhost", PORT);
  7288. Params params;
  7289. params.emplace("hello", "world");
  7290. std::string body;
  7291. auto res = cli.Get("/", params, Headers{},
  7292. [&](const char *data, size_t data_length) {
  7293. body.append(data, data_length);
  7294. return true;
  7295. });
  7296. ASSERT_TRUE(res);
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ("world", body);
  7299. }
  7300. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7301. auto host = "httpbingo.org";
  7302. auto path = std::string{"/range/32"};
  7303. #ifdef CPPHTTPLIB_SSL_ENABLED
  7304. SSLClient cli(host);
  7305. #else
  7306. Client cli(host);
  7307. #endif
  7308. cli.set_default_headers({make_range_header({{1, 10}})});
  7309. cli.set_connection_timeout(5);
  7310. {
  7311. auto res = cli.Get(path);
  7312. ASSERT_TRUE(res);
  7313. EXPECT_EQ("bcdefghijk", res->body);
  7314. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7315. }
  7316. {
  7317. auto res = cli.Get(path);
  7318. ASSERT_TRUE(res);
  7319. EXPECT_EQ("bcdefghijk", res->body);
  7320. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7321. }
  7322. }
  7323. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7324. Server svr;
  7325. svr.set_default_headers({{"Hello", "World"}});
  7326. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7327. res.set_content("ok", "text/plain");
  7328. });
  7329. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7330. auto se = detail::scope_exit([&] {
  7331. svr.stop();
  7332. listen_thread.join();
  7333. ASSERT_FALSE(svr.is_running());
  7334. });
  7335. svr.wait_until_ready();
  7336. Client cli("localhost", PORT);
  7337. auto res = cli.Get("/");
  7338. ASSERT_TRUE(res);
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. EXPECT_EQ("ok", res->body);
  7341. EXPECT_EQ("World", res->get_header_value("Hello"));
  7342. }
  7343. #ifdef CPPHTTPLIB_SSL_ENABLED
  7344. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7345. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7346. ASSERT_TRUE(svr.is_valid());
  7347. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7348. std::this_thread::sleep_for(std::chrono::seconds(2));
  7349. res.set_content("a", "text/plain");
  7350. });
  7351. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7352. res.set_content("b", "text/plain");
  7353. });
  7354. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7355. auto se = detail::scope_exit([&] {
  7356. svr.stop();
  7357. listen_thread.join();
  7358. ASSERT_FALSE(svr.is_running());
  7359. });
  7360. svr.wait_until_ready();
  7361. SSLClient cli("localhost", PORT);
  7362. cli.enable_server_certificate_verification(false);
  7363. cli.set_keep_alive(true);
  7364. cli.set_read_timeout(std::chrono::seconds(1));
  7365. auto resa = cli.Get("/a");
  7366. ASSERT_TRUE(!resa);
  7367. EXPECT_EQ(Error::Read, resa.error());
  7368. auto resb = cli.Get("/b");
  7369. ASSERT_TRUE(resb);
  7370. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7371. EXPECT_EQ("b", resb->body);
  7372. }
  7373. #endif
  7374. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7375. protected:
  7376. ServerTestWithAI_PASSIVE()
  7377. : cli_(HOST, PORT)
  7378. #ifdef CPPHTTPLIB_SSL_ENABLED
  7379. ,
  7380. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7381. #endif
  7382. {
  7383. #ifdef CPPHTTPLIB_SSL_ENABLED
  7384. cli_.enable_server_certificate_verification(false);
  7385. #endif
  7386. }
  7387. virtual void SetUp() {
  7388. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7389. res.set_content("Hello World!", "text/plain");
  7390. });
  7391. t_ = thread(
  7392. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7393. svr_.wait_until_ready();
  7394. }
  7395. virtual void TearDown() {
  7396. svr_.stop();
  7397. t_.join();
  7398. }
  7399. #ifdef CPPHTTPLIB_SSL_ENABLED
  7400. SSLClient cli_;
  7401. SSLServer svr_;
  7402. #else
  7403. Client cli_;
  7404. Server svr_;
  7405. #endif
  7406. thread t_;
  7407. };
  7408. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7409. auto res = cli_.Get("/hi");
  7410. ASSERT_TRUE(res);
  7411. EXPECT_EQ(StatusCode::OK_200, res->status);
  7412. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7413. EXPECT_EQ("Hello World!", res->body);
  7414. }
  7415. class ServerUpDownTest : public ::testing::Test {
  7416. protected:
  7417. ServerUpDownTest() : cli_(HOST, PORT) {}
  7418. virtual void SetUp() {
  7419. t_ = thread([&]() {
  7420. svr_.bind_to_any_port(HOST);
  7421. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7422. ASSERT_TRUE(svr_.listen_after_bind());
  7423. });
  7424. svr_.wait_until_ready();
  7425. }
  7426. virtual void TearDown() {
  7427. svr_.stop();
  7428. t_.join();
  7429. }
  7430. Client cli_;
  7431. Server svr_;
  7432. thread t_;
  7433. };
  7434. TEST_F(ServerUpDownTest, QuickStartStop) {
  7435. // Should not crash, especially when run with
  7436. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7437. }
  7438. class PayloadMaxLengthTest : public ::testing::Test {
  7439. protected:
  7440. PayloadMaxLengthTest()
  7441. : cli_(HOST, PORT)
  7442. #ifdef CPPHTTPLIB_SSL_ENABLED
  7443. ,
  7444. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7445. #endif
  7446. {
  7447. #ifdef CPPHTTPLIB_SSL_ENABLED
  7448. cli_.enable_server_certificate_verification(false);
  7449. #endif
  7450. }
  7451. virtual void SetUp() {
  7452. svr_.set_payload_max_length(8);
  7453. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7454. res.set_content("test", "text/plain");
  7455. });
  7456. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7457. svr_.wait_until_ready();
  7458. }
  7459. virtual void TearDown() {
  7460. svr_.stop();
  7461. t_.join();
  7462. }
  7463. #ifdef CPPHTTPLIB_SSL_ENABLED
  7464. SSLClient cli_;
  7465. SSLServer svr_;
  7466. #else
  7467. Client cli_;
  7468. Server svr_;
  7469. #endif
  7470. thread t_;
  7471. };
  7472. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7473. auto res = cli_.Post("/test", "123456789", "text/plain");
  7474. ASSERT_TRUE(res);
  7475. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7476. res = cli_.Post("/test", "12345678", "text/plain");
  7477. ASSERT_TRUE(res);
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. }
  7480. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7481. // Test chunked encoding with payload exceeding the 8-byte limit
  7482. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7483. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7484. ASSERT_TRUE(res);
  7485. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7486. }
  7487. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7488. // Test chunked encoding with payload within the 8-byte limit
  7489. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7490. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7491. ASSERT_TRUE(res);
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. }
  7494. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7495. // Test using send_request to send chunked data exceeding payload limit
  7496. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7497. "Host: " +
  7498. std::string(HOST) + ":" + std::to_string(PORT) +
  7499. "\r\n"
  7500. "Transfer-Encoding: chunked\r\n"
  7501. "Connection: close\r\n"
  7502. "\r\n"
  7503. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7504. "0123456789\r\n"
  7505. "0\r\n" // End chunk
  7506. "\r\n";
  7507. std::string response;
  7508. bool result = send_request(1, chunked_request, &response);
  7509. if (!result) {
  7510. // If send_request fails, it might be because the server closed the
  7511. // connection due to payload limit enforcement, which is acceptable
  7512. SUCCEED()
  7513. << "Server rejected oversized chunked request (connection closed)";
  7514. } else {
  7515. // If we got a response, check if it's an error response or connection was
  7516. // closed early Short response length indicates connection was closed due to
  7517. // payload limit
  7518. if (response.length() <= 10) {
  7519. SUCCEED() << "Server closed connection for oversized chunked request";
  7520. } else {
  7521. // Check for error status codes
  7522. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7523. response.find("Payload Too Large") != std::string::npos ||
  7524. response.find("400") != std::string::npos);
  7525. }
  7526. }
  7527. }
  7528. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7529. // Test request without Content-Length header exceeding payload limit
  7530. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7531. "Host: " +
  7532. std::string(HOST) + ":" +
  7533. std::to_string(PORT) +
  7534. "\r\n"
  7535. "Connection: close\r\n"
  7536. "\r\n";
  7537. // Add payload exceeding the 8-byte limit
  7538. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7539. request_without_content_length += large_payload;
  7540. std::string response;
  7541. bool result = send_request(1, request_without_content_length, &response);
  7542. if (!result) {
  7543. // If send_request fails, server likely closed connection due to payload
  7544. // limit
  7545. SUCCEED() << "Server rejected oversized request without Content-Length "
  7546. "(connection closed)";
  7547. } else {
  7548. // Check if server responded with error or closed connection early
  7549. if (response.length() <= 10) {
  7550. SUCCEED() << "Server closed connection for oversized request without "
  7551. "Content-Length";
  7552. } else {
  7553. // Check for error status codes
  7554. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7555. response.find("Payload Too Large") != std::string::npos ||
  7556. response.find("400") != std::string::npos);
  7557. }
  7558. }
  7559. }
  7560. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7561. // Test request without Content-Length header within payload limit
  7562. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7563. "Host: " +
  7564. std::string(HOST) + ":" +
  7565. std::to_string(PORT) +
  7566. "\r\n"
  7567. "Connection: close\r\n"
  7568. "\r\n";
  7569. // Add payload within the 8-byte limit
  7570. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7571. request_without_content_length += small_payload;
  7572. std::string response;
  7573. bool result = send_request(1, request_without_content_length, &response);
  7574. // For requests without Content-Length, the server may have different behavior
  7575. // The key is that it should not reject due to payload limit for small
  7576. // payloads
  7577. if (result) {
  7578. // Check for any HTTP response (success or error, but not connection closed)
  7579. if (response.length() > 10) {
  7580. SUCCEED()
  7581. << "Server processed request without Content-Length within limit";
  7582. } else {
  7583. // Short response might indicate connection closed, which is acceptable
  7584. SUCCEED() << "Server closed connection for request without "
  7585. "Content-Length (acceptable behavior)";
  7586. }
  7587. } else {
  7588. // Connection failure might be due to protocol requirements
  7589. SUCCEED() << "Connection issue with request without Content-Length "
  7590. "(environment-specific)";
  7591. }
  7592. }
  7593. class LargePayloadMaxLengthTest : public ::testing::Test {
  7594. protected:
  7595. LargePayloadMaxLengthTest()
  7596. : cli_(HOST, PORT)
  7597. #ifdef CPPHTTPLIB_SSL_ENABLED
  7598. ,
  7599. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7600. #endif
  7601. {
  7602. #ifdef CPPHTTPLIB_SSL_ENABLED
  7603. cli_.enable_server_certificate_verification(false);
  7604. #endif
  7605. }
  7606. virtual void SetUp() {
  7607. // Set 10MB payload limit
  7608. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7609. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7610. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7611. res.set_content("Large payload test", "text/plain");
  7612. });
  7613. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7614. svr_.wait_until_ready();
  7615. }
  7616. virtual void TearDown() {
  7617. svr_.stop();
  7618. t_.join();
  7619. }
  7620. #ifdef CPPHTTPLIB_SSL_ENABLED
  7621. SSLClient cli_;
  7622. SSLServer svr_;
  7623. #else
  7624. Client cli_;
  7625. Server svr_;
  7626. #endif
  7627. thread t_;
  7628. };
  7629. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7630. // Test chunked encoding with payload within 10MB limit
  7631. std::string medium_payload(5 * 1024 * 1024,
  7632. 'A'); // 5MB payload, within 10MB limit
  7633. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7634. ASSERT_TRUE(res);
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. }
  7637. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7638. // Test chunked encoding with payload exceeding 10MB limit
  7639. std::string large_payload(12 * 1024 * 1024,
  7640. 'B'); // 12MB payload, exceeds 10MB limit
  7641. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7642. // Server may either return 413 or close the connection
  7643. if (res) {
  7644. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7645. } else {
  7646. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7647. }
  7648. }
  7649. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7650. // Test request without Content-Length header within 10MB limit
  7651. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7652. "Host: " +
  7653. std::string(HOST) + ":" +
  7654. std::to_string(PORT) +
  7655. "\r\n"
  7656. "Connection: close\r\n"
  7657. "\r\n";
  7658. // Add 1MB payload (within 10MB limit)
  7659. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7660. request_without_content_length += medium_payload;
  7661. std::string response;
  7662. bool result = send_request(5, request_without_content_length, &response);
  7663. if (result) {
  7664. // Should get a proper HTTP response for payloads within limit
  7665. if (response.length() > 10) {
  7666. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7667. "10MB limit";
  7668. } else {
  7669. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7670. "Content-Length)";
  7671. }
  7672. } else {
  7673. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7674. }
  7675. }
  7676. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7677. // Test request without Content-Length header exceeding 10MB limit
  7678. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7679. "Host: " +
  7680. std::string(HOST) + ":" +
  7681. std::to_string(PORT) +
  7682. "\r\n"
  7683. "Connection: close\r\n"
  7684. "\r\n";
  7685. // Add 12MB payload (exceeds 10MB limit)
  7686. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7687. request_without_content_length += large_payload;
  7688. std::string response;
  7689. bool result = send_request(10, request_without_content_length, &response);
  7690. if (!result) {
  7691. // Server should close connection due to payload limit
  7692. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7693. "(connection closed)";
  7694. } else {
  7695. // Check for error response
  7696. if (response.length() <= 10) {
  7697. SUCCEED()
  7698. << "Server closed connection for 12MB request exceeding 10MB limit";
  7699. } else {
  7700. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7701. response.find("Payload Too Large") != std::string::npos ||
  7702. response.find("400") != std::string::npos);
  7703. }
  7704. }
  7705. }
  7706. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7707. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7708. // path.
  7709. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7710. Server svr;
  7711. const size_t LIMIT = 64 * 1024; // 64KB
  7712. svr.set_payload_max_length(LIMIT);
  7713. size_t total = 0;
  7714. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7715. const ContentReader &content_reader) {
  7716. content_reader([&](const char * /*data*/, size_t len) {
  7717. total += len;
  7718. return true;
  7719. });
  7720. res.status = 200;
  7721. res.set_content("stream_ok", "text/plain");
  7722. });
  7723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7724. auto se = detail::scope_exit([&] {
  7725. svr.stop();
  7726. thread.join();
  7727. ASSERT_FALSE(svr.is_running());
  7728. });
  7729. svr.wait_until_ready();
  7730. // Prepare 256KB raw data and gzip-compress it
  7731. std::string raw(256 * 1024, 'A');
  7732. std::string gz;
  7733. {
  7734. z_stream zs{};
  7735. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7736. Z_DEFAULT_STRATEGY);
  7737. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7738. zs.avail_in = static_cast<uInt>(raw.size());
  7739. char outbuf[4096];
  7740. int ret;
  7741. do {
  7742. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7743. zs.avail_out = sizeof(outbuf);
  7744. ret = deflate(&zs, Z_FINISH);
  7745. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7746. } while (ret != Z_STREAM_END);
  7747. deflateEnd(&zs);
  7748. }
  7749. Client cli(HOST, PORT);
  7750. cli.set_connection_timeout(std::chrono::seconds(5));
  7751. Headers headers = {{"Content-Encoding", "gzip"}};
  7752. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7753. "application/octet-stream");
  7754. ASSERT_TRUE(res);
  7755. // Server must reject oversized decompressed payloads with 413.
  7756. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7757. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7758. EXPECT_LE(total, LIMIT);
  7759. }
  7760. #endif
  7761. // Regression test for DoS vulnerability: a malicious server sending a response
  7762. // without Content-Length header must not cause unbounded memory consumption on
  7763. // the client side. The client should stop reading after a reasonable limit,
  7764. // similar to the server-side set_payload_max_length protection.
  7765. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7766. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7767. #ifndef _WIN32
  7768. signal(SIGPIPE, SIG_IGN);
  7769. #endif
  7770. auto server_thread = std::thread([] {
  7771. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7772. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7773. default_socket_options(srv);
  7774. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7775. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7776. sockaddr_in addr{};
  7777. addr.sin_family = AF_INET;
  7778. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7779. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7780. int opt = 1;
  7781. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7782. #ifdef _WIN32
  7783. reinterpret_cast<const char *>(&opt),
  7784. #else
  7785. &opt,
  7786. #endif
  7787. sizeof(opt));
  7788. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7789. ::listen(srv, 1);
  7790. sockaddr_in cli_addr{};
  7791. socklen_t cli_len = sizeof(cli_addr);
  7792. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7793. if (cli != INVALID_SOCKET) {
  7794. char buf[4096];
  7795. ::recv(cli, buf, sizeof(buf), 0);
  7796. // Malicious response: no Content-Length, no chunked encoding
  7797. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7798. "Connection: close\r\n"
  7799. "\r\n";
  7800. ::send(cli,
  7801. #ifdef _WIN32
  7802. static_cast<const char *>(response_header.c_str()),
  7803. static_cast<int>(response_header.size()),
  7804. #else
  7805. response_header.c_str(), response_header.size(),
  7806. #endif
  7807. 0);
  7808. // Send 10MB of data
  7809. std::string chunk(64 * 1024, 'A');
  7810. size_t total_sent = 0;
  7811. while (total_sent < MALICIOUS_DATA_SIZE) {
  7812. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7813. auto sent = ::send(cli,
  7814. #ifdef _WIN32
  7815. static_cast<const char *>(chunk.c_str()),
  7816. static_cast<int>(to_send),
  7817. #else
  7818. chunk.c_str(), to_send,
  7819. #endif
  7820. 0);
  7821. if (sent <= 0) break;
  7822. total_sent += static_cast<size_t>(sent);
  7823. }
  7824. detail::close_socket(cli);
  7825. }
  7826. detail::close_socket(srv);
  7827. });
  7828. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7829. size_t total_read = 0;
  7830. {
  7831. Client cli("127.0.0.1", PORT + 2);
  7832. cli.set_read_timeout(5, 0);
  7833. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7834. auto stream = cli.open_stream("GET", "/malicious");
  7835. ASSERT_TRUE(stream.is_valid());
  7836. char buffer[64 * 1024];
  7837. ssize_t n;
  7838. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7839. total_read += static_cast<size_t>(n);
  7840. }
  7841. } // StreamHandle and Client destroyed here, closing the socket
  7842. server_thread.join();
  7843. // With set_payload_max_length, the client must stop reading before consuming
  7844. // all 10MB. The read loop should be cut off at or near the configured limit.
  7845. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7846. << "Client read " << total_read << " bytes, exceeding the configured "
  7847. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7848. }
  7849. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7850. // the entire response body without truncation.
  7851. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7852. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7853. #ifndef _WIN32
  7854. signal(SIGPIPE, SIG_IGN);
  7855. #endif
  7856. auto server_thread = std::thread([] {
  7857. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7858. default_socket_options(srv);
  7859. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7860. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7861. sockaddr_in addr{};
  7862. addr.sin_family = AF_INET;
  7863. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7864. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7865. int opt = 1;
  7866. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7867. #ifdef _WIN32
  7868. reinterpret_cast<const char *>(&opt),
  7869. #else
  7870. &opt,
  7871. #endif
  7872. sizeof(opt));
  7873. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7874. ::listen(srv, 1);
  7875. sockaddr_in cli_addr{};
  7876. socklen_t cli_len = sizeof(cli_addr);
  7877. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7878. if (cli != INVALID_SOCKET) {
  7879. char buf[4096];
  7880. ::recv(cli, buf, sizeof(buf), 0);
  7881. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7882. "Connection: close\r\n"
  7883. "\r\n";
  7884. ::send(cli,
  7885. #ifdef _WIN32
  7886. static_cast<const char *>(response_header.c_str()),
  7887. static_cast<int>(response_header.size()),
  7888. #else
  7889. response_header.c_str(), response_header.size(),
  7890. #endif
  7891. 0);
  7892. std::string chunk(64 * 1024, 'A');
  7893. size_t total_sent = 0;
  7894. while (total_sent < DATA_SIZE) {
  7895. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7896. auto sent = ::send(cli,
  7897. #ifdef _WIN32
  7898. static_cast<const char *>(chunk.c_str()),
  7899. static_cast<int>(to_send),
  7900. #else
  7901. chunk.c_str(), to_send,
  7902. #endif
  7903. 0);
  7904. if (sent <= 0) break;
  7905. total_sent += static_cast<size_t>(sent);
  7906. }
  7907. #ifdef _WIN32
  7908. ::shutdown(cli, SD_SEND);
  7909. #else
  7910. ::shutdown(cli, SHUT_WR);
  7911. #endif
  7912. // Drain until the client closes its end, ensuring all data is delivered
  7913. char drain[1024];
  7914. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7915. detail::close_socket(cli);
  7916. }
  7917. detail::close_socket(srv);
  7918. });
  7919. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7920. size_t total_read = 0;
  7921. {
  7922. Client cli("127.0.0.1", PORT + 2);
  7923. cli.set_read_timeout(5, 0);
  7924. cli.set_payload_max_length(0); // 0 means no limit
  7925. auto stream = cli.open_stream("GET", "/data");
  7926. ASSERT_TRUE(stream.is_valid());
  7927. char buffer[64 * 1024];
  7928. ssize_t n;
  7929. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7930. total_read += static_cast<size_t>(n);
  7931. }
  7932. }
  7933. server_thread.join();
  7934. EXPECT_EQ(total_read, DATA_SIZE)
  7935. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7936. << " bytes without truncation, but only read " << total_read << " bytes.";
  7937. }
  7938. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  7939. // enormous Content-Length must not cause the client to pre-allocate a huge
  7940. // response body buffer. The reservation is capped at payload_max_length_, and
  7941. // the read itself fails when the body exceeds the limit.
  7942. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  7943. #ifndef _WIN32
  7944. signal(SIGPIPE, SIG_IGN);
  7945. #endif
  7946. auto server_thread = std::thread([] {
  7947. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7948. default_socket_options(srv);
  7949. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7950. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7951. sockaddr_in addr{};
  7952. addr.sin_family = AF_INET;
  7953. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7954. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7955. int opt = 1;
  7956. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7957. #ifdef _WIN32
  7958. reinterpret_cast<const char *>(&opt),
  7959. #else
  7960. &opt,
  7961. #endif
  7962. sizeof(opt));
  7963. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7964. ::listen(srv, 1);
  7965. sockaddr_in cli_addr{};
  7966. socklen_t cli_len = sizeof(cli_addr);
  7967. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7968. if (cli != INVALID_SOCKET) {
  7969. char buf[4096];
  7970. ::recv(cli, buf, sizeof(buf), 0);
  7971. // Malicious response: claim a 20GB body but send only a tiny payload.
  7972. std::string response = "HTTP/1.1 200 OK\r\n"
  7973. "Content-Length: 20000000000\r\n"
  7974. "\r\n"
  7975. "abc";
  7976. ::send(cli,
  7977. #ifdef _WIN32
  7978. static_cast<const char *>(response.c_str()),
  7979. static_cast<int>(response.size()),
  7980. #else
  7981. response.c_str(), response.size(),
  7982. #endif
  7983. 0);
  7984. detail::close_socket(cli);
  7985. }
  7986. detail::close_socket(srv);
  7987. });
  7988. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7989. {
  7990. Client cli("127.0.0.1", PORT + 2);
  7991. cli.set_read_timeout(5, 0);
  7992. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  7993. // result in a 20GB pre-allocation. The Get() call is expected to fail
  7994. // (server claims more bytes than payload_max_length permits), but it must
  7995. // not exhaust memory before getting there.
  7996. auto res = cli.Get("/malicious");
  7997. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  7998. }
  7999. server_thread.join();
  8000. }
  8001. // Verify that content_receiver bypasses the default payload_max_length,
  8002. // allowing streaming downloads larger than 100MB without requiring an explicit
  8003. // set_payload_max_length call.
  8004. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8005. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8006. #ifndef _WIN32
  8007. signal(SIGPIPE, SIG_IGN);
  8008. #endif
  8009. auto server_thread = std::thread([] {
  8010. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8011. default_socket_options(srv);
  8012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8013. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8014. sockaddr_in addr{};
  8015. addr.sin_family = AF_INET;
  8016. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8017. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8018. int opt = 1;
  8019. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8020. #ifdef _WIN32
  8021. reinterpret_cast<const char *>(&opt),
  8022. #else
  8023. &opt,
  8024. #endif
  8025. sizeof(opt));
  8026. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8027. ::listen(srv, 1);
  8028. sockaddr_in cli_addr{};
  8029. socklen_t cli_len = sizeof(cli_addr);
  8030. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8031. if (cli != INVALID_SOCKET) {
  8032. char buf[4096];
  8033. ::recv(cli, buf, sizeof(buf), 0);
  8034. // Response with Content-Length larger than default 100MB limit
  8035. auto content_length = std::to_string(DATA_SIZE);
  8036. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8037. "Content-Length: " +
  8038. content_length +
  8039. "\r\n"
  8040. "Connection: close\r\n"
  8041. "\r\n";
  8042. ::send(cli,
  8043. #ifdef _WIN32
  8044. static_cast<const char *>(response_header.c_str()),
  8045. static_cast<int>(response_header.size()),
  8046. #else
  8047. response_header.c_str(), response_header.size(),
  8048. #endif
  8049. 0);
  8050. std::string chunk(64 * 1024, 'A');
  8051. size_t total_sent = 0;
  8052. while (total_sent < DATA_SIZE) {
  8053. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8054. auto sent = ::send(cli,
  8055. #ifdef _WIN32
  8056. static_cast<const char *>(chunk.c_str()),
  8057. static_cast<int>(to_send),
  8058. #else
  8059. chunk.c_str(), to_send,
  8060. #endif
  8061. 0);
  8062. if (sent <= 0) break;
  8063. total_sent += static_cast<size_t>(sent);
  8064. }
  8065. detail::close_socket(cli);
  8066. }
  8067. detail::close_socket(srv);
  8068. });
  8069. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8070. size_t total_received = 0;
  8071. {
  8072. Client cli("127.0.0.1", PORT + 2);
  8073. cli.set_read_timeout(10, 0);
  8074. // Do NOT call set_payload_max_length — use the default 100MB limit
  8075. auto res =
  8076. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8077. total_received += data_length;
  8078. return true;
  8079. });
  8080. ASSERT_TRUE(res);
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. }
  8083. server_thread.join();
  8084. EXPECT_EQ(total_received, DATA_SIZE)
  8085. << "With content_receiver, the client should read all " << DATA_SIZE
  8086. << " bytes despite the default 100MB payload_max_length, but only read "
  8087. << total_received << " bytes.";
  8088. }
  8089. // Verify that an explicit set_payload_max_length smaller than the response is
  8090. // enforced even when a content_receiver is used.
  8091. TEST(ClientVulnerabilityTest,
  8092. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8093. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8094. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8095. #ifndef _WIN32
  8096. signal(SIGPIPE, SIG_IGN);
  8097. #endif
  8098. auto server_thread = std::thread([] {
  8099. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8100. default_socket_options(srv);
  8101. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8102. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8103. sockaddr_in addr{};
  8104. addr.sin_family = AF_INET;
  8105. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8106. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8107. int opt = 1;
  8108. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8109. #ifdef _WIN32
  8110. reinterpret_cast<const char *>(&opt),
  8111. #else
  8112. &opt,
  8113. #endif
  8114. sizeof(opt));
  8115. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8116. ::listen(srv, 1);
  8117. sockaddr_in cli_addr{};
  8118. socklen_t cli_len = sizeof(cli_addr);
  8119. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8120. if (cli != INVALID_SOCKET) {
  8121. char buf[4096];
  8122. ::recv(cli, buf, sizeof(buf), 0);
  8123. auto content_length = std::to_string(DATA_SIZE);
  8124. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8125. "Content-Length: " +
  8126. content_length +
  8127. "\r\n"
  8128. "Connection: close\r\n"
  8129. "\r\n";
  8130. ::send(cli,
  8131. #ifdef _WIN32
  8132. static_cast<const char *>(response_header.c_str()),
  8133. static_cast<int>(response_header.size()),
  8134. #else
  8135. response_header.c_str(), response_header.size(),
  8136. #endif
  8137. 0);
  8138. std::string chunk(64 * 1024, 'A');
  8139. size_t total_sent = 0;
  8140. while (total_sent < DATA_SIZE) {
  8141. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8142. auto sent = ::send(cli,
  8143. #ifdef _WIN32
  8144. static_cast<const char *>(chunk.c_str()),
  8145. static_cast<int>(to_send),
  8146. #else
  8147. chunk.c_str(), to_send,
  8148. #endif
  8149. 0);
  8150. if (sent <= 0) break;
  8151. total_sent += static_cast<size_t>(sent);
  8152. }
  8153. detail::close_socket(cli);
  8154. }
  8155. detail::close_socket(srv);
  8156. });
  8157. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8158. size_t total_received = 0;
  8159. {
  8160. Client cli("127.0.0.1", PORT + 2);
  8161. cli.set_read_timeout(10, 0);
  8162. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8163. auto res =
  8164. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8165. total_received += data_length;
  8166. return true;
  8167. });
  8168. // Should fail because 200MB exceeds the explicit 150MB limit
  8169. EXPECT_FALSE(res);
  8170. }
  8171. server_thread.join();
  8172. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8173. << "Client with content_receiver should respect the explicit "
  8174. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8175. << total_received << " bytes.";
  8176. }
  8177. // Verify that an explicit set_payload_max_length larger than the response
  8178. // allows the content_receiver to read all data successfully.
  8179. TEST(ClientVulnerabilityTest,
  8180. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8181. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8182. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8183. #ifndef _WIN32
  8184. signal(SIGPIPE, SIG_IGN);
  8185. #endif
  8186. auto server_thread = std::thread([] {
  8187. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8188. default_socket_options(srv);
  8189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8190. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8191. sockaddr_in addr{};
  8192. addr.sin_family = AF_INET;
  8193. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8194. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8195. int opt = 1;
  8196. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8197. #ifdef _WIN32
  8198. reinterpret_cast<const char *>(&opt),
  8199. #else
  8200. &opt,
  8201. #endif
  8202. sizeof(opt));
  8203. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8204. ::listen(srv, 1);
  8205. sockaddr_in cli_addr{};
  8206. socklen_t cli_len = sizeof(cli_addr);
  8207. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8208. if (cli != INVALID_SOCKET) {
  8209. char buf[4096];
  8210. ::recv(cli, buf, sizeof(buf), 0);
  8211. auto content_length = std::to_string(DATA_SIZE);
  8212. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8213. "Content-Length: " +
  8214. content_length +
  8215. "\r\n"
  8216. "Connection: close\r\n"
  8217. "\r\n";
  8218. ::send(cli,
  8219. #ifdef _WIN32
  8220. static_cast<const char *>(response_header.c_str()),
  8221. static_cast<int>(response_header.size()),
  8222. #else
  8223. response_header.c_str(), response_header.size(),
  8224. #endif
  8225. 0);
  8226. std::string chunk(64 * 1024, 'A');
  8227. size_t total_sent = 0;
  8228. while (total_sent < DATA_SIZE) {
  8229. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8230. auto sent = ::send(cli,
  8231. #ifdef _WIN32
  8232. static_cast<const char *>(chunk.c_str()),
  8233. static_cast<int>(to_send),
  8234. #else
  8235. chunk.c_str(), to_send,
  8236. #endif
  8237. 0);
  8238. if (sent <= 0) break;
  8239. total_sent += static_cast<size_t>(sent);
  8240. }
  8241. #ifdef _WIN32
  8242. ::shutdown(cli, SD_SEND);
  8243. #else
  8244. ::shutdown(cli, SHUT_WR);
  8245. #endif
  8246. char drain[1024];
  8247. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8248. detail::close_socket(cli);
  8249. }
  8250. detail::close_socket(srv);
  8251. });
  8252. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8253. size_t total_received = 0;
  8254. {
  8255. Client cli("127.0.0.1", PORT + 2);
  8256. cli.set_read_timeout(10, 0);
  8257. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8258. auto res =
  8259. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8260. total_received += data_length;
  8261. return true;
  8262. });
  8263. ASSERT_TRUE(res);
  8264. EXPECT_EQ(StatusCode::OK_200, res->status);
  8265. }
  8266. server_thread.join();
  8267. EXPECT_EQ(total_received, DATA_SIZE)
  8268. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8269. << " bytes (larger than " << DATA_SIZE
  8270. << " bytes response), content_receiver should read all data, but only "
  8271. "read "
  8272. << total_received << " bytes.";
  8273. }
  8274. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8275. // Regression test for "zip bomb" attack on the client side: a malicious server
  8276. // sends a small gzip-compressed response that decompresses to a huge payload.
  8277. // The client must enforce payload_max_length on the decompressed size.
  8278. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8279. constexpr size_t DECOMPRESSED_SIZE =
  8280. 10 * 1024 * 1024; // 10MB after decompression
  8281. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8282. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8283. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8284. std::string compressed;
  8285. {
  8286. httplib::detail::gzip_compressor compressor;
  8287. bool ok =
  8288. compressor.compress(uncompressed.data(), uncompressed.size(),
  8289. /*last=*/true, [&](const char *buf, size_t len) {
  8290. compressed.append(buf, len);
  8291. return true;
  8292. });
  8293. ASSERT_TRUE(ok);
  8294. }
  8295. // Sanity: compressed data should be much smaller than the decompressed size
  8296. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8297. #ifndef _WIN32
  8298. signal(SIGPIPE, SIG_IGN);
  8299. #endif
  8300. // Set up the listening socket in the main thread so the server is guaranteed
  8301. // to be ready before the client connects (eliminates race condition).
  8302. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8303. default_socket_options(srv);
  8304. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8305. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8306. sockaddr_in addr{};
  8307. addr.sin_family = AF_INET;
  8308. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8309. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8310. int opt = 1;
  8311. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8312. #ifdef _WIN32
  8313. reinterpret_cast<const char *>(&opt),
  8314. #else
  8315. &opt,
  8316. #endif
  8317. sizeof(opt));
  8318. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8319. ASSERT_EQ(0, ::listen(srv, 1));
  8320. auto server_thread = std::thread([&compressed, srv] {
  8321. sockaddr_in cli_addr{};
  8322. socklen_t cli_len = sizeof(cli_addr);
  8323. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8324. if (cli != INVALID_SOCKET) {
  8325. // Read the full HTTP request (until \r\n\r\n)
  8326. char buf[4096];
  8327. size_t total = 0;
  8328. while (total < sizeof(buf)) {
  8329. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8330. if (n <= 0) break;
  8331. total += static_cast<size_t>(n);
  8332. // Check for end of headers
  8333. if (total >= 4) {
  8334. std::string req(buf, total);
  8335. if (req.find("\r\n\r\n") != std::string::npos) break;
  8336. }
  8337. }
  8338. // Malicious response: gzip-compressed body, no Content-Length
  8339. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8340. "Content-Encoding: gzip\r\n"
  8341. "Connection: close\r\n"
  8342. "\r\n";
  8343. ::send(cli,
  8344. #ifdef _WIN32
  8345. static_cast<const char *>(response_header.c_str()),
  8346. static_cast<int>(response_header.size()),
  8347. #else
  8348. response_header.c_str(), response_header.size(),
  8349. #endif
  8350. 0);
  8351. // Send the compressed payload (small on the wire, huge when decompressed)
  8352. size_t total_sent = 0;
  8353. while (total_sent < compressed.size()) {
  8354. auto to_send = std::min(compressed.size() - total_sent,
  8355. static_cast<size_t>(64 * 1024));
  8356. auto sent =
  8357. ::send(cli,
  8358. #ifdef _WIN32
  8359. static_cast<const char *>(compressed.c_str() + total_sent),
  8360. static_cast<int>(to_send),
  8361. #else
  8362. compressed.c_str() + total_sent, to_send,
  8363. #endif
  8364. 0);
  8365. if (sent <= 0) break;
  8366. total_sent += static_cast<size_t>(sent);
  8367. }
  8368. detail::close_socket(cli);
  8369. }
  8370. });
  8371. auto se = detail::scope_exit([&] {
  8372. detail::close_socket(srv);
  8373. server_thread.join();
  8374. });
  8375. size_t total_decompressed = 0;
  8376. {
  8377. Client cli("127.0.0.1", PORT + 3);
  8378. cli.set_read_timeout(5, 0);
  8379. cli.set_decompress(true);
  8380. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8381. auto stream = cli.open_stream("GET", "/zipbomb");
  8382. ASSERT_TRUE(stream.is_valid());
  8383. char buffer[64 * 1024];
  8384. ssize_t n;
  8385. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8386. total_decompressed += static_cast<size_t>(n);
  8387. }
  8388. }
  8389. // The decompressed size must be capped by payload_max_length. Without
  8390. // protection, the client would decompress the full 10MB from a tiny
  8391. // compressed payload, enabling a zip bomb DoS attack.
  8392. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8393. << "Client decompressed " << total_decompressed
  8394. << " bytes from a gzip response. The decompressed size should be "
  8395. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8396. }
  8397. #endif
  8398. TEST(HostAndPortPropertiesTest, NoSSL) {
  8399. httplib::Client cli("www.google.com", 1234);
  8400. ASSERT_EQ("www.google.com", cli.host());
  8401. ASSERT_EQ(1234, cli.port());
  8402. }
  8403. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8404. httplib::Client cli("www.google.com:1234");
  8405. ASSERT_EQ("www.google.com", cli.host());
  8406. ASSERT_EQ(1234, cli.port());
  8407. }
  8408. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8409. // Port number that overflows int — should not crash, client becomes invalid
  8410. httplib::Client cli("http://www.google.com:99999999999999999999");
  8411. ASSERT_FALSE(cli.is_valid());
  8412. }
  8413. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8414. // Port 99999 exceeds valid range (1-65535) — should not crash
  8415. httplib::Client cli("http://www.google.com:99999");
  8416. ASSERT_FALSE(cli.is_valid());
  8417. }
  8418. #ifdef CPPHTTPLIB_SSL_ENABLED
  8419. TEST(HostAndPortPropertiesTest, SSL) {
  8420. httplib::SSLClient cli("www.google.com");
  8421. ASSERT_EQ("www.google.com", cli.host());
  8422. ASSERT_EQ(443, cli.port());
  8423. }
  8424. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8425. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8426. std::string cert;
  8427. read_file(CA_CERT_FILE, cert);
  8428. httplib::SSLClient httplib_client("www.google.com");
  8429. // Load CA store first time
  8430. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8431. // Load CA store second time (update)
  8432. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8433. // Verify client is still valid and can make connections
  8434. httplib_client.enable_server_certificate_verification(true);
  8435. auto res = httplib_client.Get("/");
  8436. ASSERT_TRUE(res);
  8437. // Google may return 200 or 301 depending on various factors
  8438. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8439. res->status == StatusCode::MovedPermanently_301);
  8440. }
  8441. TEST(SSLClientTest, ServerNameIndication_Online) {
  8442. auto host = "httpbingo.org";
  8443. auto path = std::string{"/get"};
  8444. SSLClient cli(host, 443);
  8445. auto res = cli.Get(path);
  8446. ASSERT_TRUE(res);
  8447. ASSERT_EQ(StatusCode::OK_200, res->status);
  8448. }
  8449. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8450. // Use a site that will cause SSL verification failure due to self-signed cert
  8451. SSLClient cli("self-signed.badssl.com", 443);
  8452. cli.enable_server_certificate_verification(true);
  8453. auto res = cli.Get("/");
  8454. ASSERT_TRUE(!res);
  8455. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8456. // Verify backend error is captured for SSLServerVerification
  8457. // This occurs when certificate verification fails
  8458. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8459. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8460. EXPECT_NE(0UL, res.ssl_backend_error());
  8461. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8462. // For OpenSSL, ssl_error is 0 for verification errors
  8463. EXPECT_EQ(0, res.ssl_error());
  8464. #if !defined(_WIN32) || \
  8465. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8466. // On non-Windows or when Windows Schannel is disabled, the error comes
  8467. // from OpenSSL's verification
  8468. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8469. res.ssl_backend_error());
  8470. #endif
  8471. #endif
  8472. }
  8473. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8474. // Use a site where hostname doesn't match the certificate
  8475. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8476. SSLClient cli("wrong.host.badssl.com", 443);
  8477. cli.enable_server_certificate_verification(true);
  8478. cli.enable_server_hostname_verification(true);
  8479. auto res = cli.Get("/");
  8480. ASSERT_TRUE(!res);
  8481. // The error type depends on when hostname verification occurs:
  8482. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8483. // - Mbed TLS: SSLServerVerification (during handshake)
  8484. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8485. res.error() == Error::SSLServerVerification);
  8486. // Verify backend error is captured for hostname verification failure
  8487. EXPECT_NE(0UL, res.ssl_backend_error());
  8488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8489. // For OpenSSL, ssl_error is 0 for verification errors
  8490. EXPECT_EQ(0, res.ssl_error());
  8491. #if !defined(_WIN32) || \
  8492. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8493. // On non-Windows or when Windows Schannel is disabled, the error comes
  8494. // from OpenSSL's hostname verification
  8495. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8496. res.ssl_backend_error());
  8497. #endif
  8498. #endif
  8499. }
  8500. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8501. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8502. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8503. SSLClient cli("www.google.com", 443);
  8504. cli.enable_server_certificate_verification(true);
  8505. auto res = cli.Get("/");
  8506. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8507. }
  8508. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8509. SSLClient cli("www.google.com", 443);
  8510. cli.enable_server_certificate_verification(true);
  8511. cli.enable_windows_certificate_verification(false);
  8512. auto res = cli.Get("/");
  8513. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8514. }
  8515. #endif
  8516. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8517. Client cli("https://google.com");
  8518. auto res = cli.Get("/");
  8519. ASSERT_TRUE(res);
  8520. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8521. }
  8522. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8523. SSLClient cli("google.com");
  8524. cli.set_ca_cert_path(CA_CERT_FILE);
  8525. auto res = cli.Get("/");
  8526. ASSERT_TRUE(res);
  8527. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8528. }
  8529. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8530. SSLClient cli("google.com");
  8531. cli.enable_server_certificate_verification(true);
  8532. cli.set_ca_cert_path("hello");
  8533. auto res = cli.Get("/");
  8534. ASSERT_TRUE(!res);
  8535. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8536. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8537. // should be set
  8538. EXPECT_EQ(0, res.ssl_error());
  8539. // Verify backend error is captured for SSLLoadingCerts
  8540. // This error occurs when loading CA certificates fails
  8541. EXPECT_NE(0UL, res.ssl_backend_error());
  8542. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8543. // OpenSSL specific error codes:
  8544. // > openssl errstr 0x80000002
  8545. // error:80000002:system library::No such file or directory
  8546. // > openssl errstr 0xA000126
  8547. // error:0A000126:SSL routines::unexpected eof while reading
  8548. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8549. res.ssl_backend_error() == 0xA000126);
  8550. #endif
  8551. }
  8552. TEST(SSLClientTest, ServerCertificateVerification4) {
  8553. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8554. ASSERT_TRUE(svr.is_valid());
  8555. svr.Get("/test", [&](const Request &, Response &res) {
  8556. res.set_content("test", "text/plain");
  8557. svr.stop();
  8558. ASSERT_TRUE(true);
  8559. });
  8560. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8561. auto se = detail::scope_exit([&] {
  8562. t.join();
  8563. ASSERT_FALSE(svr.is_running());
  8564. });
  8565. svr.wait_until_ready();
  8566. SSLClient cli("127.0.0.1", PORT);
  8567. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8568. cli.enable_server_certificate_verification(true);
  8569. cli.set_connection_timeout(30);
  8570. auto res = cli.Get("/test");
  8571. ASSERT_TRUE(res);
  8572. ASSERT_EQ(StatusCode::OK_200, res->status);
  8573. }
  8574. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8575. std::string cert;
  8576. read_file(CA_CERT_FILE, cert);
  8577. SSLClient cli("google.com");
  8578. cli.load_ca_cert_store(cert.data(), cert.size());
  8579. const auto res = cli.Get("/");
  8580. ASSERT_TRUE(res);
  8581. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8582. }
  8583. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8584. // clang-format off
  8585. static constexpr char cert[] =
  8586. "GlobalSign Root CA\n"
  8587. "==================\n"
  8588. "-----BEGIN CERTIFICATE-----\n"
  8589. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8590. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8591. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8592. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8593. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8594. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8595. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8596. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8597. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8598. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8599. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8600. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8601. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8602. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8603. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8604. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8605. "-----END CERTIFICATE-----\n";
  8606. // clang-format on
  8607. SSLClient cli("google.com");
  8608. cli.load_ca_cert_store(cert, sizeof(cert));
  8609. const auto res = cli.Get("/");
  8610. ASSERT_TRUE(res);
  8611. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8612. }
  8613. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8614. SSLClient cli("www.youtube.com");
  8615. cli.set_ca_cert_path(CA_CERT_FILE);
  8616. cli.enable_server_certificate_verification(true);
  8617. cli.set_follow_location(true);
  8618. auto res = cli.Get("/");
  8619. ASSERT_TRUE(res);
  8620. ASSERT_EQ(StatusCode::OK_200, res->status);
  8621. }
  8622. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8623. SSLClient cli("wWw.YouTube.Com");
  8624. cli.set_ca_cert_path(CA_CERT_FILE);
  8625. cli.enable_server_certificate_verification(true);
  8626. cli.enable_server_hostname_verification(true);
  8627. cli.set_follow_location(true);
  8628. auto res = cli.Get("/");
  8629. ASSERT_TRUE(res);
  8630. ASSERT_EQ(StatusCode::OK_200, res->status);
  8631. }
  8632. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8633. SSLClient cli("gOoGlE.COm");
  8634. cli.enable_server_certificate_verification(true);
  8635. cli.enable_server_hostname_verification(true);
  8636. cli.set_follow_location(true);
  8637. auto res = cli.Get("/");
  8638. ASSERT_TRUE(res);
  8639. ASSERT_EQ(StatusCode::OK_200, res->status);
  8640. }
  8641. TEST(SSLClientTest, Issue2004_Online) {
  8642. Client client("https://google.com");
  8643. client.set_follow_location(true);
  8644. auto res = client.Get("/");
  8645. ASSERT_TRUE(res);
  8646. ASSERT_EQ(StatusCode::OK_200, res->status);
  8647. auto body = res->body;
  8648. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8649. }
  8650. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8651. // Create SSLClient with invalid cert/key to make is_valid() return false
  8652. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8653. "nonexistent_key.pem");
  8654. // is_valid() should be false due to cert loading failure
  8655. ASSERT_FALSE(cli.is_valid());
  8656. auto res = cli.Get("/");
  8657. ASSERT_FALSE(res);
  8658. EXPECT_EQ(Error::SSLConnection, res.error());
  8659. }
  8660. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8661. // Test for Issue #2251: SSL error not properly reported when client cert
  8662. // and key paths are swapped or mismatched
  8663. // This simulates the scenario where user accidentally swaps the cert and key
  8664. // files
  8665. // Using client cert file as private key and vice versa (completely wrong)
  8666. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8667. // Should fail validation due to cert/key mismatch
  8668. ASSERT_FALSE(cli.is_valid());
  8669. // Attempt to make a request should fail with proper error
  8670. auto res = cli.Get("/");
  8671. ASSERT_FALSE(res);
  8672. EXPECT_EQ(Error::SSLConnection, res.error());
  8673. // SSL error should be recorded in the Result object (this is the key fix for
  8674. // Issue #2251)
  8675. auto backend_error = res.ssl_backend_error();
  8676. EXPECT_NE(0u, backend_error);
  8677. }
  8678. // Tests cert/key mismatch detection at the TLS context level
  8679. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8680. // Test that using mismatched cert/key causes connection failure.
  8681. // We verify this at the SSLClient level rather than through internal
  8682. // TLS API functions.
  8683. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8684. cli.enable_server_certificate_verification(false);
  8685. cli.set_connection_timeout(2);
  8686. // The mismatch should cause a connection or handshake error
  8687. auto res = cli.Get("/test");
  8688. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8689. // Either way, the request should fail
  8690. EXPECT_FALSE(res);
  8691. }
  8692. #endif
  8693. #if 0
  8694. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8695. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8696. ASSERT_TRUE(cli != nullptr);
  8697. cli->set_address_family(AF_INET6);
  8698. cli->set_interface("en0");
  8699. auto res = cli->Get("/get");
  8700. ASSERT_TRUE(res);
  8701. ASSERT_EQ(StatusCode::OK_200, res->status);
  8702. }
  8703. #endif
  8704. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8705. #ifdef CPPHTTPLIB_SSL_ENABLED
  8706. void ClientCertPresent(
  8707. const std::string &client_cert_file,
  8708. const std::string &client_private_key_file,
  8709. const std::string &client_encrypted_private_key_pass = std::string()) {
  8710. using namespace httplib::tls;
  8711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8712. CLIENT_CA_CERT_DIR);
  8713. ASSERT_TRUE(svr.is_valid());
  8714. svr.Get("/test", [&](const Request &req, Response &res) {
  8715. res.set_content("test", "text/plain");
  8716. auto cert = req.peer_cert();
  8717. ASSERT_TRUE(static_cast<bool>(cert));
  8718. std::string common_name = cert.subject_cn();
  8719. EXPECT_EQ("Common Name", common_name);
  8720. });
  8721. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8722. auto se = detail::scope_exit([&] {
  8723. svr.stop();
  8724. t.join();
  8725. ASSERT_FALSE(svr.is_running());
  8726. });
  8727. svr.wait_until_ready();
  8728. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8729. client_encrypted_private_key_pass);
  8730. cli.enable_server_certificate_verification(false);
  8731. cli.set_connection_timeout(30);
  8732. auto res = cli.Get("/test");
  8733. ASSERT_TRUE(res);
  8734. ASSERT_EQ(StatusCode::OK_200, res->status);
  8735. }
  8736. TEST(SSLClientServerTest, ClientCertPresent) {
  8737. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8738. }
  8739. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8740. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8741. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8742. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8743. }
  8744. // PEM memory-based constructor tests (works with all TLS backends)
  8745. void PemMemoryClientCertPresent(
  8746. const std::string &client_cert_file,
  8747. const std::string &client_private_key_file,
  8748. const std::string &client_encrypted_private_key_pass = std::string()) {
  8749. // Read PEM files into memory
  8750. std::string server_cert_pem, server_key_pem;
  8751. std::string client_ca_pem;
  8752. std::string client_cert_pem, client_key_pem;
  8753. read_file(SERVER_CERT_FILE, server_cert_pem);
  8754. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8755. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8756. read_file(client_cert_file, client_cert_pem);
  8757. read_file(client_private_key_file, client_key_pem);
  8758. // Create server with PEM memory
  8759. SSLServer::PemMemory server_pem = {
  8760. server_cert_pem.c_str(),
  8761. server_cert_pem.size(),
  8762. server_key_pem.c_str(),
  8763. server_key_pem.size(),
  8764. client_ca_pem.c_str(),
  8765. client_ca_pem.size(),
  8766. nullptr // no password for server key
  8767. };
  8768. SSLServer svr(server_pem);
  8769. ASSERT_TRUE(svr.is_valid());
  8770. svr.Get("/test", [&](const Request &, Response &res) {
  8771. res.set_content("test", "text/plain");
  8772. });
  8773. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8774. auto se = detail::scope_exit([&] {
  8775. svr.stop();
  8776. t.join();
  8777. ASSERT_FALSE(svr.is_running());
  8778. });
  8779. svr.wait_until_ready();
  8780. // Create client with PEM memory
  8781. const char *password = client_encrypted_private_key_pass.empty()
  8782. ? nullptr
  8783. : client_encrypted_private_key_pass.c_str();
  8784. SSLClient::PemMemory client_pem = {
  8785. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8786. client_key_pem.size(), password};
  8787. SSLClient cli(HOST, PORT, client_pem);
  8788. cli.enable_server_certificate_verification(false);
  8789. cli.set_connection_timeout(30);
  8790. auto res = cli.Get("/test");
  8791. ASSERT_TRUE(res);
  8792. ASSERT_EQ(StatusCode::OK_200, res->status);
  8793. }
  8794. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8795. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8796. }
  8797. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8798. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8799. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8800. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8801. }
  8802. TEST(SSLClientServerTest, ClientCertMissing) {
  8803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8804. CLIENT_CA_CERT_DIR);
  8805. ASSERT_TRUE(svr.is_valid());
  8806. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8808. auto se = detail::scope_exit([&] {
  8809. svr.stop();
  8810. t.join();
  8811. ASSERT_FALSE(svr.is_running());
  8812. });
  8813. svr.wait_until_ready();
  8814. SSLClient cli(HOST, PORT);
  8815. cli.set_connection_timeout(30);
  8816. auto res = cli.Get("/test");
  8817. ASSERT_TRUE(!res);
  8818. // When client cert is missing and server requires it, connection fails
  8819. // Error type depends on backend implementation
  8820. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8821. res.error() == Error::SSLConnection);
  8822. // Verify backend error is captured
  8823. // Note: This test may have different error codes depending on the exact
  8824. // verification failure
  8825. EXPECT_NE(0UL, res.ssl_backend_error());
  8826. }
  8827. TEST(SSLClientServerTest, TrustDirOptional) {
  8828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8829. ASSERT_TRUE(svr.is_valid());
  8830. svr.Get("/test", [&](const Request &, Response &res) {
  8831. res.set_content("test", "text/plain");
  8832. });
  8833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8834. auto se = detail::scope_exit([&] {
  8835. svr.stop();
  8836. t.join();
  8837. ASSERT_FALSE(svr.is_running());
  8838. });
  8839. svr.wait_until_ready();
  8840. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8841. cli.enable_server_certificate_verification(false);
  8842. cli.set_connection_timeout(30);
  8843. auto res = cli.Get("/test");
  8844. ASSERT_TRUE(res);
  8845. ASSERT_EQ(StatusCode::OK_200, res->status);
  8846. }
  8847. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8848. class NoListenSSLServer : public SSLServer {
  8849. public:
  8850. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8851. const char *client_ca_cert_file_path,
  8852. const char *client_ca_cert_dir_path = nullptr)
  8853. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8854. client_ca_cert_dir_path),
  8855. stop_(false) {}
  8856. std::atomic_bool stop_;
  8857. private:
  8858. bool process_and_close_socket(socket_t /*sock*/) override {
  8859. // Don't create SSL context
  8860. while (!stop_.load()) {
  8861. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8862. }
  8863. return true;
  8864. }
  8865. };
  8866. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8867. CLIENT_CA_CERT_FILE);
  8868. ASSERT_TRUE(svr.is_valid());
  8869. svr.Get("/test", [&](const Request &, Response &res) {
  8870. res.set_content("test", "text/plain");
  8871. });
  8872. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8873. auto se = detail::scope_exit([&] {
  8874. svr.stop_ = true;
  8875. svr.stop();
  8876. t.join();
  8877. ASSERT_FALSE(svr.is_running());
  8878. });
  8879. svr.wait_until_ready();
  8880. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8881. cli.enable_server_certificate_verification(false);
  8882. cli.set_connection_timeout(1);
  8883. auto res = cli.Get("/test");
  8884. ASSERT_TRUE(!res);
  8885. EXPECT_EQ(Error::SSLConnection, res.error());
  8886. // Timeout results in WantRead error code (maps to backend-specific value)
  8887. EXPECT_NE(0, res.ssl_error());
  8888. }
  8889. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8890. // Test SSLServer with client certificate verification using the standard
  8891. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8893. CLIENT_CA_CERT_DIR);
  8894. ASSERT_TRUE(svr.is_valid());
  8895. svr.Get("/test", [&](const Request &req, Response &res) {
  8896. res.set_content("test", "text/plain");
  8897. auto cert = req.peer_cert();
  8898. ASSERT_TRUE(static_cast<bool>(cert));
  8899. auto common_name = cert.subject_cn();
  8900. EXPECT_EQ("Common Name", common_name);
  8901. });
  8902. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. t.join();
  8906. ASSERT_FALSE(svr.is_running());
  8907. });
  8908. svr.wait_until_ready();
  8909. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8910. cli.enable_server_certificate_verification(false);
  8911. cli.set_connection_timeout(30);
  8912. auto res = cli.Get("/test");
  8913. ASSERT_TRUE(res);
  8914. ASSERT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8917. // Verifies that wildcard matching and exact matching work consistently
  8918. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8919. using namespace httplib::tls;
  8920. // We need a running server to test against
  8921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8922. ASSERT_TRUE(svr.is_valid());
  8923. svr.Get("/test", [](const Request &, Response &res) {
  8924. res.set_content("ok", "text/plain");
  8925. });
  8926. thread t([&]() { svr.listen(HOST, PORT); });
  8927. auto se = detail::scope_exit([&] {
  8928. svr.stop();
  8929. t.join();
  8930. });
  8931. svr.wait_until_ready();
  8932. bool verify_callback_called = false;
  8933. bool verify_result_wrong = false;
  8934. SSLClient cli(HOST, PORT);
  8935. cli.enable_server_certificate_verification(true);
  8936. cli.set_ca_cert_path(CA_CERT_FILE);
  8937. cli.set_connection_timeout(5);
  8938. // Note: Test certificate has CN="Common Name", not "localhost"
  8939. bool verify_result_cn = false;
  8940. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8941. verify_callback_called = true;
  8942. if (!ctx.cert) return false;
  8943. // Test 1: "Common Name" should match (our test server cert CN)
  8944. verify_result_cn = ctx.check_hostname("Common Name");
  8945. // Test 2: wrong hostname should not match
  8946. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8947. return true; // Accept for the purpose of this test
  8948. });
  8949. auto res = cli.Get("/test");
  8950. // The request may succeed or fail depending on cert configuration
  8951. // but the callback should have been called
  8952. ASSERT_TRUE(verify_callback_called)
  8953. << "Verify callback should have been called";
  8954. // CN="Common Name" should match our test certificate
  8955. //
  8956. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  8957. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  8958. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  8959. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  8960. // <openssl/base.h>, which is included transitively when
  8961. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  8962. #if defined(OPENSSL_IS_BORINGSSL)
  8963. EXPECT_FALSE(verify_result_cn)
  8964. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  8965. #else
  8966. EXPECT_TRUE(verify_result_cn)
  8967. << "verify_hostname should match 'Common Name' (certificate CN)";
  8968. #endif
  8969. // Wrong hostname should not match
  8970. EXPECT_FALSE(verify_result_wrong)
  8971. << "verify_hostname should not match 'wronghost.example.com'";
  8972. }
  8973. #endif
  8974. // mbedTLS-specific callback constructor test
  8975. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8976. #ifdef CPPHTTPLIB_SSL_ENABLED
  8977. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8978. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8979. ASSERT_TRUE(svr.is_valid());
  8980. // Set up a handler to verify client certificate is present
  8981. bool client_cert_verified = false;
  8982. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8983. // Verify that client certificate was provided
  8984. client_cert_verified = true;
  8985. res.set_content("success", "text/plain");
  8986. });
  8987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8988. auto se = detail::scope_exit([&] {
  8989. svr.stop();
  8990. t.join();
  8991. ASSERT_FALSE(svr.is_running());
  8992. });
  8993. svr.wait_until_ready();
  8994. // Client with certificate
  8995. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8996. cli.enable_server_certificate_verification(false);
  8997. cli.set_connection_timeout(30);
  8998. auto res = cli.Get("/test");
  8999. ASSERT_TRUE(res);
  9000. ASSERT_EQ(StatusCode::OK_200, res->status);
  9001. ASSERT_TRUE(client_cert_verified);
  9002. EXPECT_EQ("success", res->body);
  9003. }
  9004. #endif
  9005. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9006. // backends
  9007. #ifdef CPPHTTPLIB_SSL_ENABLED
  9008. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9009. using namespace httplib::tls;
  9010. // Test that when client CA cert file is provided,
  9011. // the server properly requests and validates client certificates
  9012. // Create a server with client authentication
  9013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9014. ASSERT_TRUE(svr.is_valid());
  9015. bool handler_called = false;
  9016. svr.Get("/test", [&](const Request &req, Response &res) {
  9017. handler_called = true;
  9018. // Verify that a client certificate was provided
  9019. auto cert = req.peer_cert();
  9020. ASSERT_TRUE(static_cast<bool>(cert));
  9021. // Get the issuer name
  9022. std::string issuer_str = cert.issuer_name();
  9023. ASSERT_FALSE(issuer_str.empty());
  9024. // The client certificate should be issued by our test CA
  9025. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9026. res.set_content("authenticated", "text/plain");
  9027. });
  9028. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9029. auto se = detail::scope_exit([&] {
  9030. svr.stop();
  9031. t.join();
  9032. ASSERT_FALSE(svr.is_running());
  9033. });
  9034. svr.wait_until_ready();
  9035. // Connect with a client certificate issued by the CA
  9036. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9037. cli.enable_server_certificate_verification(false);
  9038. cli.set_connection_timeout(30);
  9039. auto res = cli.Get("/test");
  9040. ASSERT_TRUE(res);
  9041. ASSERT_EQ(StatusCode::OK_200, res->status);
  9042. ASSERT_TRUE(handler_called);
  9043. EXPECT_EQ("authenticated", res->body);
  9044. }
  9045. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9046. using namespace httplib::tls;
  9047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9048. ASSERT_TRUE(svr.is_valid());
  9049. svr.Get("/test", [](const Request &, Response &res) {
  9050. res.set_content("ok", "text/plain");
  9051. });
  9052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9053. auto se = detail::scope_exit([&] {
  9054. svr.stop();
  9055. t.join();
  9056. });
  9057. svr.wait_until_ready();
  9058. SSLClient cli(HOST, PORT);
  9059. cli.enable_server_certificate_verification(false);
  9060. cli.set_connection_timeout(30);
  9061. bool cert_checked = false;
  9062. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9063. if (ctx.cert) {
  9064. auto sans = ctx.sans();
  9065. // Test certificate may or may not have SANs - just verify the API
  9066. // works If SANs exist, verify the types are valid
  9067. for (const auto &san : sans) {
  9068. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9069. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9070. san.type == SanType::OTHER);
  9071. EXPECT_FALSE(san.value.empty());
  9072. }
  9073. cert_checked = true;
  9074. }
  9075. return true;
  9076. });
  9077. auto res = cli.Get("/test");
  9078. ASSERT_TRUE(res);
  9079. EXPECT_TRUE(cert_checked);
  9080. }
  9081. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9082. using namespace httplib::tls;
  9083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9084. ASSERT_TRUE(svr.is_valid());
  9085. svr.Get("/test", [](const Request &, Response &res) {
  9086. res.set_content("ok", "text/plain");
  9087. });
  9088. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9089. auto se = detail::scope_exit([&] {
  9090. svr.stop();
  9091. t.join();
  9092. });
  9093. svr.wait_until_ready();
  9094. SSLClient cli(HOST, PORT);
  9095. cli.enable_server_certificate_verification(false);
  9096. cli.set_connection_timeout(30);
  9097. bool validity_checked = false;
  9098. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9099. if (ctx.cert) {
  9100. time_t not_before = 0, not_after = 0;
  9101. bool result = ctx.validity(not_before, not_after);
  9102. EXPECT_TRUE(result);
  9103. // Verify that not_before < now < not_after for a valid cert
  9104. time_t now = time(nullptr);
  9105. EXPECT_LT(not_before, now);
  9106. EXPECT_GT(not_after, now);
  9107. validity_checked = true;
  9108. }
  9109. return true;
  9110. });
  9111. auto res = cli.Get("/test");
  9112. ASSERT_TRUE(res);
  9113. EXPECT_TRUE(validity_checked);
  9114. }
  9115. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9116. using namespace httplib::tls;
  9117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9118. ASSERT_TRUE(svr.is_valid());
  9119. svr.Get("/test", [](const Request &, Response &res) {
  9120. res.set_content("ok", "text/plain");
  9121. });
  9122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9123. auto se = detail::scope_exit([&] {
  9124. svr.stop();
  9125. t.join();
  9126. });
  9127. svr.wait_until_ready();
  9128. SSLClient cli(HOST, PORT);
  9129. cli.enable_server_certificate_verification(false);
  9130. cli.set_connection_timeout(30);
  9131. bool serial_checked = false;
  9132. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9133. if (ctx.cert) {
  9134. std::string serial = ctx.serial();
  9135. EXPECT_FALSE(serial.empty());
  9136. // Serial should be a hex string
  9137. for (char c : serial) {
  9138. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9139. (c >= 'a' && c <= 'f'));
  9140. }
  9141. serial_checked = true;
  9142. }
  9143. return true;
  9144. });
  9145. auto res = cli.Get("/test");
  9146. ASSERT_TRUE(res);
  9147. EXPECT_TRUE(serial_checked);
  9148. }
  9149. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9150. // Test 1: Valid CA file - no error should be recorded
  9151. {
  9152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9153. CLIENT_CA_CERT_FILE);
  9154. ASSERT_TRUE(svr.is_valid());
  9155. // With valid setup, last_ssl_error should be 0
  9156. EXPECT_EQ(0, svr.ssl_last_error());
  9157. }
  9158. // Test 2: Invalid CA file content
  9159. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9160. {
  9161. // Create a temporary file with completely invalid content
  9162. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9163. {
  9164. std::ofstream ofs(temp_invalid_ca);
  9165. ofs << "This is not a certificate file at all\n";
  9166. ofs << "Just plain text content\n";
  9167. }
  9168. // Create server with invalid CA file
  9169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9170. // Clean up temporary file
  9171. std::remove(temp_invalid_ca);
  9172. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9173. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9174. // Note: SSL_CTX_load_verify_locations typically fails first,
  9175. // but our error handling code path is still exercised
  9176. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9177. }
  9178. }
  9179. TEST(VerifyCallbackTest, VerifyContextFields) {
  9180. using namespace httplib::tls;
  9181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9182. ASSERT_TRUE(svr.is_valid());
  9183. svr.Get("/test", [](const Request &, Response &res) {
  9184. res.set_content("ok", "text/plain");
  9185. });
  9186. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9187. auto se = detail::scope_exit([&] {
  9188. svr.stop();
  9189. t.join();
  9190. });
  9191. svr.wait_until_ready();
  9192. SSLClient cli(HOST, PORT);
  9193. cli.enable_server_certificate_verification(false);
  9194. cli.set_connection_timeout(30);
  9195. int callback_count = 0;
  9196. bool saw_leaf_cert = false;
  9197. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9198. if (ctx.cert) {
  9199. callback_count++;
  9200. // We should see at least one certificate (the leaf)
  9201. std::string cn = ctx.subject_cn();
  9202. if (!cn.empty()) { saw_leaf_cert = true; }
  9203. // Verify context fields are populated
  9204. EXPECT_NE(ctx.session, nullptr);
  9205. EXPECT_GE(ctx.depth, 0);
  9206. }
  9207. return true;
  9208. });
  9209. auto res = cli.Get("/test");
  9210. ASSERT_TRUE(res);
  9211. EXPECT_GT(callback_count, 0);
  9212. EXPECT_TRUE(saw_leaf_cert);
  9213. }
  9214. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9215. using httplib::tls::TlsError;
  9216. // Test that verify_error_to_string returns empty for success
  9217. std::string success_str = TlsError::verify_error_to_string(0);
  9218. EXPECT_TRUE(success_str.empty());
  9219. // Test that verify_error_to_string returns non-empty for error codes
  9220. // Using a common error code (certificate expired)
  9221. std::string error_str =
  9222. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9223. EXPECT_FALSE(error_str.empty());
  9224. }
  9225. TEST(SessionVerifierTest, CertificateAccepted) {
  9226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9227. ASSERT_TRUE(svr.is_valid());
  9228. svr.Get("/test", [](const Request &, Response &res) {
  9229. res.set_content("ok", "text/plain");
  9230. });
  9231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9232. auto se = detail::scope_exit([&] {
  9233. svr.stop();
  9234. t.join();
  9235. });
  9236. svr.wait_until_ready();
  9237. SSLClient cli(HOST, PORT);
  9238. cli.enable_server_certificate_verification(false);
  9239. cli.set_connection_timeout(30);
  9240. bool callback_called = false;
  9241. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9242. EXPECT_NE(session, nullptr);
  9243. callback_called = true;
  9244. return SSLVerifierResponse::CertificateAccepted;
  9245. });
  9246. auto res = cli.Get("/test");
  9247. ASSERT_TRUE(res);
  9248. EXPECT_EQ(200, res->status);
  9249. EXPECT_TRUE(callback_called);
  9250. }
  9251. TEST(SessionVerifierTest, CertificateRejected) {
  9252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9253. ASSERT_TRUE(svr.is_valid());
  9254. svr.Get("/test", [](const Request &, Response &res) {
  9255. res.set_content("ok", "text/plain");
  9256. });
  9257. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9258. auto se = detail::scope_exit([&] {
  9259. svr.stop();
  9260. t.join();
  9261. });
  9262. svr.wait_until_ready();
  9263. SSLClient cli(HOST, PORT);
  9264. cli.enable_server_certificate_verification(false);
  9265. cli.set_connection_timeout(30);
  9266. bool callback_called = false;
  9267. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9268. EXPECT_NE(session, nullptr);
  9269. callback_called = true;
  9270. return SSLVerifierResponse::CertificateRejected;
  9271. });
  9272. auto res = cli.Get("/test");
  9273. EXPECT_FALSE(res);
  9274. EXPECT_TRUE(callback_called);
  9275. }
  9276. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9278. ASSERT_TRUE(svr.is_valid());
  9279. svr.Get("/test", [](const Request &, Response &res) {
  9280. res.set_content("ok", "text/plain");
  9281. });
  9282. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9283. auto se = detail::scope_exit([&] {
  9284. svr.stop();
  9285. t.join();
  9286. });
  9287. svr.wait_until_ready();
  9288. // NoDecisionMade with verification disabled should succeed (no default check)
  9289. SSLClient cli(HOST, PORT);
  9290. cli.enable_server_certificate_verification(false);
  9291. cli.set_connection_timeout(30);
  9292. bool callback_called = false;
  9293. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9294. EXPECT_NE(session, nullptr);
  9295. callback_called = true;
  9296. return SSLVerifierResponse::NoDecisionMade;
  9297. });
  9298. auto res = cli.Get("/test");
  9299. ASSERT_TRUE(res);
  9300. EXPECT_EQ(200, res->status);
  9301. EXPECT_TRUE(callback_called);
  9302. }
  9303. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9305. ASSERT_TRUE(svr.is_valid());
  9306. svr.Get("/test", [](const Request &, Response &res) {
  9307. res.set_content("ok", "text/plain");
  9308. });
  9309. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9310. auto se = detail::scope_exit([&] {
  9311. svr.stop();
  9312. t.join();
  9313. });
  9314. svr.wait_until_ready();
  9315. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9316. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9317. // so we only check that the request fails, not whether the callback was
  9318. // called.
  9319. SSLClient cli(HOST, PORT);
  9320. cli.enable_server_certificate_verification(true);
  9321. cli.set_connection_timeout(30);
  9322. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9323. EXPECT_NE(session, nullptr);
  9324. return SSLVerifierResponse::NoDecisionMade;
  9325. });
  9326. auto res = cli.Get("/test");
  9327. EXPECT_FALSE(res);
  9328. }
  9329. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9330. // Test SSL server using PemMemory constructor with client CA certificates
  9331. // Read PEM files
  9332. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9333. read_file(SERVER_CERT_FILE, server_cert_pem);
  9334. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9335. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9336. // Create SSLServer with PemMemory constructor including client CA
  9337. SSLServer::PemMemory server_pem = {
  9338. server_cert_pem.c_str(),
  9339. server_cert_pem.size(),
  9340. server_key_pem.c_str(),
  9341. server_key_pem.size(),
  9342. client_ca_pem.c_str(),
  9343. client_ca_pem.size(),
  9344. nullptr // no password for server key
  9345. };
  9346. SSLServer svr(server_pem);
  9347. ASSERT_TRUE(svr.is_valid());
  9348. // No SSL error should be recorded for valid setup
  9349. EXPECT_EQ(0, svr.ssl_last_error());
  9350. // Set up server endpoints
  9351. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9352. res.set_content("ok", "text/plain");
  9353. });
  9354. // Start server in a thread
  9355. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9356. svr.wait_until_ready();
  9357. // Connect with client certificate (using constructor with paths)
  9358. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9359. cli.enable_server_certificate_verification(false);
  9360. auto res = cli.Get("/test-pem-ca");
  9361. ASSERT_TRUE(res);
  9362. EXPECT_EQ(200, res->status);
  9363. EXPECT_EQ("ok", res->body);
  9364. svr.stop();
  9365. server_thread.join();
  9366. }
  9367. #endif
  9368. #ifdef _WIN32
  9369. TEST(CleanupTest, WSACleanup) {
  9370. int ret = WSACleanup();
  9371. ASSERT_EQ(0, ret);
  9372. }
  9373. #endif
  9374. #ifndef CPPHTTPLIB_SSL_ENABLED
  9375. TEST(NoSSLSupport, SimpleInterface) {
  9376. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9377. }
  9378. #endif
  9379. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9380. TEST(InvalidScheme, SimpleInterface) {
  9381. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9382. }
  9383. #endif
  9384. TEST(NoScheme, SimpleInterface) {
  9385. Client cli("yahoo.com:80");
  9386. ASSERT_TRUE(cli.is_valid());
  9387. }
  9388. TEST(SendAPI, SimpleInterface_Online) {
  9389. Client cli("http://yahoo.com");
  9390. Request req;
  9391. req.method = "GET";
  9392. req.path = "/";
  9393. auto res = cli.send(req);
  9394. ASSERT_TRUE(res);
  9395. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9396. }
  9397. TEST(SendAPI, WithParamsInRequest) {
  9398. Server svr;
  9399. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9400. EXPECT_TRUE(req.has_param("test"));
  9401. EXPECT_EQ("test_value", req.get_param_value("test"));
  9402. });
  9403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9404. auto se = detail::scope_exit([&] {
  9405. svr.stop();
  9406. t.join();
  9407. ASSERT_FALSE(svr.is_running());
  9408. });
  9409. svr.wait_until_ready();
  9410. Client cli(HOST, PORT);
  9411. {
  9412. Request req;
  9413. req.method = "GET";
  9414. req.path = "/";
  9415. req.params.emplace("test", "test_value");
  9416. auto res = cli.send(req);
  9417. ASSERT_TRUE(res);
  9418. }
  9419. {
  9420. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9421. ASSERT_TRUE(res);
  9422. }
  9423. }
  9424. TEST(ClientImplMethods, GetSocketTest) {
  9425. httplib::Server svr;
  9426. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9427. res.status = StatusCode::OK_200;
  9428. });
  9429. auto port = svr.bind_to_any_port("127.0.0.1");
  9430. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9431. auto se = detail::scope_exit([&] {
  9432. svr.stop();
  9433. thread.join();
  9434. ASSERT_FALSE(svr.is_running());
  9435. });
  9436. svr.wait_until_ready();
  9437. {
  9438. httplib::Client cli("127.0.0.1", port);
  9439. cli.set_keep_alive(true);
  9440. // Use the behavior of cpp-httplib of opening the connection
  9441. // only when the first request happens. If that changes,
  9442. // this test would be obsolete.
  9443. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9444. // This also implicitly tests the server. But other tests would fail much
  9445. // earlier than this one to be considered.
  9446. auto res = cli.Get("/");
  9447. ASSERT_TRUE(res);
  9448. EXPECT_EQ(StatusCode::OK_200, res->status);
  9449. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9450. }
  9451. }
  9452. #ifdef CPPHTTPLIB_SSL_ENABLED
  9453. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9454. Client cli("http://yahoo.com");
  9455. auto res = cli.Get("/");
  9456. ASSERT_TRUE(res);
  9457. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9458. cli.set_follow_location(true);
  9459. res = cli.Get("/");
  9460. ASSERT_TRUE(res);
  9461. EXPECT_EQ(StatusCode::OK_200, res->status);
  9462. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9463. }
  9464. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9465. Client cli("https://yahoo.com");
  9466. auto res = cli.Get("/");
  9467. ASSERT_TRUE(res);
  9468. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9469. cli.set_follow_location(true);
  9470. res = cli.Get("/");
  9471. ASSERT_TRUE(res);
  9472. EXPECT_EQ(StatusCode::OK_200, res->status);
  9473. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9474. }
  9475. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9476. Client cli("https://yahoo.com");
  9477. auto res = cli.Get("/");
  9478. ASSERT_TRUE(res);
  9479. ASSERT_FALSE(!res);
  9480. ASSERT_TRUE(res);
  9481. ASSERT_FALSE(res == nullptr);
  9482. ASSERT_TRUE(res != nullptr);
  9483. EXPECT_EQ(Error::Success, res.error());
  9484. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9485. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9486. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9487. cli.set_follow_location(true);
  9488. res = cli.Get("/");
  9489. ASSERT_TRUE(res);
  9490. EXPECT_EQ(Error::Success, res.error());
  9491. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9492. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9493. EXPECT_EQ(StatusCode::OK_200, res->status);
  9494. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9495. }
  9496. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9497. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9498. Client cli("https://cdnjs.cloudflare.com");
  9499. auto res =
  9500. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9501. ASSERT_TRUE(res);
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. EXPECT_EQ(287630U, res->body.size());
  9504. EXPECT_EQ("application/javascript; charset=utf-8",
  9505. res->get_header_value("Content-Type"));
  9506. }
  9507. #endif
  9508. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9509. #undef REDIR_HOST // Silence compiler warning
  9510. #define REDIR_HOST "https://httpbingo.org"
  9511. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9512. Client cli(REDIR_HOST);
  9513. cli.set_follow_location(true);
  9514. auto res =
  9515. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9516. ASSERT_TRUE(res);
  9517. EXPECT_EQ(StatusCode::OK_200, res->status);
  9518. }
  9519. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9520. Client cli(REDIR_HOST);
  9521. cli.set_follow_location(true);
  9522. Params params;
  9523. params.emplace("url", "http://example.com");
  9524. params.emplace("status_code", "302");
  9525. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9526. ASSERT_TRUE(res);
  9527. EXPECT_EQ(StatusCode::OK_200, res->status);
  9528. }
  9529. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9530. Client cli(REDIR_HOST);
  9531. cli.set_follow_location(true);
  9532. Params params;
  9533. params.emplace("url", "http://example.com");
  9534. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9535. ASSERT_TRUE(res);
  9536. EXPECT_EQ(StatusCode::OK_200, res->status);
  9537. }
  9538. TEST(HttpToHttpsRedirectTest, CertFile) {
  9539. auto ssl_port = PORT + 1;
  9540. Server svr;
  9541. ASSERT_TRUE(svr.is_valid());
  9542. svr.Get("/index", [&](const Request &, Response &res) {
  9543. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9544. "/index");
  9545. svr.stop();
  9546. });
  9547. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9548. ASSERT_TRUE(ssl_svr.is_valid());
  9549. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9550. res.set_content("test", "text/plain");
  9551. ssl_svr.stop();
  9552. });
  9553. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9554. thread t2 =
  9555. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9556. auto se = detail::scope_exit([&] {
  9557. t2.join();
  9558. t.join();
  9559. ASSERT_FALSE(svr.is_running());
  9560. });
  9561. svr.wait_until_ready();
  9562. ssl_svr.wait_until_ready();
  9563. Client cli("127.0.0.1", PORT);
  9564. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9565. cli.enable_server_certificate_verification(true);
  9566. cli.set_follow_location(true);
  9567. cli.set_connection_timeout(30);
  9568. auto res = cli.Get("/index");
  9569. ASSERT_TRUE(res);
  9570. ASSERT_EQ(StatusCode::OK_200, res->status);
  9571. }
  9572. TEST(SSLClientRedirectTest, CertFile) {
  9573. auto ssl_port = PORT + 1;
  9574. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9575. ASSERT_TRUE(ssl_svr1.is_valid());
  9576. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9577. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9578. "/index");
  9579. ssl_svr1.stop();
  9580. });
  9581. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9582. ASSERT_TRUE(ssl_svr2.is_valid());
  9583. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9584. res.set_content("test", "text/plain");
  9585. ssl_svr2.stop();
  9586. });
  9587. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9588. thread t2 =
  9589. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9590. auto se = detail::scope_exit([&] {
  9591. t2.join();
  9592. t.join();
  9593. ASSERT_FALSE(ssl_svr1.is_running());
  9594. });
  9595. ssl_svr1.wait_until_ready();
  9596. ssl_svr2.wait_until_ready();
  9597. SSLClient cli("127.0.0.1", PORT);
  9598. std::string cert;
  9599. read_file(SERVER_CERT2_FILE, cert);
  9600. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9601. cli.enable_server_certificate_verification(true);
  9602. cli.set_follow_location(true);
  9603. cli.set_connection_timeout(30);
  9604. auto res = cli.Get("/index");
  9605. ASSERT_TRUE(res);
  9606. ASSERT_EQ(StatusCode::OK_200, res->status);
  9607. }
  9608. #endif
  9609. #ifdef CPPHTTPLIB_SSL_ENABLED
  9610. // Test that set_ca_cert_store() skips system certs (consistent with
  9611. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9612. // should be trusted - system certs should NOT be loaded.
  9613. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9614. // Load a specific cert that is NOT a system CA cert
  9615. std::string cert;
  9616. read_file(SERVER_CERT2_FILE, cert);
  9617. SSLClient cli("google.com");
  9618. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9619. cli.enable_server_certificate_verification(true);
  9620. // This should FAIL because:
  9621. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9622. // 2. System certs should NOT be loaded when custom store is set
  9623. // If system certs WERE loaded, this would succeed
  9624. auto res = cli.Get("/");
  9625. ASSERT_FALSE(res);
  9626. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9627. }
  9628. TEST(MultipartFormDataTest, LargeData) {
  9629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9630. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9631. const ContentReader &content_reader) {
  9632. if (req.is_multipart_form_data()) {
  9633. std::vector<FormData> items;
  9634. content_reader(
  9635. [&](const FormData &file) {
  9636. items.push_back(file);
  9637. return true;
  9638. },
  9639. [&](const char *data, size_t data_length) {
  9640. items.back().content.append(data, data_length);
  9641. return true;
  9642. });
  9643. EXPECT_TRUE(std::string(items[0].name) == "document");
  9644. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9645. EXPECT_TRUE(items[0].filename == "2MB_data");
  9646. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9647. EXPECT_TRUE(items[1].name == "hello");
  9648. EXPECT_TRUE(items[1].content == "world");
  9649. EXPECT_TRUE(items[1].filename == "");
  9650. EXPECT_TRUE(items[1].content_type == "");
  9651. } else {
  9652. std::string body;
  9653. content_reader([&](const char *data, size_t data_length) {
  9654. body.append(data, data_length);
  9655. return true;
  9656. });
  9657. }
  9658. });
  9659. auto port = svr.bind_to_any_port(HOST);
  9660. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9661. auto se = detail::scope_exit([&] {
  9662. svr.stop();
  9663. t.join();
  9664. ASSERT_FALSE(svr.is_running());
  9665. });
  9666. svr.wait_until_ready();
  9667. {
  9668. std::string data(1024 * 1024 * 2, '.');
  9669. std::stringstream buffer;
  9670. buffer << data;
  9671. SSLClient cli(HOST, port);
  9672. cli.enable_server_certificate_verification(false);
  9673. UploadFormDataItems items{
  9674. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9675. {"hello", "world", "", ""},
  9676. };
  9677. auto res = cli.Post("/post", items);
  9678. ASSERT_TRUE(res);
  9679. ASSERT_EQ(StatusCode::OK_200, res->status);
  9680. }
  9681. }
  9682. TEST(MultipartFormDataTest, DataProviderItems) {
  9683. std::random_device seed_gen;
  9684. std::mt19937 random(seed_gen());
  9685. std::string rand1;
  9686. rand1.resize(1000);
  9687. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9688. std::string rand2;
  9689. rand2.resize(3000);
  9690. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9692. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9693. const ContentReader &content_reader) {
  9694. ASSERT_FALSE(req.is_multipart_form_data());
  9695. std::string body;
  9696. content_reader([&](const char *data, size_t data_length) {
  9697. body.append(data, data_length);
  9698. return true;
  9699. });
  9700. EXPECT_EQ(body, "");
  9701. });
  9702. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9703. const ContentReader &content_reader) {
  9704. ASSERT_TRUE(req.is_multipart_form_data());
  9705. std::vector<FormData> items;
  9706. content_reader(
  9707. [&](const FormData &file) {
  9708. items.push_back(file);
  9709. return true;
  9710. },
  9711. [&](const char *data, size_t data_length) {
  9712. items.back().content.append(data, data_length);
  9713. return true;
  9714. });
  9715. ASSERT_TRUE(items.size() == 2);
  9716. EXPECT_EQ(std::string(items[0].name), "name1");
  9717. EXPECT_EQ(items[0].content, "Testing123");
  9718. EXPECT_EQ(items[0].filename, "filename1");
  9719. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9720. EXPECT_EQ(items[1].name, "name2");
  9721. EXPECT_EQ(items[1].content, "Testing456");
  9722. EXPECT_EQ(items[1].filename, "");
  9723. EXPECT_EQ(items[1].content_type, "");
  9724. });
  9725. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9726. const ContentReader &content_reader) {
  9727. ASSERT_TRUE(req.is_multipart_form_data());
  9728. std::vector<FormData> items;
  9729. content_reader(
  9730. [&](const FormData &file) {
  9731. items.push_back(file);
  9732. return true;
  9733. },
  9734. [&](const char *data, size_t data_length) {
  9735. items.back().content.append(data, data_length);
  9736. return true;
  9737. });
  9738. ASSERT_TRUE(items.size() == 2);
  9739. EXPECT_EQ(items[0].name, "name3");
  9740. EXPECT_EQ(items[0].content, rand1);
  9741. EXPECT_EQ(items[0].filename, "filename3");
  9742. EXPECT_EQ(items[0].content_type, "");
  9743. EXPECT_EQ(items[1].name, "name4");
  9744. EXPECT_EQ(items[1].content, rand2);
  9745. EXPECT_EQ(items[1].filename, "filename4");
  9746. EXPECT_EQ(items[1].content_type, "");
  9747. });
  9748. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9749. const ContentReader &content_reader) {
  9750. ASSERT_TRUE(req.is_multipart_form_data());
  9751. std::vector<FormData> items;
  9752. content_reader(
  9753. [&](const FormData &file) {
  9754. items.push_back(file);
  9755. return true;
  9756. },
  9757. [&](const char *data, size_t data_length) {
  9758. items.back().content.append(data, data_length);
  9759. return true;
  9760. });
  9761. ASSERT_TRUE(items.size() == 4);
  9762. EXPECT_EQ(std::string(items[0].name), "name1");
  9763. EXPECT_EQ(items[0].content, "Testing123");
  9764. EXPECT_EQ(items[0].filename, "filename1");
  9765. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9766. EXPECT_EQ(items[1].name, "name2");
  9767. EXPECT_EQ(items[1].content, "Testing456");
  9768. EXPECT_EQ(items[1].filename, "");
  9769. EXPECT_EQ(items[1].content_type, "");
  9770. EXPECT_EQ(items[2].name, "name3");
  9771. EXPECT_EQ(items[2].content, rand1);
  9772. EXPECT_EQ(items[2].filename, "filename3");
  9773. EXPECT_EQ(items[2].content_type, "");
  9774. EXPECT_EQ(items[3].name, "name4");
  9775. EXPECT_EQ(items[3].content, rand2);
  9776. EXPECT_EQ(items[3].filename, "filename4");
  9777. EXPECT_EQ(items[3].content_type, "");
  9778. });
  9779. auto port = svr.bind_to_any_port("localhost");
  9780. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9781. auto se = detail::scope_exit([&] {
  9782. svr.stop();
  9783. t.join();
  9784. ASSERT_FALSE(svr.is_running());
  9785. });
  9786. svr.wait_until_ready();
  9787. {
  9788. SSLClient cli("localhost", port);
  9789. cli.enable_server_certificate_verification(false);
  9790. UploadFormDataItems items{
  9791. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9792. {"name2", "Testing456", "", ""}, // not a file
  9793. };
  9794. {
  9795. auto res = cli.Post("/post-none", {}, {}, {});
  9796. ASSERT_TRUE(res);
  9797. ASSERT_EQ(StatusCode::OK_200, res->status);
  9798. }
  9799. FormDataProviderItems providers;
  9800. {
  9801. auto res =
  9802. cli.Post("/post-items", {}, items, providers); // empty providers
  9803. ASSERT_TRUE(res);
  9804. ASSERT_EQ(StatusCode::OK_200, res->status);
  9805. }
  9806. providers.push_back({"name3",
  9807. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9808. // test the offset is given correctly at each step
  9809. if (!offset)
  9810. sink.os.write(rand1.data(), 30);
  9811. else if (offset == 30)
  9812. sink.os.write(rand1.data() + 30, 300);
  9813. else if (offset == 330)
  9814. sink.os.write(rand1.data() + 330, 670);
  9815. else if (offset == rand1.size())
  9816. sink.done();
  9817. return true;
  9818. },
  9819. "filename3",
  9820. {}});
  9821. providers.push_back({"name4",
  9822. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9823. // test the offset is given correctly at each step
  9824. if (!offset)
  9825. sink.os.write(rand2.data(), 2000);
  9826. else if (offset == 2000)
  9827. sink.os.write(rand2.data() + 2000, 1);
  9828. else if (offset == 2001)
  9829. sink.os.write(rand2.data() + 2001, 999);
  9830. else if (offset == rand2.size())
  9831. sink.done();
  9832. return true;
  9833. },
  9834. "filename4",
  9835. {}});
  9836. {
  9837. auto res = cli.Post("/post-providers", {}, {}, providers);
  9838. ASSERT_TRUE(res);
  9839. ASSERT_EQ(StatusCode::OK_200, res->status);
  9840. }
  9841. {
  9842. auto res = cli.Post("/post-both", {}, items, providers);
  9843. ASSERT_TRUE(res);
  9844. ASSERT_EQ(StatusCode::OK_200, res->status);
  9845. }
  9846. }
  9847. }
  9848. TEST(MultipartFormDataTest, BadHeader) {
  9849. Server svr;
  9850. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9851. res.set_content("ok", "text/plain");
  9852. });
  9853. thread t = thread([&] { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. ASSERT_FALSE(svr.is_running());
  9858. });
  9859. svr.wait_until_ready();
  9860. const std::string body =
  9861. "This is the preamble. It is to be ignored, though it\r\n"
  9862. "is a handy place for composition agents to include an\r\n"
  9863. "explanatory note to non-MIME conformant readers.\r\n"
  9864. "\r\n"
  9865. "\r\n"
  9866. "--simple boundary\r\n"
  9867. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9868. ": BAD...\r\n"
  9869. "\r\n"
  9870. "value1\r\n"
  9871. "--simple boundary\r\n"
  9872. "Content-Disposition: form-data; name=\"field2\"; "
  9873. "filename=\"example.txt\"\r\n"
  9874. "\r\n"
  9875. "value2\r\n"
  9876. "--simple boundary--\r\n"
  9877. "This is the epilogue. It is also to be ignored.\r\n";
  9878. std::string content_type =
  9879. R"(multipart/form-data; boundary="simple boundary")";
  9880. Client cli(HOST, PORT);
  9881. auto res = cli.Post("/post", body, content_type.c_str());
  9882. ASSERT_TRUE(res);
  9883. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9884. }
  9885. TEST(MultipartFormDataTest, WithPreamble) {
  9886. Server svr;
  9887. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9888. res.set_content("ok", "text/plain");
  9889. });
  9890. thread t = thread([&] { svr.listen(HOST, PORT); });
  9891. auto se = detail::scope_exit([&] {
  9892. svr.stop();
  9893. t.join();
  9894. ASSERT_FALSE(svr.is_running());
  9895. });
  9896. svr.wait_until_ready();
  9897. const std::string body =
  9898. "This is the preamble. It is to be ignored, though it\r\n"
  9899. "is a handy place for composition agents to include an\r\n"
  9900. "explanatory note to non-MIME conformant readers.\r\n"
  9901. "\r\n"
  9902. "\r\n"
  9903. "--simple boundary\r\n"
  9904. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9905. "\r\n"
  9906. "value1\r\n"
  9907. "--simple boundary\r\n"
  9908. "Content-Disposition: form-data; name=\"field2\"; "
  9909. "filename=\"example.txt\"\r\n"
  9910. "\r\n"
  9911. "value2\r\n"
  9912. "--simple boundary--\r\n"
  9913. "This is the epilogue. It is also to be ignored.\r\n";
  9914. std::string content_type =
  9915. R"(multipart/form-data; boundary="simple boundary")";
  9916. Client cli(HOST, PORT);
  9917. auto res = cli.Post("/post", body, content_type.c_str());
  9918. ASSERT_TRUE(res);
  9919. EXPECT_EQ(StatusCode::OK_200, res->status);
  9920. }
  9921. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9923. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9924. const ContentReader &content_reader) {
  9925. if (req.is_multipart_form_data()) {
  9926. std::vector<FormData> items;
  9927. content_reader(
  9928. [&](const FormData &file) {
  9929. items.push_back(file);
  9930. return true;
  9931. },
  9932. [&](const char *data, size_t data_length) {
  9933. items.back().content.append(data, data_length);
  9934. return true;
  9935. });
  9936. EXPECT_TRUE(std::string(items[0].name) == "document");
  9937. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9938. EXPECT_TRUE(items[0].filename == "2MB_data");
  9939. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9940. EXPECT_TRUE(items[1].name == "hello");
  9941. EXPECT_TRUE(items[1].content == "world");
  9942. EXPECT_TRUE(items[1].filename == "");
  9943. EXPECT_TRUE(items[1].content_type == "");
  9944. } else {
  9945. std::string body;
  9946. content_reader([&](const char *data, size_t data_length) {
  9947. body.append(data, data_length);
  9948. return true;
  9949. });
  9950. }
  9951. });
  9952. auto port = svr.bind_to_any_port("localhost");
  9953. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9954. auto se = detail::scope_exit([&] {
  9955. svr.stop();
  9956. t.join();
  9957. ASSERT_FALSE(svr.is_running());
  9958. });
  9959. svr.wait_until_ready();
  9960. {
  9961. std::string data(1024 * 1024 * 2, '.');
  9962. std::stringstream buffer;
  9963. buffer << data;
  9964. SSLClient cli("localhost", port);
  9965. cli.enable_server_certificate_verification(false);
  9966. UploadFormDataItems items{
  9967. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9968. {"hello", "world", "", ""},
  9969. };
  9970. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9971. ASSERT_TRUE(res);
  9972. ASSERT_EQ(StatusCode::OK_200, res->status);
  9973. }
  9974. }
  9975. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9976. std::string data(1024 * 1024 * 2, '&');
  9977. std::stringstream buffer;
  9978. buffer << data;
  9979. Client cli("https://localhost:8080");
  9980. UploadFormDataItems items{
  9981. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9982. {"hello", "world", "", ""},
  9983. };
  9984. for (const char &c : " \t\r\n") {
  9985. auto res =
  9986. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9987. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9988. ASSERT_FALSE(res);
  9989. }
  9990. }
  9991. TEST(MultipartFormDataTest, PutFormData) {
  9992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9993. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9994. const ContentReader &content_reader) {
  9995. if (req.is_multipart_form_data()) {
  9996. std::vector<FormData> items;
  9997. content_reader(
  9998. [&](const FormData &file) {
  9999. items.push_back(file);
  10000. return true;
  10001. },
  10002. [&](const char *data, size_t data_length) {
  10003. items.back().content.append(data, data_length);
  10004. return true;
  10005. });
  10006. EXPECT_TRUE(std::string(items[0].name) == "document");
  10007. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10008. EXPECT_TRUE(items[0].filename == "2MB_data");
  10009. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10010. EXPECT_TRUE(items[1].name == "hello");
  10011. EXPECT_TRUE(items[1].content == "world");
  10012. EXPECT_TRUE(items[1].filename == "");
  10013. EXPECT_TRUE(items[1].content_type == "");
  10014. } else {
  10015. std::string body;
  10016. content_reader([&](const char *data, size_t data_length) {
  10017. body.append(data, data_length);
  10018. return true;
  10019. });
  10020. }
  10021. });
  10022. auto port = svr.bind_to_any_port("localhost");
  10023. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10024. auto se = detail::scope_exit([&] {
  10025. svr.stop();
  10026. t.join();
  10027. ASSERT_FALSE(svr.is_running());
  10028. });
  10029. svr.wait_until_ready();
  10030. {
  10031. std::string data(1024 * 1024 * 2, '&');
  10032. std::stringstream buffer;
  10033. buffer << data;
  10034. SSLClient cli("localhost", port);
  10035. cli.enable_server_certificate_verification(false);
  10036. UploadFormDataItems items{
  10037. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10038. {"hello", "world", "", ""},
  10039. };
  10040. auto res = cli.Put("/put", items);
  10041. ASSERT_TRUE(res);
  10042. ASSERT_EQ(StatusCode::OK_200, res->status);
  10043. }
  10044. }
  10045. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10047. svr.Put("/put_customboundary",
  10048. [&](const Request &req, const Response & /*res*/,
  10049. const ContentReader &content_reader) {
  10050. if (req.is_multipart_form_data()) {
  10051. std::vector<FormData> items;
  10052. content_reader(
  10053. [&](const FormData &file) {
  10054. items.push_back(file);
  10055. return true;
  10056. },
  10057. [&](const char *data, size_t data_length) {
  10058. items.back().content.append(data, data_length);
  10059. return true;
  10060. });
  10061. EXPECT_TRUE(std::string(items[0].name) == "document");
  10062. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10063. EXPECT_TRUE(items[0].filename == "2MB_data");
  10064. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10065. EXPECT_TRUE(items[1].name == "hello");
  10066. EXPECT_TRUE(items[1].content == "world");
  10067. EXPECT_TRUE(items[1].filename == "");
  10068. EXPECT_TRUE(items[1].content_type == "");
  10069. } else {
  10070. std::string body;
  10071. content_reader([&](const char *data, size_t data_length) {
  10072. body.append(data, data_length);
  10073. return true;
  10074. });
  10075. }
  10076. });
  10077. auto port = svr.bind_to_any_port("localhost");
  10078. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10079. auto se = detail::scope_exit([&] {
  10080. svr.stop();
  10081. t.join();
  10082. ASSERT_FALSE(svr.is_running());
  10083. });
  10084. svr.wait_until_ready();
  10085. {
  10086. std::string data(1024 * 1024 * 2, '&');
  10087. std::stringstream buffer;
  10088. buffer << data;
  10089. SSLClient cli("localhost", port);
  10090. cli.enable_server_certificate_verification(false);
  10091. UploadFormDataItems items{
  10092. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10093. {"hello", "world", "", ""},
  10094. };
  10095. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10096. ASSERT_TRUE(res);
  10097. ASSERT_EQ(StatusCode::OK_200, res->status);
  10098. }
  10099. }
  10100. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10101. std::string data(1024 * 1024 * 2, '&');
  10102. std::stringstream buffer;
  10103. buffer << data;
  10104. Client cli("https://localhost:8080");
  10105. cli.enable_server_certificate_verification(false);
  10106. UploadFormDataItems items{
  10107. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10108. {"hello", "world", "", ""},
  10109. };
  10110. for (const char &c : " \t\r\n") {
  10111. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10112. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10113. ASSERT_FALSE(res);
  10114. }
  10115. }
  10116. TEST(MultipartFormDataTest, AlternateFilename) {
  10117. auto handled = false;
  10118. Server svr;
  10119. svr.Post("/test", [&](const Request &req, Response &res) {
  10120. ASSERT_EQ(2u, req.form.files.size());
  10121. ASSERT_EQ(1u, req.form.fields.size());
  10122. // Test files
  10123. const auto &file1 = req.form.get_file("file1");
  10124. ASSERT_EQ("file1", file1.name);
  10125. ASSERT_EQ("A.txt", file1.filename);
  10126. ASSERT_EQ("text/plain", file1.content_type);
  10127. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10128. const auto &file2 = req.form.get_file("file2");
  10129. ASSERT_EQ("file2", file2.name);
  10130. ASSERT_EQ("a.html", file2.filename);
  10131. ASSERT_EQ("text/html", file2.content_type);
  10132. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10133. file2.content);
  10134. // Test text field
  10135. const auto &text = req.form.get_field("text");
  10136. ASSERT_EQ("text default", text);
  10137. res.set_content("ok", "text/plain");
  10138. handled = true;
  10139. });
  10140. thread t = thread([&] { svr.listen(HOST, PORT); });
  10141. auto se = detail::scope_exit([&] {
  10142. svr.stop();
  10143. t.join();
  10144. ASSERT_FALSE(svr.is_running());
  10145. ASSERT_TRUE(handled);
  10146. });
  10147. svr.wait_until_ready();
  10148. auto req = "POST /test HTTP/1.1\r\n"
  10149. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10150. "Content-Length: 399\r\n"
  10151. "\r\n"
  10152. "----------\r\n"
  10153. "Content-Disposition: form-data; name=\"text\"\r\n"
  10154. "\r\n"
  10155. "text default\r\n"
  10156. "----------\r\n"
  10157. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10158. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10159. "Content-Type: text/plain\r\n"
  10160. "\r\n"
  10161. "Content of a.txt.\r\n"
  10162. "\r\n"
  10163. "----------\r\n"
  10164. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10165. "\"a.html\"\r\n"
  10166. "Content-Type: text/html\r\n"
  10167. "\r\n"
  10168. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10169. "\r\n"
  10170. "------------\r\n";
  10171. ASSERT_TRUE(send_request(1, req));
  10172. }
  10173. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10174. auto handled = false;
  10175. Server svr;
  10176. svr.Post("/test", [&](const Request &req, Response &res) {
  10177. // Case-insensitive "utf-8''" prefix with a long value
  10178. const auto &file = req.form.get_file("file1");
  10179. ASSERT_EQ("file1", file.name);
  10180. // 8000 chars exercises both the Content-Disposition parser and the
  10181. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10182. // Prior to the fix, std::regex_match on this header would cause O(N)
  10183. // stack recursion in libstdc++, leading to SIGSEGV.
  10184. std::string expected_filename(8000, 'A');
  10185. ASSERT_EQ(expected_filename, file.filename);
  10186. res.set_content("ok", "text/plain");
  10187. handled = true;
  10188. });
  10189. thread t = thread([&] { svr.listen(HOST, PORT); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. t.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. ASSERT_TRUE(handled);
  10195. });
  10196. svr.wait_until_ready();
  10197. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10198. // Regression test for GHSA-qq6v-r583-3h69
  10199. std::string long_filename(8000, 'A');
  10200. std::string body = "----------\r\n"
  10201. "Content-Disposition: form-data; name=\"file1\"; "
  10202. "filename*=\"Utf-8''" +
  10203. long_filename +
  10204. "\"\r\n"
  10205. "\r\n"
  10206. "hello\r\n"
  10207. "------------\r\n";
  10208. auto req = "POST /test HTTP/1.1\r\n"
  10209. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10210. "Content-Length: " +
  10211. std::to_string(body.size()) + "\r\n\r\n" + body;
  10212. ASSERT_TRUE(send_request(1, req));
  10213. }
  10214. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10215. auto handled = false;
  10216. Server svr;
  10217. svr.Post("/test", [&](const Request &req, Response &) {
  10218. ASSERT_EQ(2u, req.form.fields.size());
  10219. const auto &text1 = req.form.get_field("text1");
  10220. ASSERT_EQ("text1", text1);
  10221. const auto &text2 = req.form.get_field("text2");
  10222. ASSERT_EQ("text2", text2);
  10223. handled = true;
  10224. });
  10225. thread t = thread([&] { svr.listen(HOST, PORT); });
  10226. auto se = detail::scope_exit([&] {
  10227. svr.stop();
  10228. t.join();
  10229. ASSERT_FALSE(svr.is_running());
  10230. ASSERT_TRUE(handled);
  10231. });
  10232. svr.wait_until_ready();
  10233. auto req = "POST /test HTTP/1.1\r\n"
  10234. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10235. "Content-Length: 146\r\n"
  10236. "\r\n----------\r\n"
  10237. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10238. "\r\n"
  10239. "text1"
  10240. "\r\n----------\r\n"
  10241. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10242. "\r\n"
  10243. "text2"
  10244. "\r\n------------";
  10245. std::string response;
  10246. ASSERT_TRUE(send_request(1, req, &response));
  10247. ASSERT_EQ("200", response.substr(9, 3));
  10248. }
  10249. TEST(MultipartFormDataTest, ContentLength) {
  10250. auto handled = false;
  10251. Server svr;
  10252. svr.Post("/test", [&](const Request &req, Response &) {
  10253. ASSERT_EQ(2u, req.form.fields.size());
  10254. const auto &text1 = req.form.get_field("text1");
  10255. ASSERT_EQ("text1", text1);
  10256. const auto &text2 = req.form.get_field("text2");
  10257. ASSERT_EQ("text2", text2);
  10258. handled = true;
  10259. });
  10260. thread t = thread([&] { svr.listen(HOST, PORT); });
  10261. auto se = detail::scope_exit([&] {
  10262. svr.stop();
  10263. t.join();
  10264. ASSERT_FALSE(svr.is_running());
  10265. ASSERT_TRUE(handled);
  10266. });
  10267. svr.wait_until_ready();
  10268. auto req = "POST /test HTTP/1.1\r\n"
  10269. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10270. "Content-Length: 167\r\n"
  10271. "\r\n----------\r\n"
  10272. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10273. "Content-Length: 5\r\n"
  10274. "\r\n"
  10275. "text1"
  10276. "\r\n----------\r\n"
  10277. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10278. "\r\n"
  10279. "text2"
  10280. "\r\n------------\r\n";
  10281. std::string response;
  10282. ASSERT_TRUE(send_request(1, req, &response));
  10283. ASSERT_EQ("200", response.substr(9, 3));
  10284. }
  10285. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10286. auto handled = false;
  10287. Server svr;
  10288. svr.Post("/test", [&](const Request &req, Response &) {
  10289. ASSERT_EQ(2u, req.form.fields.size());
  10290. const auto &text1 = req.form.get_field("text1");
  10291. ASSERT_EQ("text1", text1);
  10292. // TODO: Add header access for text fields if needed
  10293. const auto &text2 = req.form.get_field("text2");
  10294. ASSERT_EQ("text2", text2);
  10295. // TODO: Header access for text fields needs to be implemented
  10296. // auto &headers = it->second.headers;
  10297. // ASSERT_EQ(3U, headers.size());
  10298. // auto custom_header = headers.find("x-whatever");
  10299. // ASSERT_TRUE(custom_header != headers.end());
  10300. // ASSERT_NE("customvalue", custom_header->second);
  10301. // ASSERT_EQ("CustomValue", custom_header->second);
  10302. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10303. handled = true;
  10304. });
  10305. thread t = thread([&] { svr.listen(HOST, PORT); });
  10306. auto se = detail::scope_exit([&] {
  10307. svr.stop();
  10308. t.join();
  10309. ASSERT_FALSE(svr.is_running());
  10310. ASSERT_TRUE(handled);
  10311. });
  10312. svr.wait_until_ready();
  10313. auto req = "POST /test HTTP/1.1\r\n"
  10314. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10315. "Content-Length: 232\r\n"
  10316. "\r\n----------\r\n"
  10317. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10318. "Content-Length: 5\r\n"
  10319. "X-Test: 1\r\n"
  10320. "\r\n"
  10321. "text1"
  10322. "\r\n----------\r\n"
  10323. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10324. "Content-Type: text/plain\r\n"
  10325. "X-Whatever: CustomValue\r\n"
  10326. "\r\n"
  10327. "text2"
  10328. "\r\n------------\r\n"
  10329. "That should be disregarded. Not even read";
  10330. std::string response;
  10331. ASSERT_TRUE(send_request(1, req, &response));
  10332. ASSERT_EQ("200", response.substr(9, 3));
  10333. }
  10334. TEST(MultipartFormDataTest, LargeHeader) {
  10335. auto handled = false;
  10336. Server svr;
  10337. svr.Post("/test", [&](const Request &req, Response &) {
  10338. ASSERT_EQ(1u, req.form.fields.size());
  10339. const auto &text = req.form.get_field("name1");
  10340. ASSERT_EQ("text1", text);
  10341. handled = true;
  10342. });
  10343. thread t = thread([&] { svr.listen(HOST, PORT); });
  10344. auto se = detail::scope_exit([&] {
  10345. svr.stop();
  10346. t.join();
  10347. ASSERT_FALSE(svr.is_running());
  10348. ASSERT_TRUE(handled);
  10349. });
  10350. svr.wait_until_ready();
  10351. auto boundary = std::string("cpp-httplib-multipart-data");
  10352. std::string content = "--" + boundary +
  10353. "\r\n"
  10354. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10355. "\r\n"
  10356. "text1\r\n"
  10357. "--" +
  10358. boundary + "--\r\n";
  10359. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10360. "Content-Type: multipart/form-data;boundary=" +
  10361. boundary +
  10362. "\r\n"
  10363. "Content-Length: " +
  10364. std::to_string(content.size()) +
  10365. "\r\n"
  10366. "Dummy-Header: ";
  10367. std::string header_suffix = "\r\n"
  10368. "\r\n";
  10369. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10370. size_t header_dummy_size =
  10371. read_buff_size -
  10372. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10373. auto header_dummy = std::string(header_dummy_size, '@');
  10374. auto req = header_prefix + header_dummy + header_suffix + content;
  10375. std::string response;
  10376. ASSERT_TRUE(send_request(1, req, &response));
  10377. ASSERT_EQ("200", response.substr(9, 3));
  10378. }
  10379. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10380. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10381. // (not chunked Transfer-Encoding) after the streaming refactor.
  10382. auto handled = false;
  10383. Server svr;
  10384. svr.Post("/upload", [&](const Request &req, Response &res) {
  10385. auto cl_it = req.headers.find("Content-Length");
  10386. EXPECT_TRUE(cl_it != req.headers.end());
  10387. auto te_it = req.headers.find("Transfer-Encoding");
  10388. EXPECT_TRUE(te_it == req.headers.end());
  10389. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10390. res.set_content("ok", "text/plain");
  10391. handled = true;
  10392. });
  10393. auto port = svr.bind_to_any_port(HOST);
  10394. auto t = thread([&] { svr.listen_after_bind(); });
  10395. auto se = detail::scope_exit([&] {
  10396. svr.stop();
  10397. t.join();
  10398. ASSERT_FALSE(svr.is_running());
  10399. ASSERT_TRUE(handled);
  10400. });
  10401. svr.wait_until_ready();
  10402. UploadFormDataItems items = {
  10403. {"field1", "hello", "", "text/plain"},
  10404. {"file1", "world", "test.txt", "application/octet-stream"},
  10405. };
  10406. Client cli(HOST, port);
  10407. auto res = cli.Post("/upload", {}, items);
  10408. ASSERT_TRUE(res);
  10409. EXPECT_EQ(StatusCode::OK_200, res->status);
  10410. }
  10411. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10412. // Verify that make_multipart_content_provider coalesces many small segments
  10413. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10414. constexpr size_t kItemCount = 1000;
  10415. UploadFormDataItems items;
  10416. items.reserve(kItemCount);
  10417. for (size_t i = 0; i < kItemCount; i++) {
  10418. items.push_back(
  10419. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10420. }
  10421. const std::string boundary = "----test-boundary";
  10422. auto content_length = detail::get_multipart_content_length(items, boundary);
  10423. auto provider = detail::make_multipart_content_provider(items, boundary);
  10424. // Drive the provider the same way write_content_with_progress does
  10425. size_t write_count = 0;
  10426. size_t total_bytes = 0;
  10427. DataSink sink;
  10428. size_t offset = 0;
  10429. sink.write = [&](const char *d, size_t l) -> bool {
  10430. (void)d;
  10431. write_count++;
  10432. total_bytes += l;
  10433. offset += l;
  10434. return true;
  10435. };
  10436. sink.is_writable = []() -> bool { return true; };
  10437. while (offset < content_length) {
  10438. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10439. }
  10440. EXPECT_EQ(content_length, total_bytes);
  10441. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10442. // With buffering into 64KB blocks, write_count should be much smaller.
  10443. auto segment_count = 3 * kItemCount + 1;
  10444. EXPECT_LT(write_count, segment_count / 10);
  10445. }
  10446. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10447. // Integration test: send many UploadFormDataItems and verify the server
  10448. // receives all of them correctly (#2410).
  10449. constexpr size_t kItemCount = 500;
  10450. auto handled = false;
  10451. Server svr;
  10452. svr.Post("/upload", [&](const Request &req, Response &res) {
  10453. EXPECT_EQ(kItemCount, req.form.fields.size());
  10454. for (size_t i = 0; i < kItemCount; i++) {
  10455. auto key = "field" + std::to_string(i);
  10456. auto val = "value" + std::to_string(i);
  10457. auto it = req.form.fields.find(key);
  10458. if (it != req.form.fields.end()) {
  10459. EXPECT_EQ(val, it->second.content);
  10460. } else {
  10461. ADD_FAILURE() << "Missing field: " << key;
  10462. }
  10463. }
  10464. res.set_content("ok", "text/plain");
  10465. handled = true;
  10466. });
  10467. auto port = svr.bind_to_any_port(HOST);
  10468. auto t = thread([&] { svr.listen_after_bind(); });
  10469. auto se = detail::scope_exit([&] {
  10470. svr.stop();
  10471. t.join();
  10472. ASSERT_FALSE(svr.is_running());
  10473. ASSERT_TRUE(handled);
  10474. });
  10475. svr.wait_until_ready();
  10476. UploadFormDataItems items;
  10477. items.reserve(kItemCount);
  10478. for (size_t i = 0; i < kItemCount; i++) {
  10479. items.push_back(
  10480. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10481. }
  10482. Client cli(HOST, port);
  10483. auto res = cli.Post("/upload", items);
  10484. ASSERT_TRUE(res);
  10485. EXPECT_EQ(StatusCode::OK_200, res->status);
  10486. }
  10487. TEST(MultipartFormDataTest, MakeFileProvider) {
  10488. // Verify make_file_provider sends a file's contents correctly.
  10489. const std::string file_content(4096, 'Z');
  10490. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10491. {
  10492. std::ofstream ofs(tmp_path, std::ios::binary);
  10493. ofs.write(file_content.data(),
  10494. static_cast<std::streamsize>(file_content.size()));
  10495. }
  10496. auto handled = false;
  10497. Server svr;
  10498. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10499. const ContentReader &content_reader) {
  10500. ASSERT_TRUE(req.is_multipart_form_data());
  10501. std::vector<FormData> items;
  10502. content_reader(
  10503. [&](const FormData &file) {
  10504. items.push_back(file);
  10505. return true;
  10506. },
  10507. [&](const char *data, size_t data_length) {
  10508. items.back().content.append(data, data_length);
  10509. return true;
  10510. });
  10511. ASSERT_EQ(1u, items.size());
  10512. EXPECT_EQ("myfile", items[0].name);
  10513. EXPECT_EQ("data.bin", items[0].filename);
  10514. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10515. EXPECT_EQ(file_content, items[0].content);
  10516. handled = true;
  10517. });
  10518. auto port = svr.bind_to_any_port(HOST);
  10519. auto t = thread([&] { svr.listen_after_bind(); });
  10520. auto se = detail::scope_exit([&] {
  10521. svr.stop();
  10522. t.join();
  10523. ASSERT_FALSE(svr.is_running());
  10524. ASSERT_TRUE(handled);
  10525. std::remove(tmp_path.c_str());
  10526. });
  10527. svr.wait_until_ready();
  10528. FormDataProviderItems providers;
  10529. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10530. "application/octet-stream"));
  10531. Client cli(HOST, port);
  10532. auto res = cli.Post("/upload", {}, {}, providers);
  10533. ASSERT_TRUE(res);
  10534. EXPECT_EQ(StatusCode::OK_200, res->status);
  10535. }
  10536. TEST(MakeFileBodyTest, Basic) {
  10537. const std::string file_content(4096, 'Z');
  10538. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10539. {
  10540. std::ofstream ofs(tmp_path, std::ios::binary);
  10541. ofs.write(file_content.data(),
  10542. static_cast<std::streamsize>(file_content.size()));
  10543. }
  10544. auto handled = false;
  10545. Server svr;
  10546. svr.Post("/upload", [&](const Request &req, Response &res) {
  10547. EXPECT_EQ(file_content, req.body);
  10548. handled = true;
  10549. res.status = StatusCode::OK_200;
  10550. });
  10551. auto port = svr.bind_to_any_port(HOST);
  10552. auto t = thread([&] { svr.listen_after_bind(); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. t.join();
  10556. ASSERT_FALSE(svr.is_running());
  10557. ASSERT_TRUE(handled);
  10558. std::remove(tmp_path.c_str());
  10559. });
  10560. svr.wait_until_ready();
  10561. auto fb = make_file_body(tmp_path);
  10562. ASSERT_GT(fb.first, 0u);
  10563. Client cli(HOST, port);
  10564. auto res =
  10565. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10566. ASSERT_TRUE(res);
  10567. EXPECT_EQ(StatusCode::OK_200, res->status);
  10568. }
  10569. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10570. static constexpr unsigned int number_of_tasks{1000000};
  10571. std::atomic_uint count{0};
  10572. std::unique_ptr<TaskQueue> task_queue{
  10573. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10574. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10575. auto queued = task_queue->enqueue(
  10576. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10577. EXPECT_TRUE(queued);
  10578. }
  10579. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10580. task_queue->shutdown();
  10581. #else
  10582. EXPECT_NO_THROW(task_queue->shutdown());
  10583. #endif
  10584. EXPECT_EQ(number_of_tasks, count.load());
  10585. }
  10586. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10587. static constexpr unsigned int number_of_tasks{1000000};
  10588. static constexpr unsigned int qlimit{2};
  10589. unsigned int queued_count{0};
  10590. std::atomic_uint count{0};
  10591. std::unique_ptr<TaskQueue> task_queue{
  10592. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10593. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10594. if (task_queue->enqueue(
  10595. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10596. queued_count++;
  10597. }
  10598. }
  10599. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10600. task_queue->shutdown();
  10601. #else
  10602. EXPECT_NO_THROW(task_queue->shutdown());
  10603. #endif
  10604. EXPECT_EQ(queued_count, count.load());
  10605. EXPECT_TRUE(queued_count <= number_of_tasks);
  10606. EXPECT_TRUE(queued_count >= qlimit);
  10607. }
  10608. TEST(TaskQueueTest, MaxQueuedRequests) {
  10609. static constexpr unsigned int qlimit{3};
  10610. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10611. std::condition_variable sem_cv;
  10612. std::mutex sem_mtx;
  10613. int credits = 0;
  10614. bool queued;
  10615. /* Fill up the queue with tasks that will block until we give them credits to
  10616. * complete. */
  10617. for (unsigned int n = 0; n <= qlimit;) {
  10618. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10619. std::unique_lock<std::mutex> lock(sem_mtx);
  10620. while (credits <= 0) {
  10621. sem_cv.wait(lock);
  10622. }
  10623. /* Consume the credit and signal the test code if they are all gone. */
  10624. if (--credits == 0) { sem_cv.notify_one(); }
  10625. });
  10626. if (n < qlimit) {
  10627. /* The first qlimit enqueues must succeed. */
  10628. EXPECT_TRUE(queued);
  10629. } else {
  10630. /* The last one will succeed only when the worker thread
  10631. * starts and dequeues the first blocking task. Although
  10632. * not necessary for the correctness of this test, we sleep for
  10633. * a short while to avoid busy waiting. */
  10634. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10635. }
  10636. if (queued) { n++; }
  10637. }
  10638. /* Further enqueues must fail since the queue is full. */
  10639. for (auto i = 0; i < 4; i++) {
  10640. queued = task_queue->enqueue([] {});
  10641. EXPECT_FALSE(queued);
  10642. }
  10643. /* Give the credits to allow the previous tasks to complete. */
  10644. {
  10645. std::unique_lock<std::mutex> lock(sem_mtx);
  10646. credits += qlimit + 1;
  10647. }
  10648. sem_cv.notify_all();
  10649. /* Wait for all the credits to be consumed. */
  10650. {
  10651. std::unique_lock<std::mutex> lock(sem_mtx);
  10652. while (credits > 0) {
  10653. sem_cv.wait(lock);
  10654. }
  10655. }
  10656. /* Check that we are able again to enqueue at least qlimit tasks. */
  10657. for (unsigned int i = 0; i < qlimit; i++) {
  10658. queued = task_queue->enqueue([] {});
  10659. EXPECT_TRUE(queued);
  10660. }
  10661. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10662. task_queue->shutdown();
  10663. #else
  10664. EXPECT_NO_THROW(task_queue->shutdown());
  10665. #endif
  10666. }
  10667. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10668. Server svr;
  10669. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10670. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10671. });
  10672. svr.Get("/hello", [](const Request &req, Response &res) {
  10673. res.set_content(req.get_param_value("key"), "text/plain");
  10674. });
  10675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. thread.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. {
  10683. Client cli(HOST, PORT);
  10684. cli.set_follow_location(true);
  10685. auto res = cli.Get("/");
  10686. ASSERT_TRUE(res);
  10687. EXPECT_EQ(StatusCode::OK_200, res->status);
  10688. EXPECT_EQ("val&key2=val2", res->body);
  10689. }
  10690. }
  10691. #endif
  10692. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10693. Server svr;
  10694. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10695. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10696. });
  10697. svr.Get("/hello", [](const Request &req, Response &res) {
  10698. res.set_content(req.get_param_value("key"), "text/plain");
  10699. });
  10700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10701. auto se = detail::scope_exit([&] {
  10702. svr.stop();
  10703. thread.join();
  10704. ASSERT_FALSE(svr.is_running());
  10705. });
  10706. svr.wait_until_ready();
  10707. {
  10708. Client cli(HOST, PORT);
  10709. cli.set_follow_location(true);
  10710. auto res = cli.Get("/");
  10711. ASSERT_TRUE(res);
  10712. EXPECT_EQ(StatusCode::OK_200, res->status);
  10713. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10714. }
  10715. }
  10716. TEST(RedirectTest, RedirectWithPlusInPath) {
  10717. Server svr;
  10718. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10719. res.set_redirect("/a+b");
  10720. });
  10721. // Route pattern uses regex; escape + as \\+
  10722. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10723. res.set_content(req.path, "text/plain");
  10724. });
  10725. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10726. auto se = detail::scope_exit([&] {
  10727. svr.stop();
  10728. thread.join();
  10729. ASSERT_FALSE(svr.is_running());
  10730. });
  10731. svr.wait_until_ready();
  10732. {
  10733. Client cli(HOST, PORT);
  10734. cli.set_follow_location(true);
  10735. auto res = cli.Get("/");
  10736. ASSERT_TRUE(res);
  10737. EXPECT_EQ(StatusCode::OK_200, res->status);
  10738. EXPECT_EQ("/a+b", res->body);
  10739. }
  10740. }
  10741. #ifdef CPPHTTPLIB_SSL_ENABLED
  10742. TEST(RedirectTest, Issue2185_Online) {
  10743. SSLClient client("github.com");
  10744. client.set_follow_location(true);
  10745. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10746. "Coollab-Windows.zip");
  10747. ASSERT_TRUE(res);
  10748. EXPECT_EQ(StatusCode::OK_200, res->status);
  10749. EXPECT_EQ(9920427U, res->body.size());
  10750. }
  10751. #endif
  10752. TEST(VulnerabilityTest, CRLFInjection) {
  10753. Server svr;
  10754. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10755. res.set_content("Hello 1", "text/plain");
  10756. });
  10757. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10758. res.set_content("Hello 2", "text/plain");
  10759. });
  10760. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10761. res.set_content("Hello 3", "text/plain");
  10762. });
  10763. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10764. res.set_content("Hello 4", "text/plain");
  10765. });
  10766. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10767. for (const auto &x : req.headers) {
  10768. auto key = x.first;
  10769. EXPECT_STRNE("evil", key.c_str());
  10770. }
  10771. });
  10772. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10773. auto se = detail::scope_exit([&] {
  10774. svr.stop();
  10775. thread.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. svr.wait_until_ready();
  10779. {
  10780. Client cli(HOST, PORT);
  10781. cli.Post("/test1", "A=B",
  10782. "application/x-www-form-urlencoded\r\nevil: hello1");
  10783. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10784. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10785. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10786. }
  10787. }
  10788. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10789. auto server_thread = std::thread([] {
  10790. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10791. default_socket_options(srv);
  10792. sockaddr_in addr{};
  10793. addr.sin_family = AF_INET;
  10794. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10795. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10796. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10797. ::listen(srv, 1);
  10798. sockaddr_in cli_addr{};
  10799. socklen_t cli_len = sizeof(cli_addr);
  10800. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10801. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10802. std::string buf_all;
  10803. char buf[2048];
  10804. ssize_t n;
  10805. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10806. buf_all.append(buf, static_cast<size_t>(n));
  10807. size_t pos;
  10808. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10809. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10810. auto e = request_block.find("\r\n");
  10811. if (e != std::string::npos) {
  10812. auto request_line = request_block.substr(0, e);
  10813. std::string msg =
  10814. "CRLF injection detected in request line: '" + request_line + "'";
  10815. EXPECT_FALSE(true) << msg;
  10816. }
  10817. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10818. ::send(cli,
  10819. #ifdef _WIN32
  10820. static_cast<const char *>(resp.c_str()),
  10821. static_cast<int>(resp.size()),
  10822. #else
  10823. resp.c_str(), resp.size(),
  10824. #endif
  10825. 0);
  10826. buf_all.erase(0, pos + 4);
  10827. }
  10828. }
  10829. detail::close_socket(cli);
  10830. detail::close_socket(srv);
  10831. });
  10832. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10833. auto cli = Client("127.0.0.1", PORT + 1);
  10834. auto headers = Headers{
  10835. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10836. {"Connection", "keep-alive"}};
  10837. auto res = cli.Get("/hi", headers);
  10838. EXPECT_FALSE(res);
  10839. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10840. server_thread.join();
  10841. }
  10842. TEST(PathParamsTest, StaticMatch) {
  10843. const auto pattern = "/users/all";
  10844. detail::PathParamsMatcher matcher(pattern);
  10845. Request request;
  10846. request.path = "/users/all";
  10847. ASSERT_TRUE(matcher.match(request));
  10848. std::unordered_map<std::string, std::string> expected_params = {};
  10849. EXPECT_EQ(request.path_params, expected_params);
  10850. }
  10851. TEST(PathParamsTest, StaticMismatch) {
  10852. const auto pattern = "/users/all";
  10853. detail::PathParamsMatcher matcher(pattern);
  10854. Request request;
  10855. request.path = "/users/1";
  10856. ASSERT_FALSE(matcher.match(request));
  10857. }
  10858. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10859. const auto pattern = "/users/:id/subscriptions";
  10860. detail::PathParamsMatcher matcher(pattern);
  10861. Request request;
  10862. request.path = "/users/42/subscriptions";
  10863. ASSERT_TRUE(matcher.match(request));
  10864. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10865. EXPECT_EQ(request.path_params, expected_params);
  10866. }
  10867. TEST(PathParamsTest, SingleParamInTheEnd) {
  10868. const auto pattern = "/users/:id";
  10869. detail::PathParamsMatcher matcher(pattern);
  10870. Request request;
  10871. request.path = "/users/24";
  10872. ASSERT_TRUE(matcher.match(request));
  10873. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10874. EXPECT_EQ(request.path_params, expected_params);
  10875. }
  10876. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10877. const auto pattern = "/users/:id/";
  10878. detail::PathParamsMatcher matcher(pattern);
  10879. Request request;
  10880. request.path = "/users/42/";
  10881. ASSERT_TRUE(matcher.match(request));
  10882. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10883. EXPECT_EQ(request.path_params, expected_params);
  10884. }
  10885. TEST(PathParamsTest, EmptyParam) {
  10886. const auto pattern = "/users/:id/";
  10887. detail::PathParamsMatcher matcher(pattern);
  10888. Request request;
  10889. request.path = "/users//";
  10890. ASSERT_TRUE(matcher.match(request));
  10891. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10892. EXPECT_EQ(request.path_params, expected_params);
  10893. }
  10894. TEST(PathParamsTest, FragmentMismatch) {
  10895. const auto pattern = "/users/:id/";
  10896. detail::PathParamsMatcher matcher(pattern);
  10897. Request request;
  10898. request.path = "/admins/24/";
  10899. ASSERT_FALSE(matcher.match(request));
  10900. }
  10901. TEST(PathParamsTest, ExtraFragments) {
  10902. const auto pattern = "/users/:id";
  10903. detail::PathParamsMatcher matcher(pattern);
  10904. Request request;
  10905. request.path = "/users/42/subscriptions";
  10906. ASSERT_FALSE(matcher.match(request));
  10907. }
  10908. TEST(PathParamsTest, MissingTrailingParam) {
  10909. const auto pattern = "/users/:id";
  10910. detail::PathParamsMatcher matcher(pattern);
  10911. Request request;
  10912. request.path = "/users";
  10913. ASSERT_FALSE(matcher.match(request));
  10914. }
  10915. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10916. const auto pattern = "/users/:id/subscriptions";
  10917. detail::PathParamsMatcher matcher(pattern);
  10918. Request request;
  10919. request.path = "/users/subscriptions";
  10920. ASSERT_FALSE(matcher.match(request));
  10921. }
  10922. TEST(PathParamsTest, MultipleParams) {
  10923. const auto pattern = "/users/:userid/subscriptions/:subid";
  10924. detail::PathParamsMatcher matcher(pattern);
  10925. Request request;
  10926. request.path = "/users/42/subscriptions/2";
  10927. ASSERT_TRUE(matcher.match(request));
  10928. std::unordered_map<std::string, std::string> expected_params = {
  10929. {"userid", "42"}, {"subid", "2"}};
  10930. EXPECT_EQ(request.path_params, expected_params);
  10931. }
  10932. TEST(PathParamsTest, SequenceOfParams) {
  10933. const auto pattern = "/values/:x/:y/:z";
  10934. detail::PathParamsMatcher matcher(pattern);
  10935. Request request;
  10936. request.path = "/values/1/2/3";
  10937. ASSERT_TRUE(matcher.match(request));
  10938. std::unordered_map<std::string, std::string> expected_params = {
  10939. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10940. EXPECT_EQ(request.path_params, expected_params);
  10941. }
  10942. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10943. const auto pattern = "/prefix:suffix";
  10944. detail::PathParamsMatcher matcher(pattern);
  10945. Request request;
  10946. request.path = "/prefix:suffix";
  10947. ASSERT_TRUE(matcher.match(request));
  10948. const std::unordered_map<std::string, std::string> expected_params = {};
  10949. EXPECT_EQ(request.path_params, expected_params);
  10950. }
  10951. TEST(ParseUrlTest, VariousPatterns) {
  10952. {
  10953. detail::UrlComponents uc;
  10954. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10955. EXPECT_EQ("http", uc.scheme);
  10956. EXPECT_EQ("example.com", uc.host);
  10957. EXPECT_EQ("8080", uc.port);
  10958. EXPECT_EQ("/path", uc.path);
  10959. EXPECT_EQ("?q=1", uc.query);
  10960. }
  10961. {
  10962. detail::UrlComponents uc;
  10963. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10964. EXPECT_EQ("https", uc.scheme);
  10965. EXPECT_EQ("example.com", uc.host);
  10966. EXPECT_TRUE(uc.port.empty());
  10967. EXPECT_EQ("/path", uc.path);
  10968. }
  10969. {
  10970. detail::UrlComponents uc;
  10971. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10972. EXPECT_EQ("::1", uc.host);
  10973. EXPECT_EQ("8080", uc.port);
  10974. EXPECT_EQ("/path", uc.path);
  10975. }
  10976. {
  10977. detail::UrlComponents uc;
  10978. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10979. }
  10980. {
  10981. detail::UrlComponents uc;
  10982. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10983. EXPECT_TRUE(uc.scheme.empty());
  10984. EXPECT_EQ("example.com", uc.host);
  10985. EXPECT_EQ("/path", uc.path);
  10986. EXPECT_EQ("?q=1", uc.query);
  10987. }
  10988. {
  10989. detail::UrlComponents uc;
  10990. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10991. EXPECT_TRUE(uc.host.empty());
  10992. EXPECT_EQ("/path", uc.path);
  10993. EXPECT_EQ("?q=1", uc.query);
  10994. }
  10995. {
  10996. detail::UrlComponents uc;
  10997. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10998. EXPECT_EQ("example.com", uc.host);
  10999. EXPECT_EQ("8080", uc.port);
  11000. }
  11001. {
  11002. // Unix socket path — must not be parsed as host
  11003. detail::UrlComponents uc;
  11004. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11005. EXPECT_TRUE(uc.host.empty());
  11006. }
  11007. {
  11008. detail::UrlComponents uc;
  11009. ASSERT_TRUE(detail::parse_url("", uc));
  11010. EXPECT_TRUE(uc.host.empty());
  11011. EXPECT_TRUE(uc.path.empty());
  11012. }
  11013. {
  11014. detail::UrlComponents uc;
  11015. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11016. }
  11017. {
  11018. detail::UrlComponents uc;
  11019. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11020. }
  11021. {
  11022. // Accepted by parse_url; callers restrict to http/https
  11023. detail::UrlComponents uc;
  11024. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11025. EXPECT_EQ("ftp", uc.scheme);
  11026. }
  11027. {
  11028. detail::UrlComponents uc;
  11029. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11030. }
  11031. {
  11032. detail::UrlComponents uc;
  11033. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11034. }
  11035. }
  11036. TEST(ParseUrlTest, FragmentHandling) {
  11037. {
  11038. detail::UrlComponents uc;
  11039. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11040. EXPECT_EQ("/path", uc.path);
  11041. EXPECT_TRUE(uc.query.empty());
  11042. }
  11043. {
  11044. detail::UrlComponents uc;
  11045. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11046. EXPECT_TRUE(uc.path.empty());
  11047. EXPECT_TRUE(uc.query.empty());
  11048. }
  11049. }
  11050. TEST(ParseUrlTest, UserinfoHandling) {
  11051. // Userinfo with @ but no colon — host includes @
  11052. detail::UrlComponents uc;
  11053. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11054. EXPECT_EQ("user@host.com", uc.host);
  11055. EXPECT_EQ("/path", uc.path);
  11056. }
  11057. TEST(ParseUrlTest, IPv6EdgeCases) {
  11058. {
  11059. detail::UrlComponents uc;
  11060. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11061. EXPECT_TRUE(uc.scheme.empty());
  11062. EXPECT_EQ("::1", uc.host);
  11063. EXPECT_EQ("8080", uc.port);
  11064. }
  11065. {
  11066. // Zone ID '%25' is not in [a-fA-F0-9:]
  11067. detail::UrlComponents uc;
  11068. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11069. }
  11070. }
  11071. TEST(ParseUrlTest, SchemeEdgeCases) {
  11072. {
  11073. detail::UrlComponents uc;
  11074. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11075. }
  11076. {
  11077. detail::UrlComponents uc;
  11078. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11079. }
  11080. {
  11081. detail::UrlComponents uc;
  11082. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11083. }
  11084. }
  11085. TEST(ParseUrlTest, PortEdgeCases) {
  11086. {
  11087. detail::UrlComponents uc;
  11088. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11089. EXPECT_TRUE(uc.port.empty());
  11090. EXPECT_EQ("/path", uc.path);
  11091. }
  11092. {
  11093. // parse_url accepts any port string; validation is done by parse_port
  11094. detail::UrlComponents uc;
  11095. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11096. EXPECT_EQ("abc", uc.port);
  11097. }
  11098. }
  11099. TEST(ParseUrlTest, WebSocketPatterns) {
  11100. {
  11101. detail::UrlComponents uc;
  11102. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11103. EXPECT_EQ("ws", uc.scheme);
  11104. EXPECT_EQ("echo.example.com", uc.host);
  11105. EXPECT_EQ("8080", uc.port);
  11106. EXPECT_EQ("/ws", uc.path);
  11107. }
  11108. {
  11109. detail::UrlComponents uc;
  11110. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11111. EXPECT_EQ("wss", uc.scheme);
  11112. EXPECT_EQ("echo.example.com", uc.host);
  11113. EXPECT_TRUE(uc.port.empty());
  11114. EXPECT_EQ("/ws", uc.path);
  11115. }
  11116. }
  11117. TEST(ParseUrlTest, QueryOnly) {
  11118. detail::UrlComponents uc;
  11119. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11120. EXPECT_TRUE(uc.host.empty());
  11121. EXPECT_TRUE(uc.path.empty());
  11122. EXPECT_EQ("?q=1&r=2", uc.query);
  11123. }
  11124. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11125. detail::UrlComponents uc;
  11126. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11127. EXPECT_TRUE(uc.scheme.empty());
  11128. EXPECT_EQ("example.com", uc.host);
  11129. EXPECT_EQ("443", uc.port);
  11130. EXPECT_EQ("/path", uc.path);
  11131. }
  11132. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11133. // If ipv6 regex working, regex match codepath is taken.
  11134. // else port will default to 80 in Client impl
  11135. int clientImplMagicPort = 80;
  11136. int port = 4321;
  11137. // above ports must be different to avoid false negative
  11138. EXPECT_NE(clientImplMagicPort, port);
  11139. std::string ipV6TestURL = "http://[ff06::c3]";
  11140. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11141. CLIENT_PRIVATE_KEY_FILE);
  11142. EXPECT_EQ(cli.port(), port);
  11143. }
  11144. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11145. auto file_path = "./www/dir/index.html";
  11146. auto dir_path = "./www/dir";
  11147. detail::FileStat stat_file(file_path);
  11148. EXPECT_TRUE(stat_file.is_file());
  11149. EXPECT_FALSE(stat_file.is_dir());
  11150. detail::FileStat stat_dir(dir_path);
  11151. EXPECT_FALSE(stat_dir.is_file());
  11152. EXPECT_TRUE(stat_dir.is_dir());
  11153. }
  11154. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11155. // IPv4 with default HTTP port (80)
  11156. EXPECT_EQ("example.com",
  11157. detail::make_host_and_port_string("example.com", 80, false));
  11158. // IPv4 with default HTTPS port (443)
  11159. EXPECT_EQ("example.com",
  11160. detail::make_host_and_port_string("example.com", 443, true));
  11161. // IPv4 with non-default HTTP port
  11162. EXPECT_EQ("example.com:8080",
  11163. detail::make_host_and_port_string("example.com", 8080, false));
  11164. // IPv4 with non-default HTTPS port
  11165. EXPECT_EQ("example.com:8443",
  11166. detail::make_host_and_port_string("example.com", 8443, true));
  11167. // IPv6 with default HTTP port (80)
  11168. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11169. // IPv6 with default HTTPS port (443)
  11170. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11171. // IPv6 with non-default HTTP port
  11172. EXPECT_EQ("[::1]:8080",
  11173. detail::make_host_and_port_string("::1", 8080, false));
  11174. // IPv6 with non-default HTTPS port
  11175. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11176. // IPv6 full address with default port
  11177. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11178. detail::make_host_and_port_string(
  11179. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11180. // IPv6 full address with non-default port
  11181. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11182. detail::make_host_and_port_string(
  11183. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11184. // IPv6 localhost with non-default port
  11185. EXPECT_EQ("[::1]:3000",
  11186. detail::make_host_and_port_string("::1", 3000, false));
  11187. // IPv6 with zone ID (link-local address) with default port
  11188. EXPECT_EQ("[fe80::1%eth0]",
  11189. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11190. // IPv6 with zone ID (link-local address) with non-default port
  11191. EXPECT_EQ("[fe80::1%eth0]:8080",
  11192. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11193. // Edge case: Port 443 with is_ssl=false (should add port)
  11194. EXPECT_EQ("example.com:443",
  11195. detail::make_host_and_port_string("example.com", 443, false));
  11196. // Edge case: Port 80 with is_ssl=true (should add port)
  11197. EXPECT_EQ("example.com:80",
  11198. detail::make_host_and_port_string("example.com", 80, true));
  11199. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11200. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11201. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11202. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11203. // Security fix: Already bracketed IPv6 should not get double brackets
  11204. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11205. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11206. EXPECT_EQ("[::1]:8080",
  11207. detail::make_host_and_port_string("[::1]", 8080, false));
  11208. EXPECT_EQ("[2001:db8::1]:8080",
  11209. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11210. EXPECT_EQ("[fe80::1%eth0]",
  11211. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11212. EXPECT_EQ("[fe80::1%eth0]:8080",
  11213. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11214. // Edge case: Empty host (should return as-is)
  11215. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11216. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11217. // This is a known limitation but shouldn't crash
  11218. EXPECT_EQ("[host:name]",
  11219. detail::make_host_and_port_string("host:name", 80, false));
  11220. // Port number edge cases (no validation, but should not crash)
  11221. EXPECT_EQ("example.com:0",
  11222. detail::make_host_and_port_string("example.com", 0, false));
  11223. EXPECT_EQ("example.com:-1",
  11224. detail::make_host_and_port_string("example.com", -1, false));
  11225. EXPECT_EQ("example.com:65535",
  11226. detail::make_host_and_port_string("example.com", 65535, false));
  11227. EXPECT_EQ("example.com:65536",
  11228. detail::make_host_and_port_string("example.com", 65536, false));
  11229. }
  11230. #ifdef CPPHTTPLIB_SSL_ENABLED
  11231. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11232. httplib::SSLClient cli("roblox.com", 443);
  11233. cli.set_follow_location(true);
  11234. auto res = cli.Get("/");
  11235. ASSERT_TRUE(res);
  11236. EXPECT_EQ(StatusCode::OK_200, res->status);
  11237. }
  11238. #endif
  11239. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11240. Server svr;
  11241. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11242. EXPECT_EQ(res.status, 400);
  11243. });
  11244. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11245. auto se = detail::scope_exit([&] {
  11246. svr.stop();
  11247. thread.join();
  11248. ASSERT_FALSE(svr.is_running());
  11249. });
  11250. svr.wait_until_ready();
  11251. Client cli(HOST, PORT);
  11252. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11253. }
  11254. TEST(InvalidHeaderCharsTest, is_field_name) {
  11255. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11256. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11257. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11258. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11259. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11260. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11261. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11262. EXPECT_FALSE(detail::fields::is_field_name(""));
  11263. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11264. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11265. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11266. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11267. }
  11268. TEST(InvalidHeaderCharsTest, is_field_value) {
  11269. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11270. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11271. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11272. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11273. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11274. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11275. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11276. EXPECT_TRUE(detail::fields::is_field_value(""));
  11277. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11278. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11279. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11280. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11281. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11282. }
  11283. TEST(InvalidHeaderCharsTest, OnServer) {
  11284. Server svr;
  11285. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11286. std::string header = "Not Set";
  11287. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11288. res.set_header(header, "value");
  11289. res.set_content("Page Content Page Content", "text/plain");
  11290. });
  11291. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11292. std::string header = "Not Set";
  11293. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11294. res.set_header("X-Test", header);
  11295. res.set_content("Page Content Page Content", "text/plain");
  11296. });
  11297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. Client cli(HOST, PORT);
  11305. {
  11306. auto res = cli.Get(
  11307. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11308. ASSERT_TRUE(res);
  11309. EXPECT_EQ("Page Content Page Content", res->body);
  11310. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11311. }
  11312. {
  11313. auto res = cli.Get(
  11314. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11315. ASSERT_TRUE(res);
  11316. EXPECT_EQ("Page Content Page Content", res->body);
  11317. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11318. }
  11319. }
  11320. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11321. auto handled = false;
  11322. Server svr;
  11323. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11324. thread t = thread([&] { svr.listen(HOST, PORT); });
  11325. auto se = detail::scope_exit([&] {
  11326. svr.stop();
  11327. t.join();
  11328. ASSERT_FALSE(svr.is_running());
  11329. ASSERT_FALSE(handled);
  11330. });
  11331. svr.wait_until_ready();
  11332. auto req = "POST /test HTTP/1.1\r\n"
  11333. "Content-Length: x\r\n"
  11334. "\r\n";
  11335. std::string response;
  11336. ASSERT_TRUE(send_request(1, req, &response));
  11337. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11338. response.substr(0, response.find("\r\n")));
  11339. }
  11340. #ifndef _WIN32
  11341. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11342. static constexpr char reject[] = "Unauthorized";
  11343. static constexpr char accept[] = "Upload accepted";
  11344. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11345. Server svr;
  11346. svr.set_expect_100_continue_handler(
  11347. [](const Request & /*req*/, Response &res) {
  11348. res.status = StatusCode::Unauthorized_401;
  11349. res.set_content(reject, "text/plain");
  11350. return res.status;
  11351. });
  11352. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11353. res.set_content(accept, "text/plain");
  11354. });
  11355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11356. auto se = detail::scope_exit([&] {
  11357. svr.stop();
  11358. thread.join();
  11359. ASSERT_FALSE(svr.is_running());
  11360. });
  11361. svr.wait_until_ready();
  11362. {
  11363. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11364. curl_easy_init(), &curl_easy_cleanup};
  11365. ASSERT_NE(curl, nullptr);
  11366. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11367. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11368. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11369. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11370. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11371. &curl_slist_free_all};
  11372. ASSERT_NE(list, nullptr);
  11373. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11374. struct read_data {
  11375. size_t read_size;
  11376. size_t total_size;
  11377. } data = {0, total_size};
  11378. using read_callback_t =
  11379. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11380. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11381. void *userdata) -> size_t {
  11382. read_data *d = (read_data *)userdata;
  11383. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11384. std::fill_n(ptr, size * nmemb, 'A');
  11385. d->read_size += size * nmemb;
  11386. return size * nmemb;
  11387. };
  11388. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11389. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11390. std::vector<char> buffer;
  11391. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11392. using write_callback_t =
  11393. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11394. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11395. void *userdata) -> size_t {
  11396. std::vector<char> *buf = (std::vector<char> *)userdata;
  11397. buf->reserve(buf->size() + size * nmemb + 1);
  11398. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11399. return size * nmemb;
  11400. };
  11401. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11402. {
  11403. const auto res = curl_easy_perform(curl.get());
  11404. ASSERT_EQ(res, CURLE_OK);
  11405. }
  11406. {
  11407. auto response_code = long{};
  11408. const auto res =
  11409. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11410. ASSERT_EQ(res, CURLE_OK);
  11411. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11412. }
  11413. {
  11414. auto dl = curl_off_t{};
  11415. const auto res =
  11416. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11417. ASSERT_EQ(res, CURLE_OK);
  11418. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11419. }
  11420. {
  11421. buffer.push_back('\0');
  11422. ASSERT_STRCASEEQ(buffer.data(), reject);
  11423. }
  11424. }
  11425. }
  11426. #endif
  11427. template <typename S, typename C>
  11428. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11429. svr.Get("/stream", [&](const Request &, Response &res) {
  11430. auto data = new std::string("01234567890123456789");
  11431. res.set_content_provider(
  11432. data->size(), "text/plain",
  11433. [&, data](size_t offset, size_t length, DataSink &sink) {
  11434. const size_t DATA_CHUNK_SIZE = 4;
  11435. const auto &d = *data;
  11436. std::this_thread::sleep_for(std::chrono::seconds(1));
  11437. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11438. return true;
  11439. },
  11440. [data](bool success) {
  11441. EXPECT_FALSE(success);
  11442. delete data;
  11443. });
  11444. });
  11445. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11446. auto i = new size_t(0);
  11447. res.set_content_provider(
  11448. "text/plain",
  11449. [i](size_t, DataSink &sink) {
  11450. if (*i < 5) {
  11451. std::this_thread::sleep_for(std::chrono::seconds(1));
  11452. sink.write("abcd", 4);
  11453. (*i)++;
  11454. } else {
  11455. sink.done();
  11456. }
  11457. return true;
  11458. },
  11459. [i](bool success) {
  11460. EXPECT_FALSE(success);
  11461. delete i;
  11462. });
  11463. });
  11464. svr.Get("/chunked", [&](const Request &, Response &res) {
  11465. auto i = new size_t(0);
  11466. res.set_chunked_content_provider(
  11467. "text/plain",
  11468. [i](size_t, DataSink &sink) {
  11469. if (*i < 5) {
  11470. std::this_thread::sleep_for(std::chrono::seconds(1));
  11471. sink.os << "abcd";
  11472. (*i)++;
  11473. } else {
  11474. sink.done();
  11475. }
  11476. return true;
  11477. },
  11478. [i](bool success) {
  11479. EXPECT_FALSE(success);
  11480. delete i;
  11481. });
  11482. });
  11483. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11484. auto se = detail::scope_exit([&] {
  11485. svr.stop();
  11486. listen_thread.join();
  11487. ASSERT_FALSE(svr.is_running());
  11488. });
  11489. svr.wait_until_ready();
  11490. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11491. {
  11492. auto start = std::chrono::steady_clock::now();
  11493. auto res = cli.Get("/stream");
  11494. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11495. std::chrono::steady_clock::now() - start)
  11496. .count();
  11497. ASSERT_FALSE(res);
  11498. EXPECT_EQ(Error::Read, res.error());
  11499. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11500. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11501. }
  11502. {
  11503. auto start = std::chrono::steady_clock::now();
  11504. auto res = cli.Get("/stream_without_length");
  11505. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11506. std::chrono::steady_clock::now() - start)
  11507. .count();
  11508. ASSERT_FALSE(res);
  11509. EXPECT_EQ(Error::Read, res.error());
  11510. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11511. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11512. }
  11513. {
  11514. auto start = std::chrono::steady_clock::now();
  11515. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11516. EXPECT_EQ("abcd", string(data, data_length));
  11517. return true;
  11518. });
  11519. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11520. std::chrono::steady_clock::now() - start)
  11521. .count();
  11522. ASSERT_FALSE(res);
  11523. EXPECT_EQ(Error::Read, res.error());
  11524. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11525. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11526. }
  11527. }
  11528. TEST(MaxTimeoutTest, ContentStream) {
  11529. time_t timeout = 2000;
  11530. time_t threshold = 200;
  11531. Server svr;
  11532. Client cli("localhost", PORT);
  11533. max_timeout_test(svr, cli, timeout, threshold);
  11534. }
  11535. #ifdef CPPHTTPLIB_SSL_ENABLED
  11536. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11537. time_t timeout = 2000;
  11538. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11540. SSLClient cli("localhost", PORT);
  11541. cli.enable_server_certificate_verification(false);
  11542. max_timeout_test(svr, cli, timeout, threshold);
  11543. }
  11544. #endif
  11545. class EventDispatcher {
  11546. public:
  11547. EventDispatcher() {}
  11548. bool wait_event(DataSink *sink) {
  11549. unique_lock<mutex> lk(m_);
  11550. int id = id_;
  11551. // Wait with timeout to prevent hanging if client disconnects
  11552. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11553. [&] { return cid_ == id; })) {
  11554. return false; // Timeout occurred
  11555. }
  11556. sink->write(message_.data(), message_.size());
  11557. return true;
  11558. }
  11559. void send_event(const string &message) {
  11560. lock_guard<mutex> lk(m_);
  11561. cid_ = id_++;
  11562. message_ = message;
  11563. cv_.notify_all();
  11564. }
  11565. private:
  11566. mutex m_;
  11567. condition_variable cv_;
  11568. atomic_int id_{0};
  11569. atomic_int cid_{-1};
  11570. string message_;
  11571. };
  11572. TEST(ClientInThreadTest, Issue2068) {
  11573. EventDispatcher ed;
  11574. Server svr;
  11575. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11576. res.set_chunked_content_provider("text/event-stream",
  11577. [&](size_t /*offset*/, DataSink &sink) {
  11578. return ed.wait_event(&sink);
  11579. });
  11580. });
  11581. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11582. svr.wait_until_ready();
  11583. thread event_thread([&] {
  11584. int id = 0;
  11585. while (svr.is_running()) {
  11586. this_thread::sleep_for(chrono::milliseconds(500));
  11587. std::stringstream ss;
  11588. ss << "data: " << id << "\n\n";
  11589. ed.send_event(ss.str());
  11590. id++;
  11591. }
  11592. });
  11593. auto se = detail::scope_exit([&] {
  11594. svr.stop();
  11595. listen_thread.join();
  11596. event_thread.join();
  11597. ASSERT_FALSE(svr.is_running());
  11598. });
  11599. {
  11600. auto client = detail::make_unique<Client>(HOST, PORT);
  11601. client->set_read_timeout(std::chrono::minutes(10));
  11602. std::atomic<bool> stop{false};
  11603. std::thread t([&] {
  11604. client->Get("/event1",
  11605. [&](const char *, size_t) -> bool { return !stop; });
  11606. });
  11607. std::this_thread::sleep_for(std::chrono::seconds(2));
  11608. stop = true;
  11609. client->stop();
  11610. t.join();
  11611. // Reset client after thread has finished
  11612. client.reset();
  11613. }
  11614. }
  11615. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11616. auto handled = false;
  11617. Server svr;
  11618. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11619. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11620. auto se = detail::scope_exit([&] {
  11621. svr.stop();
  11622. t.join();
  11623. ASSERT_FALSE(svr.is_running());
  11624. ASSERT_FALSE(handled);
  11625. });
  11626. svr.wait_until_ready();
  11627. // Two Content-Length headers with different values — must be rejected
  11628. auto req = "POST /test HTTP/1.1\r\n"
  11629. "Content-Length: 5\r\n"
  11630. "Content-Length: 10\r\n"
  11631. "\r\n"
  11632. "hello";
  11633. std::string response;
  11634. ASSERT_TRUE(send_request(1, req, &response));
  11635. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11636. response.substr(0, response.find("\r\n")));
  11637. }
  11638. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11639. auto handled = false;
  11640. Server svr;
  11641. svr.Post("/test", [&](const Request &, Response &res) {
  11642. handled = true;
  11643. res.set_content("ok", "text/plain");
  11644. });
  11645. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11646. auto se = detail::scope_exit([&] {
  11647. svr.stop();
  11648. t.join();
  11649. ASSERT_FALSE(svr.is_running());
  11650. ASSERT_TRUE(handled);
  11651. });
  11652. svr.wait_until_ready();
  11653. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11654. auto req = "POST /test HTTP/1.1\r\n"
  11655. "Content-Length: 5\r\n"
  11656. "Content-Length: 5\r\n"
  11657. "\r\n"
  11658. "hello";
  11659. std::string response;
  11660. ASSERT_TRUE(send_request(1, req, &response));
  11661. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11662. }
  11663. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11664. Server svr;
  11665. svr.Get("/", [](const Request &req, Response &res) {
  11666. EXPECT_EQ(2U, req.trailers.size());
  11667. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11668. // Denied
  11669. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11670. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11671. // Accepted
  11672. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11673. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11674. EXPECT_TRUE(req.has_trailer("X-World"));
  11675. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11676. res.set_content("ok", "text/plain");
  11677. });
  11678. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11679. auto se = detail::scope_exit([&] {
  11680. svr.stop();
  11681. t.join();
  11682. ASSERT_FALSE(svr.is_running());
  11683. });
  11684. svr.wait_until_ready();
  11685. const std::string req = "GET / HTTP/1.1\r\n"
  11686. "Transfer-Encoding: chunked\r\n"
  11687. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11688. "\r\n"
  11689. "0\r\n"
  11690. "Content-Length: 10\r\n"
  11691. "Host: internal.local\r\n"
  11692. "Content-Type: malicious/content\r\n"
  11693. "Cookie: any\r\n"
  11694. "Set-Cookie: any\r\n"
  11695. "X-Forwarded-For: attacker.com\r\n"
  11696. "X-Real-Ip: 1.1.1.1\r\n"
  11697. "X-Hello: hello\r\n"
  11698. "X-World: world\r\n"
  11699. "\r\n";
  11700. std::string res;
  11701. ASSERT_TRUE(send_request(1, req, &res));
  11702. }
  11703. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11704. Server svr;
  11705. std::string observed_remote_addr;
  11706. std::string observed_xff;
  11707. svr.Get("/ip", [&](const Request &req, Response &res) {
  11708. observed_remote_addr = req.remote_addr;
  11709. observed_xff = req.get_header_value("X-Forwarded-For");
  11710. res.set_content("ok", "text/plain");
  11711. });
  11712. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11713. auto se = detail::scope_exit([&] {
  11714. svr.stop();
  11715. t.join();
  11716. ASSERT_FALSE(svr.is_running());
  11717. });
  11718. svr.wait_until_ready();
  11719. Client cli(HOST, PORT);
  11720. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11721. ASSERT_TRUE(res);
  11722. EXPECT_EQ(StatusCode::OK_200, res->status);
  11723. EXPECT_EQ(observed_xff, "203.0.113.66");
  11724. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11725. observed_remote_addr == "127.0.0.1");
  11726. }
  11727. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11728. Server svr;
  11729. svr.set_trusted_proxies({"203.0.113.66"});
  11730. std::string observed_remote_addr;
  11731. std::string observed_xff;
  11732. svr.Get("/ip", [&](const Request &req, Response &res) {
  11733. observed_remote_addr = req.remote_addr;
  11734. observed_xff = req.get_header_value("X-Forwarded-For");
  11735. res.set_content("ok", "text/plain");
  11736. });
  11737. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11738. auto se = detail::scope_exit([&] {
  11739. svr.stop();
  11740. t.join();
  11741. ASSERT_FALSE(svr.is_running());
  11742. });
  11743. svr.wait_until_ready();
  11744. Client cli(HOST, PORT);
  11745. auto res = cli.Get("/ip");
  11746. ASSERT_TRUE(res);
  11747. EXPECT_EQ(StatusCode::OK_200, res->status);
  11748. EXPECT_EQ(observed_xff, "");
  11749. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11750. observed_remote_addr == "127.0.0.1");
  11751. }
  11752. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11753. Server svr;
  11754. svr.set_trusted_proxies({"203.0.113.66"});
  11755. std::string observed_remote_addr;
  11756. std::string observed_xff;
  11757. svr.Get("/ip", [&](const Request &req, Response &res) {
  11758. observed_remote_addr = req.remote_addr;
  11759. observed_xff = req.get_header_value("X-Forwarded-For");
  11760. res.set_content("ok", "text/plain");
  11761. });
  11762. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11763. auto se = detail::scope_exit([&] {
  11764. svr.stop();
  11765. t.join();
  11766. ASSERT_FALSE(svr.is_running());
  11767. });
  11768. svr.wait_until_ready();
  11769. Client cli(HOST, PORT);
  11770. auto res =
  11771. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11772. ASSERT_TRUE(res);
  11773. EXPECT_EQ(StatusCode::OK_200, res->status);
  11774. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11775. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11776. }
  11777. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11778. Server svr;
  11779. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11780. std::string observed_remote_addr;
  11781. std::string observed_xff;
  11782. svr.Get("/ip", [&](const Request &req, Response &res) {
  11783. observed_remote_addr = req.remote_addr;
  11784. observed_xff = req.get_header_value("X-Forwarded-For");
  11785. res.set_content("ok", "text/plain");
  11786. });
  11787. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11788. auto se = detail::scope_exit([&] {
  11789. svr.stop();
  11790. t.join();
  11791. ASSERT_FALSE(svr.is_running());
  11792. });
  11793. svr.wait_until_ready();
  11794. Client cli(HOST, PORT);
  11795. auto res = cli.Get(
  11796. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11797. ASSERT_TRUE(res);
  11798. EXPECT_EQ(StatusCode::OK_200, res->status);
  11799. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11800. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11801. }
  11802. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11803. Server svr;
  11804. svr.set_trusted_proxies({"192.0.2.45"});
  11805. std::string observed_remote_addr;
  11806. std::string observed_xff;
  11807. svr.Get("/ip", [&](const Request &req, Response &res) {
  11808. observed_remote_addr = req.remote_addr;
  11809. observed_xff = req.get_header_value("X-Forwarded-For");
  11810. res.set_content("ok", "text/plain");
  11811. });
  11812. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11813. auto se = detail::scope_exit([&] {
  11814. svr.stop();
  11815. t.join();
  11816. ASSERT_FALSE(svr.is_running());
  11817. });
  11818. svr.wait_until_ready();
  11819. Client cli(HOST, PORT);
  11820. auto res =
  11821. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11822. ASSERT_TRUE(res);
  11823. EXPECT_EQ(StatusCode::OK_200, res->status);
  11824. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11825. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11826. }
  11827. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11828. Server svr;
  11829. svr.set_trusted_proxies({"192.0.2.45"});
  11830. std::string observed_remote_addr;
  11831. std::string observed_xff;
  11832. svr.Get("/ip", [&](const Request &req, Response &res) {
  11833. observed_remote_addr = req.remote_addr;
  11834. observed_xff = req.get_header_value("X-Forwarded-For");
  11835. res.set_content("ok", "text/plain");
  11836. });
  11837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11838. auto se = detail::scope_exit([&] {
  11839. svr.stop();
  11840. t.join();
  11841. ASSERT_FALSE(svr.is_running());
  11842. });
  11843. svr.wait_until_ready();
  11844. Client cli(HOST, PORT);
  11845. auto res = cli.Get(
  11846. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11847. ASSERT_TRUE(res);
  11848. EXPECT_EQ(StatusCode::OK_200, res->status);
  11849. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11850. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11851. }
  11852. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11853. Server svr;
  11854. svr.set_trusted_proxies({"192.0.2.45"});
  11855. std::string observed_remote_addr;
  11856. std::string observed_xff;
  11857. svr.Get("/ip", [&](const Request &req, Response &res) {
  11858. observed_remote_addr = req.remote_addr;
  11859. observed_xff = req.get_header_value("X-Forwarded-For");
  11860. res.set_content("ok", "text/plain");
  11861. });
  11862. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11863. auto se = detail::scope_exit([&] {
  11864. svr.stop();
  11865. t.join();
  11866. ASSERT_FALSE(svr.is_running());
  11867. });
  11868. svr.wait_until_ready();
  11869. std::string raw_req =
  11870. "GET /ip HTTP/1.1\r\n"
  11871. "Host: localhost\r\n"
  11872. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11873. "Connection: close\r\n"
  11874. "\r\n";
  11875. std::string out;
  11876. ASSERT_TRUE(send_request(5, raw_req, &out));
  11877. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11878. // Header parser trims surrounding whitespace of the header value
  11879. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11880. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11881. }
  11882. // An X-Forwarded-For header whose value parses to zero IP segments must not
  11883. // crash the server (it used to call front() on an empty vector inside
  11884. // get_client_ip). The connection-level remote address must be retained instead.
  11885. static void run_malformed_xff_test(const std::string &xff_value) {
  11886. Server svr;
  11887. svr.set_trusted_proxies({"192.0.2.45"});
  11888. std::string observed_remote_addr;
  11889. svr.Get("/ip", [&](const Request &req, Response &res) {
  11890. observed_remote_addr = req.remote_addr;
  11891. res.set_content("ok", "text/plain");
  11892. });
  11893. int port = 0;
  11894. thread t = thread([&]() {
  11895. port = svr.bind_to_any_port(HOST);
  11896. svr.listen_after_bind();
  11897. });
  11898. auto se = detail::scope_exit([&] {
  11899. svr.stop();
  11900. t.join();
  11901. ASSERT_FALSE(svr.is_running());
  11902. });
  11903. svr.wait_until_ready();
  11904. Client cli(HOST, port);
  11905. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  11906. ASSERT_TRUE(res);
  11907. EXPECT_EQ(StatusCode::OK_200, res->status);
  11908. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11909. observed_remote_addr == "127.0.0.1");
  11910. }
  11911. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  11912. run_malformed_xff_test("");
  11913. }
  11914. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  11915. run_malformed_xff_test(",");
  11916. }
  11917. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  11918. run_malformed_xff_test(", , ,");
  11919. }
  11920. #ifndef _WIN32
  11921. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11922. Server svr;
  11923. svr.Post("/post", [&](const Request &req, Response &res) {
  11924. res.set_content(req.body, "text/plain");
  11925. });
  11926. svr.Put("/put", [&](const Request &req, Response &res) {
  11927. res.set_content(req.body, "text/plain");
  11928. });
  11929. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11930. res.set_content(req.body, "text/plain");
  11931. });
  11932. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11933. res.set_content(req.body, "text/plain");
  11934. });
  11935. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11936. auto se = detail::scope_exit([&] {
  11937. svr.stop();
  11938. t.join();
  11939. ASSERT_FALSE(svr.is_running());
  11940. });
  11941. svr.wait_until_ready();
  11942. std::string resp;
  11943. // POST without Content-Length
  11944. ASSERT_TRUE(send_request(5,
  11945. "POST /post HTTP/1.1\r\n"
  11946. "Host: localhost\r\n"
  11947. "Connection: close\r\n"
  11948. "\r\n",
  11949. &resp));
  11950. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11951. // PUT without Content-Length
  11952. resp.clear();
  11953. ASSERT_TRUE(send_request(5,
  11954. "PUT /put HTTP/1.1\r\n"
  11955. "Host: localhost\r\n"
  11956. "Connection: close\r\n"
  11957. "\r\n",
  11958. &resp));
  11959. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11960. // PATCH without Content-Length
  11961. resp.clear();
  11962. ASSERT_TRUE(send_request(5,
  11963. "PATCH /patch HTTP/1.1\r\n"
  11964. "Host: localhost\r\n"
  11965. "Connection: close\r\n"
  11966. "\r\n",
  11967. &resp));
  11968. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11969. // DELETE without Content-Length
  11970. resp.clear();
  11971. ASSERT_TRUE(send_request(5,
  11972. "DELETE /delete HTTP/1.1\r\n"
  11973. "Host: localhost\r\n"
  11974. "Connection: close\r\n"
  11975. "\r\n",
  11976. &resp));
  11977. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11978. }
  11979. #endif
  11980. //==============================================================================
  11981. // open_stream() Tests
  11982. //==============================================================================
  11983. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11984. std::string result;
  11985. char buf[8192];
  11986. ssize_t n;
  11987. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11988. result.append(buf, static_cast<size_t>(n));
  11989. }
  11990. return result;
  11991. }
  11992. // Mock stream for unit tests
  11993. class MockStream : public Stream {
  11994. public:
  11995. std::string data;
  11996. size_t pos = 0;
  11997. ssize_t error_after = -1; // -1 = no error
  11998. explicit MockStream(const std::string &d, ssize_t err = -1)
  11999. : data(d), error_after(err) {}
  12000. bool is_readable() const override { return true; }
  12001. bool wait_readable() const override { return true; }
  12002. bool wait_writable() const override { return true; }
  12003. ssize_t read(char *ptr, size_t size) override {
  12004. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12005. if (pos >= data.size()) return 0;
  12006. size_t limit =
  12007. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12008. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12009. std::memcpy(ptr, data.data() + pos, to_read);
  12010. pos += to_read;
  12011. return static_cast<ssize_t>(to_read);
  12012. }
  12013. ssize_t write(const char *, size_t) override { return -1; }
  12014. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12015. ip = "127.0.0.1";
  12016. port = 0;
  12017. }
  12018. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12019. ip = "127.0.0.1";
  12020. port = 0;
  12021. }
  12022. socket_t socket() const override { return INVALID_SOCKET; }
  12023. time_t duration() const override { return 0; }
  12024. };
  12025. TEST(StreamHandleTest, Basic) {
  12026. ClientImpl::StreamHandle handle;
  12027. EXPECT_FALSE(handle.is_valid());
  12028. handle.response = detail::make_unique<Response>();
  12029. handle.error = Error::Connection;
  12030. EXPECT_FALSE(handle.is_valid());
  12031. handle.error = Error::Success;
  12032. EXPECT_TRUE(handle.is_valid());
  12033. }
  12034. TEST(BodyReaderTest, Basic) {
  12035. MockStream stream("Hello, World!");
  12036. detail::BodyReader reader;
  12037. reader.stream = &stream;
  12038. reader.content_length = 13;
  12039. char buf[32];
  12040. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12041. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12042. EXPECT_TRUE(reader.eof);
  12043. }
  12044. TEST(BodyReaderTest, NoStream) {
  12045. detail::BodyReader reader;
  12046. char buf[32];
  12047. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12048. EXPECT_EQ(Error::Connection, reader.last_error);
  12049. }
  12050. TEST(BodyReaderTest, Error) {
  12051. MockStream stream("Hello, World!", 5);
  12052. detail::BodyReader reader;
  12053. reader.stream = &stream;
  12054. reader.content_length = 13;
  12055. char buf[32];
  12056. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12057. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12058. EXPECT_EQ(Error::Read, reader.last_error);
  12059. }
  12060. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12061. // Mock-based StreamHandle tests relying on private internals are removed.
  12062. class OpenStreamTest : public ::testing::Test {
  12063. protected:
  12064. void SetUp() override {
  12065. svr_.Get("/hello", [](const Request &, Response &res) {
  12066. res.set_content("Hello World!", "text/plain");
  12067. });
  12068. svr_.Get("/large", [](const Request &, Response &res) {
  12069. res.set_content(std::string(10000, 'X'), "text/plain");
  12070. });
  12071. svr_.Get("/chunked", [](const Request &, Response &res) {
  12072. res.set_chunked_content_provider("text/plain",
  12073. [](size_t offset, DataSink &sink) {
  12074. if (offset < 15) {
  12075. sink.write("chunk", 5);
  12076. return true;
  12077. }
  12078. sink.done();
  12079. return true;
  12080. });
  12081. });
  12082. svr_.Get("/compressible", [](const Request &, Response &res) {
  12083. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12084. DataSink &sink) {
  12085. if (offset < 100 * 1024) {
  12086. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12087. sink.write(chunk.data(), chunk.size());
  12088. return true;
  12089. }
  12090. sink.done();
  12091. return true;
  12092. });
  12093. });
  12094. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12095. [](const Request & /*req*/, Response &res) {
  12096. auto i = new int(0);
  12097. res.set_header("Trailer", "Content-Length, X-Allowed");
  12098. res.set_chunked_content_provider(
  12099. "text/plain",
  12100. [i](size_t /*offset*/, DataSink &sink) {
  12101. switch (*i) {
  12102. case 0: sink.os << "123"; break;
  12103. case 1: sink.os << "456"; break;
  12104. case 2: sink.os << "789"; break;
  12105. case 3: {
  12106. sink.done_with_trailer(
  12107. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12108. } break;
  12109. }
  12110. (*i)++;
  12111. return true;
  12112. },
  12113. [i](bool success) {
  12114. EXPECT_TRUE(success);
  12115. delete i;
  12116. });
  12117. });
  12118. // Echo headers endpoint for header-related tests
  12119. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12120. std::string body;
  12121. for (const auto &h : req.headers) {
  12122. body.append(h.first);
  12123. body.push_back(':');
  12124. body.append(h.second);
  12125. body.push_back('\n');
  12126. }
  12127. res.set_content(body, "text/plain");
  12128. });
  12129. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12130. std::string body;
  12131. for (const auto &h : req.headers) {
  12132. body.append(h.first);
  12133. body.push_back(':');
  12134. body.append(h.second);
  12135. body.push_back('\n');
  12136. }
  12137. res.set_content(body, "text/plain");
  12138. });
  12139. port_ = svr_.bind_to_any_port("127.0.0.1");
  12140. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12141. svr_.wait_until_ready();
  12142. }
  12143. void TearDown() override {
  12144. svr_.stop();
  12145. if (thread_.joinable()) thread_.join();
  12146. }
  12147. Server svr_;
  12148. std::thread thread_;
  12149. int port_ = 0;
  12150. };
  12151. TEST_F(OpenStreamTest, Basic) {
  12152. Client cli("127.0.0.1", port_);
  12153. auto handle = cli.open_stream("GET", "/hello");
  12154. EXPECT_TRUE(handle.is_valid());
  12155. EXPECT_EQ("Hello World!", read_all(handle));
  12156. }
  12157. TEST_F(OpenStreamTest, SmallBuffer) {
  12158. Client cli("127.0.0.1", port_);
  12159. auto handle = cli.open_stream("GET", "/hello");
  12160. std::string result;
  12161. char buf[4];
  12162. ssize_t n;
  12163. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12164. result.append(buf, static_cast<size_t>(n));
  12165. EXPECT_EQ("Hello World!", result);
  12166. }
  12167. TEST_F(OpenStreamTest, DefaultHeaders) {
  12168. Client cli("127.0.0.1", port_);
  12169. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12170. {
  12171. auto handle = cli.open_stream("GET", "/echo-headers");
  12172. ASSERT_TRUE(handle.is_valid());
  12173. auto body = read_all(handle);
  12174. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12175. std::string::npos);
  12176. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12177. std::string::npos);
  12178. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12179. }
  12180. // open_stream POST with body and no explicit content_type should NOT add
  12181. // text/plain Content-Type (behavior differs from non-streaming path), but
  12182. // should include Content-Length
  12183. {
  12184. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12185. ASSERT_TRUE(handle.is_valid());
  12186. auto body = read_all(handle);
  12187. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12188. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12189. }
  12190. // open_stream POST with explicit Content-Type should preserve it
  12191. {
  12192. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12193. {{"Content-Type", "application/custom"}},
  12194. "{}", "application/custom");
  12195. ASSERT_TRUE(handle.is_valid());
  12196. auto body = read_all(handle);
  12197. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12198. }
  12199. // User-specified User-Agent must not be overwritten for stream API
  12200. {
  12201. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12202. {{"User-Agent", "MyAgent/1.2"}});
  12203. ASSERT_TRUE(handle.is_valid());
  12204. auto body = read_all(handle);
  12205. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12206. }
  12207. }
  12208. TEST_F(OpenStreamTest, Large) {
  12209. Client cli("127.0.0.1", port_);
  12210. auto handle = cli.open_stream("GET", "/large");
  12211. EXPECT_EQ(10000u, read_all(handle).size());
  12212. }
  12213. TEST_F(OpenStreamTest, ConnectionError) {
  12214. Client cli("127.0.0.1", 9999);
  12215. auto handle = cli.open_stream("GET", "/hello");
  12216. EXPECT_FALSE(handle.is_valid());
  12217. }
  12218. TEST_F(OpenStreamTest, Chunked) {
  12219. Client cli("127.0.0.1", port_);
  12220. auto handle = cli.open_stream("GET", "/chunked");
  12221. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12222. "Transfer-Encoding") == "chunked");
  12223. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12224. }
  12225. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12226. Client cli("127.0.0.1", port_);
  12227. auto handle =
  12228. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12229. ASSERT_TRUE(handle.is_valid());
  12230. // Consume body to allow trailers to be received/parsed
  12231. auto body = read_all(handle);
  12232. // Explicitly parse trailers (ensure trailers are available for assertion)
  12233. handle.parse_trailers_if_needed();
  12234. EXPECT_EQ(std::string("123456789"), body);
  12235. // The response should include a Trailer header declaring both names
  12236. ASSERT_TRUE(handle.response);
  12237. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12238. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12239. handle.response->get_header_value("Trailer"));
  12240. // Prohibited trailer must not be present
  12241. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12242. // Allowed trailer should be present
  12243. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12244. EXPECT_EQ(std::string("yes"),
  12245. handle.response->get_trailer_value("X-Allowed"));
  12246. // Verify trailers are NOT present as regular headers
  12247. EXPECT_EQ(std::string(""),
  12248. handle.response->get_header_value("Content-Length"));
  12249. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12250. }
  12251. static std::thread serve_single_response(std::promise<int> &port_promise,
  12252. const std::string &response) {
  12253. return std::thread([&port_promise, response] {
  12254. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12255. default_socket_options(srv);
  12256. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12257. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12258. sockaddr_in addr{};
  12259. addr.sin_family = AF_INET;
  12260. addr.sin_port = htons(0); // Let OS assign a free port
  12261. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12262. int opt = 1;
  12263. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12264. #ifdef _WIN32
  12265. reinterpret_cast<const char *>(&opt),
  12266. #else
  12267. &opt,
  12268. #endif
  12269. sizeof(opt));
  12270. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12271. ::listen(srv, 1) != 0) {
  12272. port_promise.set_value(-1);
  12273. detail::close_socket(srv);
  12274. return;
  12275. }
  12276. socklen_t addr_len = sizeof(addr);
  12277. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12278. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12279. sockaddr_in cli_addr{};
  12280. socklen_t cli_len = sizeof(cli_addr);
  12281. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12282. if (cli != INVALID_SOCKET) {
  12283. // Read the complete HTTP request (until the blank line that terminates
  12284. // headers) before sending the response. If the server closes the socket
  12285. // while the client's request data is still unread in the kernel receive
  12286. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12287. // connection on both sides: it discards the client's receive buffer
  12288. // (which already holds our response) and causes any in-progress write on
  12289. // the client to fail with ECONNRESET. Reading all request data first
  12290. // ensures close() emits a graceful FIN.
  12291. {
  12292. char rbuf[256];
  12293. std::string req;
  12294. while (req.find("\r\n\r\n") == std::string::npos) {
  12295. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12296. if (n <= 0) { break; }
  12297. req.append(rbuf, static_cast<size_t>(n));
  12298. }
  12299. }
  12300. ::send(cli,
  12301. #ifdef _WIN32
  12302. static_cast<const char *>(response.c_str()),
  12303. static_cast<int>(response.size()),
  12304. #else
  12305. response.c_str(), response.size(),
  12306. #endif
  12307. 0);
  12308. detail::close_socket(cli);
  12309. }
  12310. detail::close_socket(srv);
  12311. });
  12312. }
  12313. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12314. #ifndef _WIN32
  12315. signal(SIGPIPE, SIG_IGN);
  12316. #endif
  12317. std::promise<int> port_promise;
  12318. auto port_future = port_promise.get_future();
  12319. auto server_thread =
  12320. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12321. "Content-Type: text/plain\r\n"
  12322. "Content-Length: not-a-number\r\n"
  12323. "Connection: close\r\n"
  12324. "\r\n"
  12325. "hello");
  12326. auto port = port_future.get();
  12327. ASSERT_GT(port, 0);
  12328. Client cli("127.0.0.1", port);
  12329. auto handle = cli.open_stream("GET", "/");
  12330. EXPECT_FALSE(handle.is_valid());
  12331. server_thread.join();
  12332. }
  12333. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12334. #ifndef _WIN32
  12335. signal(SIGPIPE, SIG_IGN);
  12336. #endif
  12337. std::promise<int> port_promise;
  12338. auto port_future = port_promise.get_future();
  12339. auto server_thread = serve_single_response(
  12340. port_promise, "HTTP/1.1 200 OK\r\n"
  12341. "Content-Type: text/plain\r\n"
  12342. "Content-Length: 99999999999999999999999999\r\n"
  12343. "Connection: close\r\n"
  12344. "\r\n"
  12345. "hello");
  12346. auto port = port_future.get();
  12347. ASSERT_GT(port, 0);
  12348. // Before the fix, std::stoull would throw std::out_of_range here and
  12349. // crash the process. After the fix, strtoull silently clamps to
  12350. // ULLONG_MAX so the stream opens without crashing. The important thing
  12351. // is that the process does NOT terminate.
  12352. Client cli("127.0.0.1", port);
  12353. auto handle = cli.open_stream("GET", "/");
  12354. EXPECT_TRUE(handle.is_valid());
  12355. server_thread.join();
  12356. }
  12357. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12358. TEST_F(OpenStreamTest, Gzip) {
  12359. Client cli("127.0.0.1", port_);
  12360. auto handle = cli.open_stream("GET", "/compressible", {},
  12361. {{"Accept-Encoding", "gzip"}});
  12362. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12363. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12364. }
  12365. #endif
  12366. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12367. TEST_F(OpenStreamTest, Brotli) {
  12368. Client cli("127.0.0.1", port_);
  12369. auto handle =
  12370. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12371. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12372. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12373. }
  12374. #endif
  12375. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12376. TEST_F(OpenStreamTest, Zstd) {
  12377. Client cli("127.0.0.1", port_);
  12378. auto handle = cli.open_stream("GET", "/compressible", {},
  12379. {{"Accept-Encoding", "zstd"}});
  12380. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12381. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12382. }
  12383. #endif
  12384. #ifdef CPPHTTPLIB_SSL_ENABLED
  12385. class SSLOpenStreamTest : public ::testing::Test {
  12386. protected:
  12387. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12388. void SetUp() override {
  12389. svr_.Get("/hello", [](const Request &, Response &res) {
  12390. res.set_content("Hello SSL World!", "text/plain");
  12391. });
  12392. svr_.Get("/chunked", [](const Request &, Response &res) {
  12393. res.set_chunked_content_provider("text/plain",
  12394. [](size_t offset, DataSink &sink) {
  12395. if (offset < 15) {
  12396. sink.write("chunk", 5);
  12397. return true;
  12398. }
  12399. sink.done();
  12400. return true;
  12401. });
  12402. });
  12403. svr_.Post("/echo", [](const Request &req, Response &res) {
  12404. res.set_content(req.body, req.get_header_value("Content-Type"));
  12405. });
  12406. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12407. std::string body = req.body;
  12408. res.set_chunked_content_provider(
  12409. "text/plain", [body](size_t offset, DataSink &sink) {
  12410. if (offset < body.size()) {
  12411. sink.write(body.data() + offset, body.size() - offset);
  12412. }
  12413. sink.done();
  12414. return true;
  12415. });
  12416. });
  12417. port_ = svr_.bind_to_any_port("127.0.0.1");
  12418. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12419. svr_.wait_until_ready();
  12420. }
  12421. void TearDown() override {
  12422. svr_.stop();
  12423. if (thread_.joinable()) thread_.join();
  12424. }
  12425. SSLServer svr_;
  12426. std::thread thread_;
  12427. int port_ = 0;
  12428. };
  12429. TEST_F(SSLOpenStreamTest, Basic) {
  12430. SSLClient cli("127.0.0.1", port_);
  12431. cli.enable_server_certificate_verification(false);
  12432. auto handle = cli.open_stream("GET", "/hello");
  12433. ASSERT_TRUE(handle.is_valid());
  12434. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12435. }
  12436. TEST_F(SSLOpenStreamTest, Chunked) {
  12437. SSLClient cli("127.0.0.1", port_);
  12438. cli.enable_server_certificate_verification(false);
  12439. auto handle = cli.open_stream("GET", "/chunked");
  12440. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12441. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12442. "Transfer-Encoding") == "chunked");
  12443. auto body = read_all(handle);
  12444. EXPECT_EQ("chunkchunkchunk", body);
  12445. }
  12446. TEST_F(SSLOpenStreamTest, Post) {
  12447. SSLClient cli("127.0.0.1", port_);
  12448. cli.enable_server_certificate_verification(false);
  12449. auto handle =
  12450. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12451. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12452. EXPECT_EQ(200, handle.response->status);
  12453. auto body = read_all(handle);
  12454. EXPECT_EQ("Hello SSL POST", body);
  12455. }
  12456. TEST_F(SSLOpenStreamTest, PostChunked) {
  12457. SSLClient cli("127.0.0.1", port_);
  12458. cli.enable_server_certificate_verification(false);
  12459. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12460. "Chunked SSL Data", "text/plain");
  12461. ASSERT_TRUE(handle.is_valid());
  12462. EXPECT_EQ(200, handle.response->status);
  12463. auto body = read_all(handle);
  12464. EXPECT_EQ("Chunked SSL Data", body);
  12465. }
  12466. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12467. // Content-Length is terminated by the server closing the connection. When the
  12468. // SSL peer sends a close_notify after the body, the client must treat it as a
  12469. // clean EOF and return a successful response rather than an error.
  12470. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12472. ASSERT_TRUE(svr.is_valid());
  12473. svr.set_keep_alive_max_count(1);
  12474. const std::string expected_body = "Hello from connection-close response!";
  12475. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12476. res.set_content_provider("text/plain",
  12477. [&](size_t offset, DataSink &sink) -> bool {
  12478. if (offset < expected_body.size()) {
  12479. sink.write(expected_body.data() + offset,
  12480. expected_body.size() - offset);
  12481. }
  12482. sink.done();
  12483. return true;
  12484. });
  12485. });
  12486. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12487. auto se = detail::scope_exit([&] {
  12488. svr.stop();
  12489. listen_thread.join();
  12490. ASSERT_FALSE(svr.is_running());
  12491. });
  12492. svr.wait_until_ready();
  12493. SSLClient cli(HOST, PORT);
  12494. cli.enable_server_certificate_verification(false);
  12495. auto res = cli.Get("/no-content-length");
  12496. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12497. EXPECT_EQ(StatusCode::OK_200, res->status);
  12498. EXPECT_EQ(expected_body, res->body);
  12499. }
  12500. #endif // CPPHTTPLIB_SSL_ENABLED
  12501. //==============================================================================
  12502. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12503. // results for various scenarios.
  12504. //==============================================================================
  12505. TEST(ParityTest, GetVsOpenStream) {
  12506. Server svr;
  12507. const std::string path = "/parity";
  12508. const std::string content = "Parity test content: hello world";
  12509. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12510. res.set_content(content, "text/plain");
  12511. });
  12512. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12513. auto se = detail::scope_exit([&] {
  12514. svr.stop();
  12515. t.join();
  12516. ASSERT_FALSE(svr.is_running());
  12517. });
  12518. svr.wait_until_ready();
  12519. Client cli(HOST, PORT);
  12520. // Non-stream path
  12521. auto r1 = cli.Get(path);
  12522. ASSERT_TRUE(r1);
  12523. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12524. // Stream path
  12525. auto h = cli.open_stream("GET", path);
  12526. ASSERT_TRUE(h.is_valid());
  12527. EXPECT_EQ(r1->body, read_all(h));
  12528. }
  12529. // Helper to compress data with provided compressor type T
  12530. template <typename Compressor>
  12531. static std::string compress_payload_for_parity(const std::string &in) {
  12532. std::string out;
  12533. Compressor compressor;
  12534. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12535. [&](const char *data, size_t n) {
  12536. out.append(data, n);
  12537. return true;
  12538. });
  12539. EXPECT_TRUE(ok);
  12540. return out;
  12541. }
  12542. // Helper function for compression parity tests
  12543. template <typename Compressor>
  12544. static void test_compression_parity(const std::string &original,
  12545. const std::string &path,
  12546. const std::string &encoding) {
  12547. const std::string compressed =
  12548. compress_payload_for_parity<Compressor>(original);
  12549. Server svr;
  12550. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12551. res.set_content(compressed, "application/octet-stream");
  12552. res.set_header("Content-Encoding", encoding);
  12553. });
  12554. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12555. auto se = detail::scope_exit([&] {
  12556. svr.stop();
  12557. t.join();
  12558. ASSERT_FALSE(svr.is_running());
  12559. });
  12560. svr.wait_until_ready();
  12561. Client cli(HOST, PORT);
  12562. // Non-streaming
  12563. {
  12564. auto res = cli.Get(path);
  12565. ASSERT_TRUE(res);
  12566. EXPECT_EQ(StatusCode::OK_200, res->status);
  12567. EXPECT_EQ(original, res->body);
  12568. }
  12569. // Streaming
  12570. {
  12571. auto h = cli.open_stream("GET", path);
  12572. ASSERT_TRUE(h.is_valid());
  12573. EXPECT_EQ(original, read_all(h));
  12574. }
  12575. }
  12576. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12577. TEST(ParityTest, Gzip) {
  12578. test_compression_parity<detail::gzip_compressor>(
  12579. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12580. }
  12581. #endif
  12582. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12583. TEST(ParityTest, Brotli) {
  12584. test_compression_parity<detail::brotli_compressor>(
  12585. "Hello, brotli parity test payload", "/parity-br", "br");
  12586. }
  12587. #endif
  12588. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12589. TEST(ParityTest, Zstd) {
  12590. test_compression_parity<detail::zstd_compressor>(
  12591. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12592. }
  12593. #endif
  12594. //==============================================================================
  12595. // New Stream API Tests
  12596. //==============================================================================
  12597. inline std::string read_body(httplib::stream::Result &result) {
  12598. std::string body;
  12599. while (result.next()) {
  12600. body.append(result.data(), result.size());
  12601. }
  12602. return body;
  12603. }
  12604. TEST(ClientConnectionTest, Basic) {
  12605. httplib::ClientConnection conn;
  12606. EXPECT_FALSE(conn.is_open());
  12607. conn.sock = 1;
  12608. EXPECT_TRUE(conn.is_open());
  12609. httplib::ClientConnection conn2(std::move(conn));
  12610. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12611. conn2.sock = INVALID_SOCKET;
  12612. }
  12613. // Unified test server for all stream::* tests
  12614. class StreamApiTest : public ::testing::Test {
  12615. protected:
  12616. void SetUp() override {
  12617. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12618. res.set_content("Hello World!", "text/plain");
  12619. });
  12620. svr_.Get("/echo-params",
  12621. [](const httplib::Request &req, httplib::Response &res) {
  12622. std::string r;
  12623. for (const auto &p : req.params) {
  12624. if (!r.empty()) r += "&";
  12625. r += p.first + "=" + p.second;
  12626. }
  12627. res.set_content(r, "text/plain");
  12628. });
  12629. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12630. res.set_content(req.body, req.get_header_value("Content-Type"));
  12631. });
  12632. svr_.Post("/echo-headers",
  12633. [](const httplib::Request &req, httplib::Response &res) {
  12634. std::string r;
  12635. for (const auto &h : req.headers)
  12636. r += h.first + ": " + h.second + "\n";
  12637. res.set_content(r, "text/plain");
  12638. });
  12639. svr_.Post("/echo-params",
  12640. [](const httplib::Request &req, httplib::Response &res) {
  12641. std::string r = "params:";
  12642. for (const auto &p : req.params)
  12643. r += p.first + "=" + p.second + ";";
  12644. res.set_content(r + " body:" + req.body, "text/plain");
  12645. });
  12646. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12647. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12648. });
  12649. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12650. res.set_content("PUT:" + req.body, "text/plain");
  12651. });
  12652. svr_.Patch("/echo",
  12653. [](const httplib::Request &req, httplib::Response &res) {
  12654. res.set_content("PATCH:" + req.body, "text/plain");
  12655. });
  12656. svr_.Delete(
  12657. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12658. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12659. "text/plain");
  12660. });
  12661. svr_.Get("/head-test",
  12662. [](const httplib::Request &, httplib::Response &res) {
  12663. res.set_content("body for HEAD", "text/plain");
  12664. });
  12665. svr_.Options("/options",
  12666. [](const httplib::Request &, httplib::Response &res) {
  12667. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12668. });
  12669. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12670. svr_.wait_until_ready();
  12671. }
  12672. void TearDown() override {
  12673. svr_.stop();
  12674. if (thread_.joinable()) thread_.join();
  12675. }
  12676. httplib::Server svr_;
  12677. std::thread thread_;
  12678. };
  12679. // stream::Get tests
  12680. TEST_F(StreamApiTest, GetBasic) {
  12681. httplib::Client cli(HOST, PORT);
  12682. auto result = httplib::stream::Get(cli, "/hello");
  12683. ASSERT_TRUE(result.is_valid());
  12684. EXPECT_EQ(200, result.status());
  12685. EXPECT_EQ("Hello World!", read_body(result));
  12686. }
  12687. TEST_F(StreamApiTest, GetWithParams) {
  12688. httplib::Client cli(HOST, PORT);
  12689. httplib::Params params{{"foo", "bar"}};
  12690. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12691. ASSERT_TRUE(result.is_valid());
  12692. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12693. }
  12694. TEST_F(StreamApiTest, GetConnectionError) {
  12695. httplib::Client cli(HOST, 9999);
  12696. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12697. }
  12698. TEST_F(StreamApiTest, Get404) {
  12699. httplib::Client cli(HOST, PORT);
  12700. auto result = httplib::stream::Get(cli, "/nonexistent");
  12701. EXPECT_TRUE(result.is_valid());
  12702. EXPECT_EQ(404, result.status());
  12703. }
  12704. // stream::Post tests
  12705. TEST_F(StreamApiTest, PostBasic) {
  12706. httplib::Client cli(HOST, PORT);
  12707. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12708. "application/json");
  12709. ASSERT_TRUE(result.is_valid());
  12710. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12711. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12712. }
  12713. TEST_F(StreamApiTest, PostWithHeaders) {
  12714. httplib::Client cli(HOST, PORT);
  12715. httplib::Headers headers{{"X-Custom", "value"}};
  12716. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12717. "text/plain");
  12718. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12719. }
  12720. TEST_F(StreamApiTest, PostWithParams) {
  12721. httplib::Client cli(HOST, PORT);
  12722. httplib::Params params{{"k", "v"}};
  12723. auto result =
  12724. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12725. auto body = read_body(result);
  12726. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12727. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12728. }
  12729. TEST_F(StreamApiTest, PostLarge) {
  12730. httplib::Client cli(HOST, PORT);
  12731. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12732. size_t total = 0;
  12733. while (result.next()) {
  12734. total += result.size();
  12735. }
  12736. EXPECT_EQ(100u * 1024u, total);
  12737. }
  12738. // stream::Put/Patch tests
  12739. TEST_F(StreamApiTest, PutAndPatch) {
  12740. httplib::Client cli(HOST, PORT);
  12741. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12742. EXPECT_EQ("PUT:test", read_body(put));
  12743. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12744. EXPECT_EQ("PATCH:test", read_body(patch));
  12745. }
  12746. // stream::Delete tests
  12747. TEST_F(StreamApiTest, Delete) {
  12748. httplib::Client cli(HOST, PORT);
  12749. auto del1 = httplib::stream::Delete(cli, "/resource");
  12750. EXPECT_EQ("Deleted", read_body(del1));
  12751. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12752. EXPECT_EQ("Deleted:data", read_body(del2));
  12753. }
  12754. // stream::Head/Options tests
  12755. TEST_F(StreamApiTest, HeadAndOptions) {
  12756. httplib::Client cli(HOST, PORT);
  12757. auto head = httplib::stream::Head(cli, "/head-test");
  12758. EXPECT_TRUE(head.is_valid());
  12759. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12760. auto opts = httplib::stream::Options(cli, "/options");
  12761. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12762. }
  12763. // SSL stream::* tests
  12764. #ifdef CPPHTTPLIB_SSL_ENABLED
  12765. class SSLStreamApiTest : public ::testing::Test {
  12766. protected:
  12767. void SetUp() override {
  12768. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12769. res.set_content("Hello SSL!", "text/plain");
  12770. });
  12771. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12772. res.set_content(req.body, "text/plain");
  12773. });
  12774. port_ = svr_.bind_to_any_port("127.0.0.1");
  12775. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12776. svr_.wait_until_ready();
  12777. }
  12778. void TearDown() override {
  12779. svr_.stop();
  12780. if (thread_.joinable()) thread_.join();
  12781. }
  12782. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12783. std::thread thread_;
  12784. int port_ = 0;
  12785. };
  12786. TEST_F(SSLStreamApiTest, GetAndPost) {
  12787. httplib::SSLClient cli("127.0.0.1", port_);
  12788. cli.enable_server_certificate_verification(false);
  12789. auto get = httplib::stream::Get(cli, "/hello");
  12790. EXPECT_EQ("Hello SSL!", read_body(get));
  12791. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12792. EXPECT_EQ("test", read_body(post));
  12793. }
  12794. #endif
  12795. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12796. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12797. // BodyReader
  12798. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12799. // Test that read timeout during streaming is detected
  12800. // Use a large content-length response where server delays mid-stream
  12801. Server svr;
  12802. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12803. // Send a large response with delay in the middle
  12804. res.set_content_provider(
  12805. 1000, // content_length
  12806. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12807. if (offset < 100) {
  12808. // Send first 100 bytes immediately
  12809. std::string data(100, 'A');
  12810. sink.write(data.c_str(), data.size());
  12811. return true;
  12812. }
  12813. // Then delay longer than client timeout
  12814. std::this_thread::sleep_for(std::chrono::seconds(3));
  12815. std::string data(900, 'B');
  12816. sink.write(data.c_str(), data.size());
  12817. return true;
  12818. });
  12819. });
  12820. auto port = 8091;
  12821. std::thread t([&]() { svr.listen("localhost", port); });
  12822. svr.wait_until_ready();
  12823. Client cli("localhost", port);
  12824. cli.set_read_timeout(1, 0); // 1 second timeout
  12825. auto handle = cli.open_stream("GET", "/slow-stream");
  12826. ASSERT_TRUE(handle.is_valid());
  12827. char buf[256];
  12828. ssize_t total = 0;
  12829. ssize_t n;
  12830. bool got_error = false;
  12831. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12832. total += n;
  12833. }
  12834. if (n < 0) {
  12835. got_error = true;
  12836. // Should be timeout or read error
  12837. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12838. handle.get_read_error() == Error::Read)
  12839. << "Actual error: " << to_string(handle.get_read_error());
  12840. }
  12841. // Either we got an error, or we got less data than expected
  12842. EXPECT_TRUE(got_error || total < 1000)
  12843. << "Expected timeout but got all " << total << " bytes";
  12844. svr.stop();
  12845. t.join();
  12846. }
  12847. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12848. // Test connection closed detection via BodyReader
  12849. Server svr;
  12850. std::atomic<bool> close_now{false};
  12851. svr.Get("/will-close", [&](const Request &, Response &res) {
  12852. res.set_content_provider(
  12853. 10000, // Large content_length that we won't fully send
  12854. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12855. if (offset < 100) {
  12856. std::string data(100, 'X');
  12857. sink.write(data.c_str(), data.size());
  12858. return true;
  12859. }
  12860. // Wait for signal then abort
  12861. while (!close_now) {
  12862. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12863. }
  12864. return false; // Abort - server will close connection
  12865. });
  12866. });
  12867. auto port = 8092;
  12868. std::thread t([&]() { svr.listen("localhost", port); });
  12869. svr.wait_until_ready();
  12870. Client cli("localhost", port);
  12871. auto handle = cli.open_stream("GET", "/will-close");
  12872. ASSERT_TRUE(handle.is_valid());
  12873. char buf[256];
  12874. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12875. EXPECT_GT(n, 0) << "First read should succeed";
  12876. // Signal server to close
  12877. close_now = true;
  12878. // Keep reading until error or EOF
  12879. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12880. // Keep reading
  12881. }
  12882. // Should get an error since content_length wasn't satisfied
  12883. if (n < 0) {
  12884. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12885. handle.get_read_error() == Error::Read)
  12886. << "Actual error: " << to_string(handle.get_read_error());
  12887. }
  12888. svr.stop();
  12889. t.join();
  12890. }
  12891. #ifdef CPPHTTPLIB_SSL_ENABLED
  12892. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12893. // Test that read timeout during SSL streaming is detected
  12894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12895. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12896. res.set_content_provider(
  12897. 1000, "text/plain",
  12898. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12899. if (offset < 100) {
  12900. std::string data(100, 'A');
  12901. sink.write(data.c_str(), data.size());
  12902. return true;
  12903. }
  12904. std::this_thread::sleep_for(std::chrono::seconds(3));
  12905. std::string data(900, 'B');
  12906. sink.write(data.c_str(), data.size());
  12907. return true;
  12908. });
  12909. });
  12910. auto port = 8093;
  12911. std::thread t([&]() { svr.listen("localhost", port); });
  12912. svr.wait_until_ready();
  12913. SSLClient cli("localhost", port);
  12914. cli.enable_server_certificate_verification(false);
  12915. cli.set_read_timeout(1, 0); // 1 second timeout
  12916. auto handle = cli.open_stream("GET", "/slow-stream");
  12917. ASSERT_TRUE(handle.is_valid());
  12918. char buf[256];
  12919. ssize_t total = 0;
  12920. ssize_t n;
  12921. bool got_error = false;
  12922. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12923. total += n;
  12924. }
  12925. if (n < 0) {
  12926. got_error = true;
  12927. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12928. handle.get_read_error() == Error::Read)
  12929. << "Actual error: " << to_string(handle.get_read_error());
  12930. }
  12931. EXPECT_TRUE(got_error || total < 1000)
  12932. << "Expected timeout but got all " << total << " bytes";
  12933. svr.stop();
  12934. t.join();
  12935. }
  12936. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12937. // Test SSL connection closed detection
  12938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12939. std::atomic<bool> close_now{false};
  12940. svr.Get("/will-close", [&](const Request &, Response &res) {
  12941. res.set_content_provider(
  12942. 10000, "text/plain",
  12943. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12944. if (offset < 100) {
  12945. std::string data(100, 'X');
  12946. sink.write(data.c_str(), data.size());
  12947. return true;
  12948. }
  12949. while (!close_now) {
  12950. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12951. }
  12952. return false;
  12953. });
  12954. });
  12955. auto port = 8094;
  12956. std::thread t([&]() { svr.listen("localhost", port); });
  12957. svr.wait_until_ready();
  12958. SSLClient cli("localhost", port);
  12959. cli.enable_server_certificate_verification(false);
  12960. auto handle = cli.open_stream("GET", "/will-close");
  12961. ASSERT_TRUE(handle.is_valid());
  12962. char buf[256];
  12963. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12964. EXPECT_GT(n, 0);
  12965. // Signal server to close
  12966. close_now = true;
  12967. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12968. // Keep reading
  12969. }
  12970. if (n < 0) {
  12971. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12972. handle.get_read_error() == Error::Read)
  12973. << "Actual error: " << to_string(handle.get_read_error());
  12974. }
  12975. svr.stop();
  12976. t.join();
  12977. }
  12978. #endif
  12979. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12980. using namespace httplib;
  12981. // Create a test file
  12982. const char *fname = "etag_testfile.txt";
  12983. const char *content = "etag-content";
  12984. {
  12985. std::ofstream ofs(fname);
  12986. ofs << content;
  12987. ASSERT_TRUE(ofs.good());
  12988. }
  12989. Server svr;
  12990. svr.set_mount_point("/static", ".");
  12991. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12992. svr.wait_until_ready();
  12993. Client cli(HOST, PORT);
  12994. // First request: should get 200 with ETag header
  12995. auto res1 = cli.Get("/static/etag_testfile.txt");
  12996. ASSERT_TRUE(res1);
  12997. ASSERT_EQ(200, res1->status);
  12998. ASSERT_TRUE(res1->has_header("ETag"));
  12999. std::string etag = res1->get_header_value("ETag");
  13000. EXPECT_FALSE(etag.empty());
  13001. // Verify ETag format: W/"hex-hex"
  13002. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13003. EXPECT_EQ('W', etag[0]);
  13004. EXPECT_EQ('/', etag[1]);
  13005. EXPECT_EQ('"', etag[2]);
  13006. EXPECT_EQ('"', etag.back());
  13007. // Exact match: expect 304 Not Modified
  13008. Headers h2 = {{"If-None-Match", etag}};
  13009. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13010. ASSERT_TRUE(res2);
  13011. EXPECT_EQ(304, res2->status);
  13012. // Wildcard match: expect 304 Not Modified
  13013. Headers h3 = {{"If-None-Match", "*"}};
  13014. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13015. ASSERT_TRUE(res3);
  13016. EXPECT_EQ(304, res3->status);
  13017. // Non-matching ETag: expect 200
  13018. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13019. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13020. ASSERT_TRUE(res4);
  13021. EXPECT_EQ(200, res4->status);
  13022. // Multiple ETags with one matching: expect 304
  13023. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13024. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13025. ASSERT_TRUE(res5);
  13026. EXPECT_EQ(304, res5->status);
  13027. svr.stop();
  13028. t.join();
  13029. std::remove(fname);
  13030. }
  13031. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13032. using namespace httplib;
  13033. Server svr;
  13034. svr.set_mount_point("/static", ".");
  13035. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13036. svr.wait_until_ready();
  13037. Client cli(HOST, PORT);
  13038. // Send If-None-Match: * to a non-existent file
  13039. Headers h = {{"If-None-Match", "*"}};
  13040. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13041. ASSERT_TRUE(res);
  13042. EXPECT_EQ(404, res->status);
  13043. svr.stop();
  13044. t.join();
  13045. }
  13046. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13047. using namespace httplib;
  13048. // Create a test file
  13049. const char *fname = "etag_boundary_testfile.txt";
  13050. const char *content = "boundary-test";
  13051. {
  13052. std::ofstream ofs(fname);
  13053. ofs << content;
  13054. ASSERT_TRUE(ofs.good());
  13055. }
  13056. Server svr;
  13057. svr.set_mount_point("/static", ".");
  13058. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13059. svr.wait_until_ready();
  13060. Client cli(HOST, PORT);
  13061. // Get the actual ETag
  13062. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13063. ASSERT_TRUE(res1);
  13064. ASSERT_EQ(200, res1->status);
  13065. ASSERT_TRUE(res1->has_header("ETag"));
  13066. std::string etag = res1->get_header_value("ETag");
  13067. // Test 1: Very long ETag value (longer than actual ETag)
  13068. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13069. Headers h1 = {{"If-None-Match", "W/"
  13070. "\"very-long-etag-value-that-is-much-longer-"
  13071. "than-the-actual-etag-value\""}};
  13072. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13073. ASSERT_TRUE(res2);
  13074. EXPECT_EQ(200, res2->status); // Should not match
  13075. // Test 2: Long string followed by wildcard
  13076. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13077. // string)
  13078. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13079. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13080. ASSERT_TRUE(res3);
  13081. EXPECT_EQ(304, res3->status); // Should match on "*"
  13082. // Test 3: Wildcard followed by long string
  13083. // Should match on "*" immediately and return 304
  13084. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13085. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13086. ASSERT_TRUE(res4);
  13087. EXPECT_EQ(304, res4->status); // Should match on "*"
  13088. // Test 4: Multiple long non-matching values
  13089. // Should NOT match and return 200 (test that all comparisons are safe)
  13090. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13091. "W/\"second-long-non-matching-value\", "
  13092. "W/\"third-long-non-matching-value\""}};
  13093. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13094. ASSERT_TRUE(res5);
  13095. EXPECT_EQ(200, res5->status); // Should not match
  13096. // Test 5: Single character that is not "*" (edge case)
  13097. Headers h5 = {{"If-None-Match", "X"}};
  13098. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13099. ASSERT_TRUE(res6);
  13100. EXPECT_EQ(200, res6->status); // Should not match
  13101. svr.stop();
  13102. t.join();
  13103. std::remove(fname);
  13104. }
  13105. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13106. using namespace httplib;
  13107. // Create a test file
  13108. const char *fname = "ims_testfile.txt";
  13109. const char *content = "if-modified-since-test";
  13110. {
  13111. std::ofstream ofs(fname);
  13112. ofs << content;
  13113. ASSERT_TRUE(ofs.good());
  13114. }
  13115. Server svr;
  13116. svr.set_mount_point("/static", ".");
  13117. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13118. svr.wait_until_ready();
  13119. Client cli(HOST, PORT);
  13120. // First request: should get 200 with Last-Modified header
  13121. auto res1 = cli.Get("/static/ims_testfile.txt");
  13122. ASSERT_TRUE(res1);
  13123. ASSERT_EQ(200, res1->status);
  13124. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13125. std::string last_modified = res1->get_header_value("Last-Modified");
  13126. EXPECT_FALSE(last_modified.empty());
  13127. // If-Modified-Since with same time: expect 304
  13128. Headers h2 = {{"If-Modified-Since", last_modified}};
  13129. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13130. ASSERT_TRUE(res2);
  13131. EXPECT_EQ(304, res2->status);
  13132. // If-Modified-Since with future time: expect 304
  13133. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13134. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13135. ASSERT_TRUE(res3);
  13136. EXPECT_EQ(304, res3->status);
  13137. // If-Modified-Since with past time: expect 200
  13138. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13139. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13140. ASSERT_TRUE(res4);
  13141. EXPECT_EQ(200, res4->status);
  13142. // If-None-Match takes precedence over If-Modified-Since
  13143. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13144. ASSERT_TRUE(res1->has_header("ETag"));
  13145. std::string etag = res1->get_header_value("ETag");
  13146. Headers h5 = {{"If-None-Match", etag},
  13147. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13148. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13149. ASSERT_TRUE(res5);
  13150. EXPECT_EQ(304, res5->status);
  13151. svr.stop();
  13152. t.join();
  13153. std::remove(fname);
  13154. }
  13155. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13156. using namespace httplib;
  13157. Server svr;
  13158. // Endpoint that returns compressible content
  13159. svr.Get("/compressible", [](const Request &, Response &res) {
  13160. // Return a large enough body to trigger compression
  13161. std::string body(1000, 'a');
  13162. res.set_content(body, "text/plain");
  13163. });
  13164. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13165. svr.wait_until_ready();
  13166. Client cli(HOST, PORT);
  13167. // Request with gzip support: should get Vary header when compressed
  13168. cli.set_compress(true);
  13169. auto res1 = cli.Get("/compressible");
  13170. ASSERT_TRUE(res1);
  13171. EXPECT_EQ(200, res1->status);
  13172. // If Content-Encoding is set, Vary should also be set
  13173. if (res1->has_header("Content-Encoding")) {
  13174. EXPECT_TRUE(res1->has_header("Vary"));
  13175. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13176. }
  13177. // Request without Accept-Encoding header: should not have compression
  13178. Headers h_no_compress;
  13179. auto res2 = cli.Get("/compressible", h_no_compress);
  13180. ASSERT_TRUE(res2);
  13181. EXPECT_EQ(200, res2->status);
  13182. // Verify Vary header is present when compression is applied
  13183. // (the exact behavior depends on server configuration)
  13184. svr.stop();
  13185. t.join();
  13186. }
  13187. TEST(ETagTest, IfRangeWithETag) {
  13188. using namespace httplib;
  13189. // Create a test file with known content
  13190. const char *fname = "if_range_testfile.txt";
  13191. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13192. {
  13193. std::ofstream ofs(fname);
  13194. ofs << content;
  13195. ASSERT_TRUE(ofs.good());
  13196. }
  13197. Server svr;
  13198. svr.set_mount_point("/static", ".");
  13199. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13200. svr.wait_until_ready();
  13201. Client cli(HOST, PORT);
  13202. // First request: get ETag
  13203. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13204. ASSERT_TRUE(res1);
  13205. ASSERT_EQ(200, res1->status);
  13206. ASSERT_TRUE(res1->has_header("ETag"));
  13207. std::string etag = res1->get_header_value("ETag");
  13208. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13209. // Since our server generates weak ETags (W/"..."), If-Range with our
  13210. // ETag should NOT result in partial content - it should return full content.
  13211. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13212. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13213. ASSERT_TRUE(res2);
  13214. // Weak ETag in If-Range -> full content (200), not partial (206)
  13215. EXPECT_EQ(200, res2->status);
  13216. EXPECT_EQ(content, res2->body);
  13217. EXPECT_FALSE(res2->has_header("Content-Range"));
  13218. // Range request with non-matching If-Range (ETag): should get 200 (full
  13219. // content)
  13220. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13221. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13222. ASSERT_TRUE(res3);
  13223. EXPECT_EQ(200, res3->status);
  13224. EXPECT_EQ(content, res3->body);
  13225. EXPECT_FALSE(res3->has_header("Content-Range"));
  13226. // Range request with strong ETag (hypothetical - our server doesn't generate
  13227. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13228. // should return full content)
  13229. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13230. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13231. ASSERT_TRUE(res4);
  13232. EXPECT_EQ(200, res4->status);
  13233. EXPECT_EQ(content, res4->body);
  13234. EXPECT_FALSE(res4->has_header("Content-Range"));
  13235. svr.stop();
  13236. t.join();
  13237. std::remove(fname);
  13238. }
  13239. TEST(ETagTest, IfRangeWithDate) {
  13240. using namespace httplib;
  13241. // Create a test file
  13242. const char *fname = "if_range_date_testfile.txt";
  13243. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13244. {
  13245. std::ofstream ofs(fname);
  13246. ofs << content;
  13247. ASSERT_TRUE(ofs.good());
  13248. }
  13249. Server svr;
  13250. svr.set_mount_point("/static", ".");
  13251. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13252. svr.wait_until_ready();
  13253. Client cli(HOST, PORT);
  13254. // First request: get Last-Modified
  13255. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13256. ASSERT_TRUE(res1);
  13257. ASSERT_EQ(200, res1->status);
  13258. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13259. std::string last_modified = res1->get_header_value("Last-Modified");
  13260. // Range request with matching If-Range (date): should get 206
  13261. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13262. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13263. ASSERT_TRUE(res2);
  13264. EXPECT_EQ(206, res2->status);
  13265. EXPECT_EQ("FGHIJ", res2->body);
  13266. // Range request with old If-Range date: should get 200 (full content)
  13267. Headers h3 = {{"Range", "bytes=5-9"},
  13268. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13269. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13270. ASSERT_TRUE(res3);
  13271. EXPECT_EQ(200, res3->status);
  13272. EXPECT_EQ(content, res3->body);
  13273. // Range request with future If-Range date: should get 206
  13274. Headers h4 = {{"Range", "bytes=0-4"},
  13275. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13276. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13277. ASSERT_TRUE(res4);
  13278. EXPECT_EQ(206, res4->status);
  13279. EXPECT_EQ("ABCDE", res4->body);
  13280. svr.stop();
  13281. t.join();
  13282. std::remove(fname);
  13283. }
  13284. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13285. using namespace httplib;
  13286. const char *fname = "etag_malformed.txt";
  13287. const char *content = "malformed-etag";
  13288. {
  13289. std::ofstream ofs(fname);
  13290. ofs << content;
  13291. ASSERT_TRUE(ofs.good());
  13292. }
  13293. Server svr;
  13294. svr.set_mount_point("/static", ".");
  13295. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13296. svr.wait_until_ready();
  13297. Client cli(HOST, PORT);
  13298. // baseline: should get 200 and an ETag
  13299. auto res1 = cli.Get("/static/etag_malformed.txt");
  13300. ASSERT_TRUE(res1);
  13301. ASSERT_EQ(200, res1->status);
  13302. ASSERT_TRUE(res1->has_header("ETag"));
  13303. // Malformed ETag value (missing quotes) should be treated as non-matching
  13304. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13305. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13306. ASSERT_TRUE(res_bad);
  13307. EXPECT_EQ(200, res_bad->status);
  13308. // Whitespace-only header value should be considered invalid / non-matching
  13309. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13310. "Host: localhost\r\n"
  13311. "If-None-Match: \r\n"
  13312. "Connection: close\r\n"
  13313. "\r\n";
  13314. std::string out;
  13315. ASSERT_TRUE(send_request(5, raw_req, &out));
  13316. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13317. svr.stop();
  13318. t.join();
  13319. std::remove(fname);
  13320. }
  13321. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13322. using namespace httplib;
  13323. const char *fname = "ims_invalid_format.txt";
  13324. const char *content = "ims-bad-format";
  13325. {
  13326. std::ofstream ofs(fname);
  13327. ofs << content;
  13328. ASSERT_TRUE(ofs.good());
  13329. }
  13330. Server svr;
  13331. svr.set_mount_point("/static", ".");
  13332. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13333. svr.wait_until_ready();
  13334. Client cli(HOST, PORT);
  13335. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13336. ASSERT_TRUE(res1);
  13337. ASSERT_EQ(200, res1->status);
  13338. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13339. // If-Modified-Since with invalid format should not result in 304
  13340. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13341. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13342. ASSERT_TRUE(res_bad);
  13343. EXPECT_EQ(200, res_bad->status);
  13344. // If-Range with invalid date format should be treated as mismatch -> full
  13345. // content (200)
  13346. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13347. {"If-Range", "invalid-date"}};
  13348. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13349. ASSERT_TRUE(res_ifrange);
  13350. EXPECT_EQ(200, res_ifrange->status);
  13351. svr.stop();
  13352. t.join();
  13353. std::remove(fname);
  13354. }
  13355. TEST(ETagTest, IfRangeWithMalformedETag) {
  13356. using namespace httplib;
  13357. const char *fname = "ifrange_malformed.txt";
  13358. const std::string content = "0123456789";
  13359. {
  13360. std::ofstream ofs(fname);
  13361. ofs << content;
  13362. ASSERT_TRUE(ofs.good());
  13363. }
  13364. Server svr;
  13365. svr.set_mount_point("/static", ".");
  13366. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13367. svr.wait_until_ready();
  13368. Client cli(HOST, PORT);
  13369. // First request: get ETag
  13370. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13371. ASSERT_TRUE(res1);
  13372. ASSERT_EQ(200, res1->status);
  13373. ASSERT_TRUE(res1->has_header("ETag"));
  13374. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13375. // full content (200)
  13376. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13377. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13378. ASSERT_TRUE(res2);
  13379. EXPECT_EQ(200, res2->status);
  13380. EXPECT_EQ(content, res2->body);
  13381. svr.stop();
  13382. t.join();
  13383. std::remove(fname);
  13384. }
  13385. TEST(ETagTest, ExtremeLargeDateValues) {
  13386. using namespace httplib;
  13387. const char *fname = "ims_extreme_date.txt";
  13388. const char *content = "ims-extreme-date";
  13389. {
  13390. std::ofstream ofs(fname);
  13391. ofs << content;
  13392. ASSERT_TRUE(ofs.good());
  13393. }
  13394. Server svr;
  13395. svr.set_mount_point("/static", ".");
  13396. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13397. svr.wait_until_ready();
  13398. Client cli(HOST, PORT);
  13399. auto res1 = cli.Get(std::string("/static/") + fname);
  13400. ASSERT_TRUE(res1);
  13401. ASSERT_EQ(200, res1->status);
  13402. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13403. // Extremely large year that may overflow date parsing routines.
  13404. Headers h_large_date = {
  13405. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13406. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13407. ASSERT_TRUE(res_bad);
  13408. // Expect server to treat this as invalid/mismatch and return full content
  13409. EXPECT_EQ(200, res_bad->status);
  13410. // If-Range with extremely large date should be treated as mismatch -> full
  13411. // content (200)
  13412. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13413. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13414. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13415. ASSERT_TRUE(res_ifrange);
  13416. EXPECT_EQ(200, res_ifrange->status);
  13417. svr.stop();
  13418. t.join();
  13419. std::remove(fname);
  13420. }
  13421. TEST(ETagTest, NegativeFileModificationTime) {
  13422. using namespace httplib;
  13423. const char *fname = "ims_negative_mtime.txt";
  13424. const std::string content = "negative-mtime";
  13425. {
  13426. std::ofstream ofs(fname);
  13427. ofs << content;
  13428. ASSERT_TRUE(ofs.good());
  13429. }
  13430. // Try to set file mtime to a negative value. This may fail on some
  13431. // platforms/filesystems; if it fails, the test will still verify server
  13432. // behaves safely by performing a regular conditional request.
  13433. #if defined(__APPLE__) || defined(__linux__)
  13434. bool set_negative = false;
  13435. do {
  13436. struct timeval times[2];
  13437. // access time: now
  13438. times[0].tv_sec = time(nullptr);
  13439. times[0].tv_usec = 0;
  13440. // modification time: negative (e.g., -1)
  13441. times[1].tv_sec = -1;
  13442. times[1].tv_usec = 0;
  13443. if (utimes(fname, times) == 0) { set_negative = true; }
  13444. } while (0);
  13445. #else
  13446. bool set_negative = false;
  13447. #endif
  13448. Server svr;
  13449. svr.set_mount_point("/static", ".");
  13450. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13451. svr.wait_until_ready();
  13452. Client cli(HOST, PORT);
  13453. auto res1 = cli.Get(std::string("/static/") + fname);
  13454. ASSERT_TRUE(res1);
  13455. ASSERT_EQ(200, res1->status);
  13456. bool has_last_modified = res1->has_header("Last-Modified");
  13457. std::string last_modified;
  13458. if (has_last_modified) {
  13459. last_modified = res1->get_header_value("Last-Modified");
  13460. }
  13461. if (set_negative) {
  13462. // If we successfully set a negative mtime, ensure server returns a
  13463. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13464. // with an old date and ensure server handles it without crash.
  13465. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13466. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13467. ASSERT_TRUE(res2);
  13468. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13469. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13470. } else {
  13471. // Could not set negative mtime on this platform; fall back to verifying
  13472. // that normal invalid/malformed dates are treated safely (non-304).
  13473. Headers h_bad_date = {
  13474. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13475. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13476. ASSERT_TRUE(res_bad);
  13477. EXPECT_EQ(200, res_bad->status);
  13478. }
  13479. svr.stop();
  13480. t.join();
  13481. std::remove(fname);
  13482. }
  13483. //==============================================================================
  13484. // SSE Parsing Tests
  13485. //==============================================================================
  13486. class SSEParsingTest : public ::testing::Test {
  13487. protected:
  13488. // Test helper that mimics SSE parsing behavior
  13489. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13490. int &retry_ms) {
  13491. // Blank line signals end of event
  13492. if (line.empty() || line == "\r") { return true; }
  13493. // Lines starting with ':' are comments (ignored)
  13494. if (!line.empty() && line[0] == ':') { return false; }
  13495. // Find the colon separator
  13496. auto colon_pos = line.find(':');
  13497. if (colon_pos == std::string::npos) {
  13498. // Line with no colon is treated as field name with empty value
  13499. return false;
  13500. }
  13501. std::string field = line.substr(0, colon_pos);
  13502. std::string value;
  13503. // Value starts after colon, skip optional single space
  13504. if (colon_pos + 1 < line.size()) {
  13505. size_t value_start = colon_pos + 1;
  13506. if (line[value_start] == ' ') { value_start++; }
  13507. value = line.substr(value_start);
  13508. // Remove trailing \r if present
  13509. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13510. }
  13511. // Handle known fields
  13512. if (field == "event") {
  13513. msg.event = value;
  13514. } else if (field == "data") {
  13515. // Multiple data lines are concatenated with newlines
  13516. if (!msg.data.empty()) { msg.data += "\n"; }
  13517. msg.data += value;
  13518. } else if (field == "id") {
  13519. // Empty id is valid (clears the last event ID)
  13520. msg.id = value;
  13521. } else if (field == "retry") {
  13522. // Parse retry interval in milliseconds
  13523. {
  13524. int v = 0;
  13525. auto res =
  13526. detail::from_chars(value.data(), value.data() + value.size(), v);
  13527. if (res.ec == std::errc{}) { retry_ms = v; }
  13528. }
  13529. }
  13530. // Unknown fields are ignored per SSE spec
  13531. return false;
  13532. }
  13533. };
  13534. // Test: Single-line data
  13535. TEST_F(SSEParsingTest, SingleLineData) {
  13536. sse::SSEMessage msg;
  13537. int retry_ms = 3000;
  13538. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13539. EXPECT_EQ(msg.data, "hello");
  13540. EXPECT_EQ(msg.event, "message");
  13541. // Blank line ends event
  13542. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13543. }
  13544. // Test: Multi-line data
  13545. TEST_F(SSEParsingTest, MultiLineData) {
  13546. sse::SSEMessage msg;
  13547. int retry_ms = 3000;
  13548. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13549. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13550. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13551. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13552. }
  13553. // Test: Custom event types
  13554. TEST_F(SSEParsingTest, CustomEventType) {
  13555. sse::SSEMessage msg;
  13556. int retry_ms = 3000;
  13557. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13558. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13559. EXPECT_EQ(msg.event, "update");
  13560. EXPECT_EQ(msg.data, "payload");
  13561. }
  13562. // Test: Event ID handling
  13563. TEST_F(SSEParsingTest, EventIdHandling) {
  13564. sse::SSEMessage msg;
  13565. int retry_ms = 3000;
  13566. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13567. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13568. EXPECT_EQ(msg.id, "12345");
  13569. }
  13570. // Test: Empty event ID (clears last event ID)
  13571. TEST_F(SSEParsingTest, EmptyEventId) {
  13572. sse::SSEMessage msg;
  13573. msg.id = "previous";
  13574. int retry_ms = 3000;
  13575. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13576. EXPECT_EQ(msg.id, "");
  13577. }
  13578. // Test: Retry field parsing
  13579. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13580. sse::SSEMessage msg;
  13581. int retry_ms = 3000;
  13582. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13583. EXPECT_EQ(retry_ms, 5000);
  13584. }
  13585. // Test: Invalid retry value
  13586. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13587. sse::SSEMessage msg;
  13588. int retry_ms = 3000;
  13589. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13590. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13591. }
  13592. // Test: Comments (lines starting with :)
  13593. TEST_F(SSEParsingTest, CommentsIgnored) {
  13594. sse::SSEMessage msg;
  13595. int retry_ms = 3000;
  13596. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13597. EXPECT_EQ(msg.data, "");
  13598. EXPECT_EQ(msg.event, "message");
  13599. }
  13600. // Test: Colon in value
  13601. TEST_F(SSEParsingTest, ColonInValue) {
  13602. sse::SSEMessage msg;
  13603. int retry_ms = 3000;
  13604. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13605. EXPECT_EQ(msg.data, "hello:world:test");
  13606. }
  13607. // Test: Line with no colon (field name only)
  13608. TEST_F(SSEParsingTest, FieldNameOnly) {
  13609. sse::SSEMessage msg;
  13610. int retry_ms = 3000;
  13611. // According to SSE spec, this is treated as field name with empty value
  13612. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13613. // Since we don't recognize "data" without colon, data should be empty
  13614. EXPECT_EQ(msg.data, "");
  13615. }
  13616. // Test: Trailing \r handling
  13617. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13618. sse::SSEMessage msg;
  13619. int retry_ms = 3000;
  13620. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13621. EXPECT_EQ(msg.data, "hello");
  13622. }
  13623. // Test: Unknown fields ignored
  13624. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13625. sse::SSEMessage msg;
  13626. int retry_ms = 3000;
  13627. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13628. EXPECT_EQ(msg.data, "");
  13629. EXPECT_EQ(msg.event, "message");
  13630. }
  13631. // Test: Space after colon is optional
  13632. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13633. sse::SSEMessage msg1, msg2;
  13634. int retry_ms = 3000;
  13635. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13636. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13637. EXPECT_EQ(msg1.data, "hello");
  13638. EXPECT_EQ(msg2.data, "hello");
  13639. }
  13640. // Test: SSEMessage clear
  13641. TEST_F(SSEParsingTest, MessageClear) {
  13642. sse::SSEMessage msg;
  13643. msg.event = "custom";
  13644. msg.data = "some data";
  13645. msg.id = "123";
  13646. msg.clear();
  13647. EXPECT_EQ(msg.event, "message");
  13648. EXPECT_EQ(msg.data, "");
  13649. EXPECT_EQ(msg.id, "");
  13650. }
  13651. // Test: Complete event parsing
  13652. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13653. sse::SSEMessage msg;
  13654. int retry_ms = 3000;
  13655. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13656. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13657. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13658. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13659. // Blank line ends event
  13660. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13661. EXPECT_EQ(msg.event, "notification");
  13662. EXPECT_EQ(msg.id, "evt-42");
  13663. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13664. EXPECT_EQ(retry_ms, 1000);
  13665. }
  13666. //==============================================================================
  13667. // Integration Tests with Server
  13668. //==============================================================================
  13669. class SSEIntegrationTest : public ::testing::Test {
  13670. protected:
  13671. void SetUp() override {
  13672. stop_server_.store(false);
  13673. events_.clear();
  13674. server_ = httplib::detail::make_unique<Server>();
  13675. setup_server();
  13676. start_server();
  13677. }
  13678. void TearDown() override {
  13679. stop_server_.store(true);
  13680. event_cv_.notify_all();
  13681. server_->stop();
  13682. if (server_thread_.joinable()) { server_thread_.join(); }
  13683. }
  13684. void setup_server() {
  13685. // Simple SSE endpoint
  13686. server_->Get("/events", [this](const Request &req, Response &res) {
  13687. auto last_id = req.get_header_value("Last-Event-ID");
  13688. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13689. res.set_chunked_content_provider(
  13690. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13691. std::unique_lock<std::mutex> lock(event_mutex_);
  13692. if (event_cv_.wait_for(
  13693. lock, std::chrono::milliseconds(200), [this] {
  13694. return !events_.empty() || stop_server_.load();
  13695. })) {
  13696. if (stop_server_.load()) { return false; }
  13697. if (!events_.empty()) {
  13698. std::string event = events_.front();
  13699. events_.erase(events_.begin());
  13700. sink.write(event.data(), event.size());
  13701. return true;
  13702. }
  13703. }
  13704. return !stop_server_.load();
  13705. });
  13706. });
  13707. // Endpoint that returns error
  13708. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13709. res.status = 500;
  13710. res.set_content("Internal Server Error", "text/plain");
  13711. });
  13712. // Endpoint for custom event types
  13713. server_->Get("/custom-events", [](const Request &, Response &res) {
  13714. res.set_chunked_content_provider(
  13715. "text/event-stream", [](size_t offset, DataSink &sink) {
  13716. if (offset == 0) {
  13717. std::string event = "event: update\ndata: updated\n\n"
  13718. "event: delete\ndata: deleted\n\n";
  13719. sink.write(event.data(), event.size());
  13720. }
  13721. return false; // End stream after sending
  13722. });
  13723. });
  13724. }
  13725. void start_server() {
  13726. port_ = server_->bind_to_any_port(HOST);
  13727. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13728. // Wait for server to start
  13729. while (!server_->is_running()) {
  13730. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13731. }
  13732. }
  13733. int get_port() const { return port_; }
  13734. void send_event(const std::string &event) {
  13735. std::lock_guard<std::mutex> lock(event_mutex_);
  13736. events_.push_back(event);
  13737. event_cv_.notify_all();
  13738. }
  13739. std::unique_ptr<Server> server_;
  13740. std::thread server_thread_;
  13741. std::mutex event_mutex_;
  13742. std::condition_variable event_cv_;
  13743. std::vector<std::string> events_;
  13744. std::atomic<bool> stop_server_{false};
  13745. std::string last_received_event_id_;
  13746. int port_ = 0;
  13747. };
  13748. // Test: Successful connection and on_open callback
  13749. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13750. // Add a simple endpoint that sends one event and closes
  13751. server_->Get("/simple-event", [](const Request &, Response &res) {
  13752. res.set_chunked_content_provider(
  13753. "text/event-stream", [](size_t offset, DataSink &sink) {
  13754. if (offset == 0) {
  13755. std::string event = "data: hello\n\n";
  13756. sink.write(event.data(), event.size());
  13757. }
  13758. return false; // Close stream after sending
  13759. });
  13760. });
  13761. Client client("localhost", get_port());
  13762. sse::SSEClient sse(client, "/simple-event");
  13763. std::atomic<bool> open_called{false};
  13764. std::atomic<bool> message_received{false};
  13765. sse.on_open([&open_called]() { open_called.store(true); });
  13766. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13767. if (msg.data == "hello") { message_received.store(true); }
  13768. });
  13769. sse.set_reconnect_interval(100);
  13770. sse.set_max_reconnect_attempts(1);
  13771. // Start async
  13772. sse.start_async();
  13773. // Wait for message to be processed
  13774. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13775. sse.stop();
  13776. EXPECT_TRUE(open_called.load());
  13777. EXPECT_TRUE(message_received.load());
  13778. }
  13779. // Test: on_message callback
  13780. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13781. // Endpoint that sends multiple events then closes
  13782. server_->Get("/multi-event", [](const Request &, Response &res) {
  13783. res.set_chunked_content_provider(
  13784. "text/event-stream", [](size_t offset, DataSink &sink) {
  13785. if (offset == 0) {
  13786. std::string events = "data: message1\n\ndata: message2\n\n";
  13787. sink.write(events.data(), events.size());
  13788. }
  13789. return false;
  13790. });
  13791. });
  13792. Client client("localhost", get_port());
  13793. sse::SSEClient sse(client, "/multi-event");
  13794. std::vector<std::string> received_messages;
  13795. std::mutex messages_mutex;
  13796. sse.on_message([&](const sse::SSEMessage &msg) {
  13797. std::lock_guard<std::mutex> lock(messages_mutex);
  13798. received_messages.push_back(msg.data);
  13799. });
  13800. sse.set_reconnect_interval(100);
  13801. sse.set_max_reconnect_attempts(1);
  13802. sse.start_async();
  13803. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13804. sse.stop();
  13805. std::lock_guard<std::mutex> lock(messages_mutex);
  13806. EXPECT_GE(received_messages.size(), 2u);
  13807. if (received_messages.size() >= 2) {
  13808. EXPECT_EQ(received_messages[0], "message1");
  13809. EXPECT_EQ(received_messages[1], "message2");
  13810. }
  13811. }
  13812. // Test: on_event for specific types
  13813. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13814. Client client("localhost", get_port());
  13815. sse::SSEClient sse(client, "/custom-events");
  13816. std::atomic<bool> update_received{false};
  13817. std::atomic<bool> delete_received{false};
  13818. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13819. if (msg.data == "updated") { update_received.store(true); }
  13820. });
  13821. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13822. if (msg.data == "deleted") { delete_received.store(true); }
  13823. });
  13824. sse.set_max_reconnect_attempts(1);
  13825. sse.start_async();
  13826. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13827. sse.stop();
  13828. EXPECT_TRUE(update_received.load());
  13829. EXPECT_TRUE(delete_received.load());
  13830. }
  13831. // Test: on_error callback on connection failure
  13832. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13833. // Connect to a non-existent port
  13834. Client client("localhost", 59999);
  13835. sse::SSEClient sse(client, "/events");
  13836. std::atomic<bool> error_called{false};
  13837. Error received_error = Error::Success;
  13838. sse.on_error([&](Error err) {
  13839. error_called.store(true);
  13840. received_error = err;
  13841. });
  13842. sse.set_reconnect_interval(50);
  13843. sse.set_max_reconnect_attempts(1);
  13844. sse.start_async();
  13845. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13846. sse.stop();
  13847. EXPECT_TRUE(error_called.load());
  13848. EXPECT_NE(received_error, Error::Success);
  13849. }
  13850. // Test: Last-Event-ID header sent on reconnect
  13851. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13852. // Endpoint that sends event with ID
  13853. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13854. res.set_chunked_content_provider(
  13855. "text/event-stream", [](size_t offset, DataSink &sink) {
  13856. if (offset == 0) {
  13857. std::string event = "id: evt-123\ndata: test\n\n";
  13858. sink.write(event.data(), event.size());
  13859. }
  13860. return false;
  13861. });
  13862. });
  13863. Client client("localhost", get_port());
  13864. sse::SSEClient sse(client, "/event-with-id");
  13865. std::atomic<bool> id_received{false};
  13866. sse.on_message([&](const sse::SSEMessage &msg) {
  13867. if (!msg.id.empty()) { id_received.store(true); }
  13868. });
  13869. sse.set_reconnect_interval(100);
  13870. sse.set_max_reconnect_attempts(1);
  13871. sse.start_async();
  13872. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13873. sse.stop();
  13874. EXPECT_TRUE(id_received.load());
  13875. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13876. }
  13877. // Test: Manual stop
  13878. TEST_F(SSEIntegrationTest, ManualStop) {
  13879. // Endpoint that sends one event and stays open briefly
  13880. std::atomic<bool> handler_running{true};
  13881. server_->Get("/stay-open", [&handler_running](const Request &,
  13882. Response &res) {
  13883. res.set_chunked_content_provider(
  13884. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13885. if (offset == 0) {
  13886. std::string event = "data: connected\n\n";
  13887. sink.write(event.data(), event.size());
  13888. }
  13889. // Keep connection open while handler_running is true
  13890. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13891. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13892. }
  13893. return false;
  13894. });
  13895. });
  13896. Client client("localhost", get_port());
  13897. sse::SSEClient sse(client, "/stay-open");
  13898. std::atomic<bool> connected{false};
  13899. sse.on_open([&connected]() { connected.store(true); });
  13900. sse.set_reconnect_interval(100);
  13901. sse.set_max_reconnect_attempts(1);
  13902. sse.start_async();
  13903. // Wait for connection to establish
  13904. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13905. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13906. }
  13907. EXPECT_TRUE(connected.load());
  13908. EXPECT_TRUE(sse.is_connected());
  13909. // Signal handler to stop
  13910. handler_running.store(false);
  13911. // Stop SSE client
  13912. sse.stop();
  13913. EXPECT_FALSE(sse.is_connected());
  13914. }
  13915. // Test: SSEClient with custom headers
  13916. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13917. // Setup a server endpoint that checks for custom header
  13918. std::atomic<bool> header_received{false};
  13919. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13920. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13921. header_received.store(true);
  13922. }
  13923. res.set_chunked_content_provider("text/event-stream",
  13924. [](size_t, DataSink &) { return false; });
  13925. });
  13926. Client client("localhost", get_port());
  13927. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13928. sse::SSEClient sse(client, "/header-check", headers);
  13929. sse.set_max_reconnect_attempts(1);
  13930. sse.start_async();
  13931. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13932. sse.stop();
  13933. EXPECT_TRUE(header_received.load());
  13934. }
  13935. // Test: Reconnect interval configuration
  13936. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13937. Client client("localhost", get_port());
  13938. sse::SSEClient sse(client, "/events");
  13939. auto &result = sse.set_reconnect_interval(500);
  13940. // Builder pattern should return reference to self
  13941. EXPECT_EQ(&result, &sse);
  13942. }
  13943. // Test: Max reconnect attempts
  13944. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13945. // Connect to non-existent port to force reconnects
  13946. Client client("localhost", 59998);
  13947. sse::SSEClient sse(client, "/events");
  13948. std::atomic<int> error_count{0};
  13949. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13950. sse.set_reconnect_interval(50);
  13951. sse.set_max_reconnect_attempts(2);
  13952. auto start = std::chrono::steady_clock::now();
  13953. sse.start(); // Blocking call
  13954. auto end = std::chrono::steady_clock::now();
  13955. // Should have stopped after 2 failed attempts
  13956. EXPECT_GE(error_count.load(), 2);
  13957. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13958. auto duration =
  13959. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13960. #ifdef _WIN32
  13961. // Windows is much slower for socket connection failures
  13962. EXPECT_LT(duration.count(), 7000);
  13963. #else
  13964. EXPECT_LT(duration.count(), 1000);
  13965. #endif
  13966. }
  13967. // Test: Multi-line data in integration
  13968. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13969. // Endpoint with multi-line data
  13970. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13971. res.set_chunked_content_provider(
  13972. "text/event-stream", [](size_t offset, DataSink &sink) {
  13973. if (offset == 0) {
  13974. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13975. sink.write(event.data(), event.size());
  13976. }
  13977. return false;
  13978. });
  13979. });
  13980. Client client("localhost", get_port());
  13981. sse::SSEClient sse(client, "/multiline-data");
  13982. std::string received_data;
  13983. std::mutex data_mutex;
  13984. sse.on_message([&](const sse::SSEMessage &msg) {
  13985. std::lock_guard<std::mutex> lock(data_mutex);
  13986. received_data = msg.data;
  13987. });
  13988. sse.set_reconnect_interval(100);
  13989. sse.set_max_reconnect_attempts(1);
  13990. sse.start_async();
  13991. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13992. sse.stop();
  13993. std::lock_guard<std::mutex> lock(data_mutex);
  13994. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13995. }
  13996. // Test: Auto-reconnect after server disconnection
  13997. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13998. std::atomic<int> connection_count{0};
  13999. std::atomic<int> message_count{0};
  14000. // Endpoint that sends one event and closes, forcing reconnect
  14001. server_->Get("/reconnect-test",
  14002. [&connection_count](const Request &, Response &res) {
  14003. connection_count.fetch_add(1);
  14004. res.set_chunked_content_provider(
  14005. "text/event-stream", [](size_t offset, DataSink &sink) {
  14006. if (offset == 0) {
  14007. std::string event = "data: hello\n\n";
  14008. sink.write(event.data(), event.size());
  14009. }
  14010. return false; // Close connection after sending
  14011. });
  14012. });
  14013. Client client("localhost", get_port());
  14014. sse::SSEClient sse(client, "/reconnect-test");
  14015. sse.on_message([&message_count](const sse::SSEMessage &) {
  14016. message_count.fetch_add(1);
  14017. });
  14018. sse.set_reconnect_interval(100);
  14019. sse.set_max_reconnect_attempts(3);
  14020. sse.start_async();
  14021. // Wait long enough for multiple reconnects
  14022. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14023. sse.stop();
  14024. // Should have connected multiple times (initial + reconnects)
  14025. EXPECT_GE(connection_count.load(), 2);
  14026. // Should have received messages from multiple connections
  14027. EXPECT_GE(message_count.load(), 2);
  14028. }
  14029. // Test: Last-Event-ID sent on reconnect
  14030. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14031. std::atomic<int> connection_count{0};
  14032. std::vector<std::string> received_last_event_ids;
  14033. std::mutex id_mutex;
  14034. // Endpoint that checks Last-Event-ID header and sends event with ID
  14035. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14036. int conn = connection_count.fetch_add(1);
  14037. // Capture the Last-Event-ID header from each connection
  14038. {
  14039. std::lock_guard<std::mutex> lock(id_mutex);
  14040. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14041. }
  14042. res.set_chunked_content_provider(
  14043. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14044. if (offset == 0) {
  14045. std::string event =
  14046. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14047. sink.write(event.data(), event.size());
  14048. }
  14049. return false;
  14050. });
  14051. });
  14052. Client client("localhost", get_port());
  14053. sse::SSEClient sse(client, "/reconnect-with-id");
  14054. sse.set_reconnect_interval(100);
  14055. sse.set_max_reconnect_attempts(3);
  14056. sse.start_async();
  14057. // Wait for at least 2 connections
  14058. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14059. sse.stop();
  14060. // Verify behavior
  14061. std::lock_guard<std::mutex> lock(id_mutex);
  14062. EXPECT_GE(received_last_event_ids.size(), 2u);
  14063. // First connection should have no Last-Event-ID
  14064. if (!received_last_event_ids.empty()) {
  14065. EXPECT_EQ(received_last_event_ids[0], "");
  14066. }
  14067. // Second connection should have Last-Event-ID from first connection
  14068. if (received_last_event_ids.size() >= 2) {
  14069. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14070. }
  14071. }
  14072. // Test: set_headers updates headers used on reconnect
  14073. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14074. std::vector<std::string> received_tokens;
  14075. std::mutex token_mutex;
  14076. // Endpoint that captures Authorization header
  14077. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14078. {
  14079. std::lock_guard<std::mutex> lock(token_mutex);
  14080. received_tokens.push_back(req.get_header_value("Authorization"));
  14081. }
  14082. res.set_chunked_content_provider(
  14083. "text/event-stream", [](size_t offset, DataSink &sink) {
  14084. if (offset == 0) {
  14085. std::string event = "data: hello\n\n";
  14086. sink.write(event.data(), event.size());
  14087. }
  14088. return false; // Close connection to trigger reconnect
  14089. });
  14090. });
  14091. Client client("localhost", get_port());
  14092. Headers headers = {{"Authorization", "Bearer old-token"}};
  14093. sse::SSEClient sse(client, "/auth-check", headers);
  14094. // Update headers on each successful connection
  14095. sse.on_open(
  14096. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14097. sse.set_reconnect_interval(100);
  14098. sse.set_max_reconnect_attempts(3);
  14099. sse.start_async();
  14100. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14101. sse.stop();
  14102. std::lock_guard<std::mutex> lock(token_mutex);
  14103. ASSERT_GE(received_tokens.size(), 2u);
  14104. // First connection uses original header
  14105. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14106. // Second connection uses updated header from set_headers
  14107. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14108. }
  14109. // Test: 401 allows reconnection (so on_error can refresh headers)
  14110. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14111. std::atomic<int> connection_count{0};
  14112. // Endpoint: returns 401 on first attempt, 200 on second
  14113. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14114. int conn = connection_count.fetch_add(1);
  14115. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14116. res.status = StatusCode::Unauthorized_401;
  14117. res.set_content("Unauthorized", "text/plain");
  14118. return;
  14119. }
  14120. res.set_chunked_content_provider(
  14121. "text/event-stream", [](size_t offset, DataSink &sink) {
  14122. if (offset == 0) {
  14123. std::string event = "data: authenticated\n\n";
  14124. sink.write(event.data(), event.size());
  14125. }
  14126. return false;
  14127. });
  14128. });
  14129. Client client("localhost", get_port());
  14130. Headers headers = {{"Authorization", "Bearer expired"}};
  14131. sse::SSEClient sse(client, "/auth-retry", headers);
  14132. std::atomic<bool> message_received{false};
  14133. // Refresh token on error
  14134. sse.on_error(
  14135. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14136. sse.on_message([&](const sse::SSEMessage &msg) {
  14137. if (msg.data == "authenticated") { message_received.store(true); }
  14138. });
  14139. sse.set_reconnect_interval(100);
  14140. sse.set_max_reconnect_attempts(3);
  14141. sse.start_async();
  14142. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14143. sse.stop();
  14144. // Should have reconnected after 401 and succeeded with new token
  14145. EXPECT_GE(connection_count.load(), 2);
  14146. EXPECT_TRUE(message_received.load());
  14147. }
  14148. TEST(Issue2318Test, EmptyHostString) {
  14149. {
  14150. httplib::Client cli_empty("", PORT);
  14151. auto res = cli_empty.Get("/");
  14152. ASSERT_FALSE(res);
  14153. EXPECT_EQ(httplib::Error::Connection, res.error());
  14154. }
  14155. {
  14156. httplib::Client cli(" ", PORT);
  14157. auto res = cli.Get("/");
  14158. ASSERT_FALSE(res);
  14159. EXPECT_EQ(httplib::Error::Connection, res.error());
  14160. }
  14161. }
  14162. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14163. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14164. Server svr;
  14165. // Set a small payload limit (1KB)
  14166. svr.set_payload_max_length(1024);
  14167. svr.Post("/test", [&](const Request &req, Response &res) {
  14168. res.set_content("Body size: " + std::to_string(req.body.size()),
  14169. "text/plain");
  14170. });
  14171. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14172. auto se = detail::scope_exit([&] {
  14173. svr.stop();
  14174. listen_thread.join();
  14175. });
  14176. svr.wait_until_ready();
  14177. // Create data that compresses well but exceeds limit when decompressed
  14178. // 8KB of repeated null bytes compresses to a very small size
  14179. std::string original_data(8 * 1024, '\0');
  14180. // Compress the data using gzip
  14181. std::string compressed_data;
  14182. detail::gzip_compressor compressor;
  14183. compressor.compress(original_data.data(), original_data.size(), true,
  14184. [&](const char *data, size_t size) {
  14185. compressed_data.append(data, size);
  14186. return true;
  14187. });
  14188. // Verify compression worked (compressed should be much smaller)
  14189. ASSERT_LT(compressed_data.size(), original_data.size());
  14190. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14191. // Send compressed data with Content-Encoding: gzip
  14192. Client cli(HOST, PORT);
  14193. Headers headers = {{"Content-Encoding", "gzip"}};
  14194. auto res =
  14195. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14196. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14197. ASSERT_TRUE(res);
  14198. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14199. }
  14200. #endif
  14201. // ============================================================================
  14202. // OpenSSL-Specific Tests
  14203. // ============================================================================
  14204. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14205. X509 *readCertificate(const std::string &strFileName) {
  14206. std::ifstream inStream(strFileName);
  14207. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14208. std::istreambuf_iterator<char>());
  14209. if (strCertPEM.empty()) return (nullptr);
  14210. BIO *pbCert = BIO_new(BIO_s_mem());
  14211. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14212. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14213. BIO_free(pbCert);
  14214. return (pCert);
  14215. }
  14216. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14217. std::ifstream inStream(strFileName);
  14218. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14219. std::istreambuf_iterator<char>());
  14220. if (strPrivateKeyPEM.empty()) return (nullptr);
  14221. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14222. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14223. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14224. BIO_free(pbPrivKey);
  14225. return (pPrivateKey);
  14226. }
  14227. TEST(BindServerTest, UpdateCerts) {
  14228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14229. int port = svr.bind_to_any_port("0.0.0.0");
  14230. ASSERT_TRUE(svr.is_valid());
  14231. ASSERT_TRUE(port > 0);
  14232. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14233. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14234. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14235. ASSERT_TRUE(cert != nullptr);
  14236. ASSERT_TRUE(ca_cert != nullptr);
  14237. ASSERT_TRUE(key != nullptr);
  14238. X509_STORE *cert_store = X509_STORE_new();
  14239. X509_STORE_add_cert(cert_store, ca_cert);
  14240. // svr.update_certs(cert, key, cert_store); // deprecated
  14241. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14242. CLIENT_CA_CERT_FILE);
  14243. ASSERT_TRUE(svr.is_valid());
  14244. svr.stop();
  14245. X509_STORE_free(cert_store);
  14246. X509_free(cert);
  14247. X509_free(ca_cert);
  14248. EVP_PKEY_free(key);
  14249. }
  14250. // Test that update_certs() updates client CA list correctly
  14251. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14252. // Start with file-based constructor
  14253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14254. ASSERT_TRUE(svr.is_valid());
  14255. // Initially no client CA list should be set
  14256. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14257. ASSERT_TRUE(ssl_ctx != nullptr);
  14258. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14259. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14260. EXPECT_EQ(0, count_before);
  14261. // Now update with client CA (PEM string)
  14262. std::string cert_pem, key_pem, ca_pem;
  14263. read_file(SERVER_CERT_FILE, cert_pem);
  14264. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14265. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14266. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14267. ASSERT_TRUE(svr.is_valid());
  14268. // Now client CA list should be set
  14269. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14270. ASSERT_TRUE(ca_list_after != nullptr);
  14271. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14272. }
  14273. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14274. // Test that the file-path SSLServer constructor properly sets the client CA
  14275. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14277. ASSERT_TRUE(svr.is_valid());
  14278. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14279. ASSERT_TRUE(ssl_ctx != nullptr);
  14280. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14281. ASSERT_TRUE(ca_list != nullptr);
  14282. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14283. }
  14284. #endif
  14285. // ============================================================================
  14286. // MbedTLS-Specific Tests
  14287. // ============================================================================
  14288. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14289. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14290. using namespace httplib::tls;
  14291. // Track if callback was invoked
  14292. bool callback_invoked = false;
  14293. // The callback receives void* ctx which is actually MbedTlsContext*
  14294. // We can access the mbedtls_ssl_config via the context
  14295. auto setup_callback = [&callback_invoked](void *ctx) {
  14296. callback_invoked = true;
  14297. // Cast to MbedTlsContext* to access the ssl config
  14298. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14299. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14300. // Use static variables to hold certificate data (simplified for test)
  14301. static mbedtls_x509_crt own_cert;
  14302. static mbedtls_pk_context own_key;
  14303. static mbedtls_x509_crt ca_chain;
  14304. static bool initialized = false;
  14305. if (!initialized) {
  14306. mbedtls_x509_crt_init(&own_cert);
  14307. mbedtls_pk_init(&own_key);
  14308. mbedtls_x509_crt_init(&ca_chain);
  14309. // Load server certificate
  14310. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14311. return false;
  14312. }
  14313. // Load server private key
  14314. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14315. #if MBEDTLS_VERSION_MAJOR >= 3
  14316. ,
  14317. mbedtls_ctr_drbg_random, nullptr
  14318. #endif
  14319. ) != 0) {
  14320. return false;
  14321. }
  14322. // Load CA chain for client verification
  14323. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14324. return false;
  14325. }
  14326. initialized = true;
  14327. }
  14328. // Configure the SSL config
  14329. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14330. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14331. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14332. // Set minimum TLS version using mbedTLS native API
  14333. #if MBEDTLS_VERSION_MAJOR >= 3
  14334. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14335. #else
  14336. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14337. MBEDTLS_SSL_MINOR_VERSION_3);
  14338. #endif
  14339. return true;
  14340. };
  14341. SSLServer svr(setup_callback);
  14342. ASSERT_TRUE(svr.is_valid());
  14343. ASSERT_TRUE(callback_invoked);
  14344. svr.Get("/test", [&](const Request &req, Response &res) {
  14345. res.set_content("test", "text/plain");
  14346. auto cert = req.peer_cert();
  14347. ASSERT_TRUE(static_cast<bool>(cert));
  14348. auto common_name = cert.subject_cn();
  14349. EXPECT_EQ("Common Name", common_name);
  14350. });
  14351. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14352. auto se = detail::scope_exit([&] {
  14353. svr.stop();
  14354. t.join();
  14355. ASSERT_FALSE(svr.is_running());
  14356. });
  14357. svr.wait_until_ready();
  14358. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14359. cli.enable_server_certificate_verification(false);
  14360. cli.set_connection_timeout(30);
  14361. auto res = cli.Get("/test");
  14362. ASSERT_TRUE(res);
  14363. ASSERT_EQ(StatusCode::OK_200, res->status);
  14364. }
  14365. #endif
  14366. // WebSocket Tests
  14367. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14368. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14369. // defining the meaning of these bits has been negotiated.
  14370. auto make_frame = [](uint8_t first_byte) {
  14371. std::string frame;
  14372. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14373. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14374. frame += "Hello";
  14375. return frame;
  14376. };
  14377. // RSV1 set (0x40)
  14378. {
  14379. detail::BufferStream strm;
  14380. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14381. ws::Opcode opcode;
  14382. std::string payload;
  14383. bool fin;
  14384. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14385. false, 1024));
  14386. }
  14387. // RSV2 set (0x20)
  14388. {
  14389. detail::BufferStream strm;
  14390. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14391. ws::Opcode opcode;
  14392. std::string payload;
  14393. bool fin;
  14394. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14395. false, 1024));
  14396. }
  14397. // RSV3 set (0x10)
  14398. {
  14399. detail::BufferStream strm;
  14400. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14401. ws::Opcode opcode;
  14402. std::string payload;
  14403. bool fin;
  14404. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14405. false, 1024));
  14406. }
  14407. // No RSV bits set - should succeed
  14408. {
  14409. detail::BufferStream strm;
  14410. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14411. ws::Opcode opcode;
  14412. std::string payload;
  14413. bool fin;
  14414. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14415. false, 1024));
  14416. EXPECT_EQ(ws::Opcode::Text, opcode);
  14417. EXPECT_EQ("Hello", payload);
  14418. EXPECT_TRUE(fin);
  14419. }
  14420. }
  14421. TEST(WebSocketTest, ControlFrameValidation) {
  14422. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14423. // payload length <= 125.
  14424. // Ping with FIN=0 - must be rejected
  14425. {
  14426. detail::BufferStream strm;
  14427. std::string frame;
  14428. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14429. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14430. strm.write(frame.data(), frame.size());
  14431. ws::Opcode opcode;
  14432. std::string payload;
  14433. bool fin;
  14434. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14435. false, 1024));
  14436. }
  14437. // Close with FIN=0 - must be rejected
  14438. {
  14439. detail::BufferStream strm;
  14440. std::string frame;
  14441. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14442. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14443. strm.write(frame.data(), frame.size());
  14444. ws::Opcode opcode;
  14445. std::string payload;
  14446. bool fin;
  14447. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14448. false, 1024));
  14449. }
  14450. // Ping with payload_len=126 (extended length) - must be rejected
  14451. {
  14452. detail::BufferStream strm;
  14453. std::string frame;
  14454. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14455. frame += static_cast<char>(126); // payload_len=126 (>125)
  14456. frame += static_cast<char>(0x00); // extended length high byte
  14457. frame += static_cast<char>(126); // extended length low byte
  14458. frame += std::string(126, 'x');
  14459. strm.write(frame.data(), frame.size());
  14460. ws::Opcode opcode;
  14461. std::string payload;
  14462. bool fin;
  14463. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14464. false, 1024));
  14465. }
  14466. // Ping with FIN=1 and payload_len=125 - should succeed
  14467. {
  14468. detail::BufferStream strm;
  14469. std::string frame;
  14470. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14471. frame += static_cast<char>(125); // payload_len=125
  14472. frame += std::string(125, 'x');
  14473. strm.write(frame.data(), frame.size());
  14474. ws::Opcode opcode;
  14475. std::string payload;
  14476. bool fin;
  14477. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14478. false, 1024));
  14479. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14480. EXPECT_EQ(125u, payload.size());
  14481. EXPECT_TRUE(fin);
  14482. }
  14483. }
  14484. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14485. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14486. // length MUST be 0.
  14487. // MSB set - must be rejected
  14488. {
  14489. detail::BufferStream strm;
  14490. std::string frame;
  14491. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14492. frame += static_cast<char>(127); // 64-bit extended length
  14493. frame += static_cast<char>(0x80); // MSB set (invalid)
  14494. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14495. strm.write(frame.data(), frame.size());
  14496. ws::Opcode opcode;
  14497. std::string payload;
  14498. bool fin;
  14499. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14500. false, 1024));
  14501. }
  14502. // MSB clear - should pass length parsing (will be rejected by max_len,
  14503. // but that's a different check; use a small length to verify)
  14504. {
  14505. detail::BufferStream strm;
  14506. std::string frame;
  14507. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14508. frame += static_cast<char>(127); // 64-bit extended length
  14509. frame += std::string(7, '\0'); // high bytes = 0
  14510. frame += static_cast<char>(0x03); // length = 3
  14511. frame += "abc";
  14512. strm.write(frame.data(), frame.size());
  14513. ws::Opcode opcode;
  14514. std::string payload;
  14515. bool fin;
  14516. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14517. false, 1024));
  14518. EXPECT_EQ(ws::Opcode::Text, opcode);
  14519. EXPECT_EQ("abc", payload);
  14520. }
  14521. }
  14522. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14523. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14524. // Valid UTF-8
  14525. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14526. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14527. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14528. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14529. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14530. // Invalid UTF-8
  14531. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14532. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14533. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14534. EXPECT_FALSE(
  14535. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14536. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14537. }
  14538. TEST(WebSocketTest, ConnectAndDisconnect) {
  14539. Server svr;
  14540. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14541. std::string msg;
  14542. while (ws.read(msg)) {}
  14543. });
  14544. auto port = svr.bind_to_any_port(HOST);
  14545. std::thread t([&]() { svr.listen_after_bind(); });
  14546. svr.wait_until_ready();
  14547. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14548. ASSERT_TRUE(client.connect());
  14549. EXPECT_TRUE(client.is_open());
  14550. client.close();
  14551. EXPECT_FALSE(client.is_open());
  14552. svr.stop();
  14553. t.join();
  14554. }
  14555. TEST(WebSocketTest, ValidURL) {
  14556. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14557. EXPECT_TRUE(ws1.is_valid());
  14558. ws::WebSocketClient ws2("ws://example.com/path");
  14559. EXPECT_TRUE(ws2.is_valid());
  14560. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14561. EXPECT_TRUE(ws3.is_valid());
  14562. #ifdef CPPHTTPLIB_SSL_ENABLED
  14563. ws::WebSocketClient wss1("wss://example.com/path");
  14564. EXPECT_TRUE(wss1.is_valid());
  14565. ws::WebSocketClient wss2("wss://example.com:443/path");
  14566. EXPECT_TRUE(wss2.is_valid());
  14567. #endif
  14568. }
  14569. TEST(WebSocketTest, InvalidURL) {
  14570. // No scheme
  14571. ws::WebSocketClient ws1("localhost:8080/path");
  14572. EXPECT_FALSE(ws1.is_valid());
  14573. // No path
  14574. ws::WebSocketClient ws2("ws://localhost:8080");
  14575. EXPECT_FALSE(ws2.is_valid());
  14576. // Empty string
  14577. ws::WebSocketClient ws3("");
  14578. EXPECT_FALSE(ws3.is_valid());
  14579. // Missing host
  14580. ws::WebSocketClient ws4("ws://:8080/path");
  14581. EXPECT_FALSE(ws4.is_valid());
  14582. // Port number overflow — should not crash
  14583. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14584. EXPECT_FALSE(ws5.is_valid());
  14585. // Port out of range
  14586. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14587. EXPECT_FALSE(ws6.is_valid());
  14588. }
  14589. TEST(WebSocketTest, UnsupportedScheme) {
  14590. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14591. ws::WebSocketClient ws1("http://localhost:8080/path");
  14592. EXPECT_FALSE(ws1.is_valid());
  14593. ws::WebSocketClient ws2("https://localhost:8080/path");
  14594. EXPECT_FALSE(ws2.is_valid());
  14595. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14596. EXPECT_FALSE(ws3.is_valid());
  14597. #else
  14598. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14599. std::invalid_argument);
  14600. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14601. std::invalid_argument);
  14602. #endif
  14603. }
  14604. TEST(WebSocketTest, ConnectWhenInvalid) {
  14605. ws::WebSocketClient ws("not a valid url");
  14606. EXPECT_FALSE(ws.is_valid());
  14607. EXPECT_FALSE(ws.connect());
  14608. }
  14609. TEST(WebSocketTest, DefaultPort) {
  14610. ws::WebSocketClient ws1("ws://example.com/path");
  14611. EXPECT_TRUE(ws1.is_valid());
  14612. // ws:// defaults to port 80 (verified by successful parse)
  14613. #ifdef CPPHTTPLIB_SSL_ENABLED
  14614. ws::WebSocketClient ws2("wss://example.com/path");
  14615. EXPECT_TRUE(ws2.is_valid());
  14616. // wss:// defaults to port 443 (verified by successful parse)
  14617. #endif
  14618. }
  14619. TEST(WebSocketTest, IPv6LiteralAddress) {
  14620. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14621. EXPECT_TRUE(ws1.is_valid());
  14622. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14623. EXPECT_TRUE(ws2.is_valid());
  14624. }
  14625. TEST(WebSocketTest, ComplexPath) {
  14626. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14627. EXPECT_TRUE(ws1.is_valid());
  14628. ws::WebSocketClient ws2("ws://localhost:8080/");
  14629. EXPECT_TRUE(ws2.is_valid());
  14630. }
  14631. class WebSocketIntegrationTest : public ::testing::Test {
  14632. protected:
  14633. void SetUp() override {
  14634. server_ = httplib::detail::make_unique<Server>();
  14635. setup_server();
  14636. start_server();
  14637. }
  14638. void TearDown() override {
  14639. server_->stop();
  14640. if (server_thread_.joinable()) { server_thread_.join(); }
  14641. }
  14642. void setup_server() {
  14643. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14644. std::string msg;
  14645. ws::ReadResult ret;
  14646. while ((ret = ws.read(msg))) {
  14647. if (ret == ws::Binary) {
  14648. ws.send(msg.data(), msg.size());
  14649. } else {
  14650. ws.send(msg);
  14651. }
  14652. }
  14653. });
  14654. server_->WebSocket("/ws-echo-string",
  14655. [](const Request &, ws::WebSocket &ws) {
  14656. std::string msg;
  14657. while (ws.read(msg)) {
  14658. ws.send("echo: " + msg);
  14659. }
  14660. });
  14661. server_->WebSocket(
  14662. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14663. // Echo back request metadata
  14664. ws.send("path:" + req.path);
  14665. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14666. std::string msg;
  14667. while (ws.read(msg)) {}
  14668. });
  14669. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14670. std::string msg;
  14671. ws.read(msg); // wait for a message
  14672. ws.close();
  14673. });
  14674. server_->WebSocket("/ws-close-status",
  14675. [](const Request &, ws::WebSocket &ws) {
  14676. std::string msg;
  14677. ws.read(msg); // wait for a message
  14678. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14679. });
  14680. server_->WebSocket(
  14681. "/ws-subprotocol",
  14682. [](const Request &, ws::WebSocket &ws) {
  14683. std::string msg;
  14684. while (ws.read(msg)) {
  14685. ws.send(msg);
  14686. }
  14687. },
  14688. [](const std::vector<std::string> &protocols) -> std::string {
  14689. for (const auto &p : protocols) {
  14690. if (p == "graphql-ws") { return p; }
  14691. }
  14692. return "";
  14693. });
  14694. }
  14695. void start_server() {
  14696. port_ = server_->bind_to_any_port(HOST);
  14697. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14698. server_->wait_until_ready();
  14699. }
  14700. std::unique_ptr<Server> server_;
  14701. std::thread server_thread_;
  14702. int port_ = 0;
  14703. };
  14704. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14705. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14706. "/ws-echo");
  14707. ASSERT_TRUE(client.connect());
  14708. ASSERT_TRUE(client.is_open());
  14709. ASSERT_TRUE(client.send("Hello WebSocket"));
  14710. std::string msg;
  14711. EXPECT_EQ(ws::Text, client.read(msg));
  14712. EXPECT_EQ("Hello WebSocket", msg);
  14713. client.close();
  14714. }
  14715. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14716. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14717. "/ws-echo");
  14718. ASSERT_TRUE(client.connect());
  14719. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14720. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14721. std::string msg;
  14722. EXPECT_EQ(ws::Binary, client.read(msg));
  14723. EXPECT_EQ(binary_data, msg);
  14724. client.close();
  14725. }
  14726. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14727. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14728. "/ws-echo");
  14729. ASSERT_TRUE(client.connect());
  14730. for (int i = 0; i < 10; i++) {
  14731. auto text = "message " + std::to_string(i);
  14732. ASSERT_TRUE(client.send(text));
  14733. std::string msg;
  14734. ASSERT_TRUE(client.read(msg));
  14735. EXPECT_EQ(text, msg);
  14736. }
  14737. client.close();
  14738. }
  14739. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14741. "/ws-close");
  14742. ASSERT_TRUE(client.connect());
  14743. // Send a message to trigger the server to close
  14744. ASSERT_TRUE(client.send("trigger close"));
  14745. // The server will close, so read should return false
  14746. std::string msg;
  14747. EXPECT_FALSE(client.read(msg));
  14748. EXPECT_FALSE(client.is_open());
  14749. }
  14750. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14751. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14752. "/ws-echo");
  14753. ASSERT_TRUE(client.connect());
  14754. // 128KB message
  14755. std::string large_data(128 * 1024, 'X');
  14756. ASSERT_TRUE(client.send(large_data));
  14757. std::string msg;
  14758. ASSERT_TRUE(client.read(msg));
  14759. EXPECT_EQ(large_data, msg);
  14760. client.close();
  14761. }
  14762. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14764. "/ws-echo");
  14765. ASSERT_TRUE(client.connect());
  14766. const int num_threads = 4;
  14767. std::vector<std::thread> threads;
  14768. std::atomic<int> send_count{0};
  14769. for (int t = 0; t < num_threads; t++) {
  14770. threads.emplace_back([&client, &send_count, t]() {
  14771. for (int i = 0; i < 5; i++) {
  14772. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14773. if (client.send(text)) { send_count++; }
  14774. }
  14775. });
  14776. }
  14777. for (auto &th : threads) {
  14778. th.join();
  14779. }
  14780. int received = 0;
  14781. std::string msg;
  14782. while (received < send_count.load()) {
  14783. if (!client.read(msg)) { break; }
  14784. received++;
  14785. }
  14786. EXPECT_EQ(send_count.load(), received);
  14787. client.close();
  14788. }
  14789. TEST_F(WebSocketIntegrationTest, ReadString) {
  14790. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14791. "/ws-echo-string");
  14792. ASSERT_TRUE(client.connect());
  14793. ASSERT_TRUE(client.send("hello"));
  14794. std::string msg;
  14795. ASSERT_TRUE(client.read(msg));
  14796. EXPECT_EQ("echo: hello", msg);
  14797. ASSERT_TRUE(client.send("world"));
  14798. ASSERT_TRUE(client.read(msg));
  14799. EXPECT_EQ("echo: world", msg);
  14800. client.close();
  14801. }
  14802. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14803. Headers headers = {{"X-Test-Header", "test-value"}};
  14804. ws::WebSocketClient client(
  14805. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14806. ASSERT_TRUE(client.connect());
  14807. std::string msg;
  14808. ASSERT_TRUE(client.read(msg));
  14809. EXPECT_EQ("path:/ws-request-info", msg);
  14810. ASSERT_TRUE(client.read(msg));
  14811. EXPECT_EQ("header:test-value", msg);
  14812. client.close();
  14813. }
  14814. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14815. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14816. "/ws-echo");
  14817. client.set_read_timeout(1, 0); // 1 second
  14818. ASSERT_TRUE(client.connect());
  14819. // Don't send anything — server echo handler waits for a message,
  14820. // so read() should time out and return false.
  14821. std::string msg;
  14822. EXPECT_FALSE(client.read(msg));
  14823. }
  14824. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14825. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14826. "/ws-echo");
  14827. client.set_read_timeout(5, 0);
  14828. ASSERT_TRUE(client.connect());
  14829. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14830. // The server should reject it and close the connection.
  14831. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14832. client.send(oversized);
  14833. // The server's read() should have failed due to payload limit,
  14834. // so our read() should return false (connection closed).
  14835. std::string msg;
  14836. EXPECT_FALSE(client.read(msg));
  14837. }
  14838. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14839. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14840. "/ws-echo");
  14841. client.set_read_timeout(10, 0);
  14842. ASSERT_TRUE(client.connect());
  14843. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14844. // This should succeed.
  14845. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14846. ASSERT_TRUE(client.send(at_limit));
  14847. std::string msg;
  14848. ASSERT_TRUE(client.read(msg));
  14849. EXPECT_EQ(at_limit.size(), msg.size());
  14850. client.close();
  14851. }
  14852. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14853. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14854. "/nonexistent");
  14855. EXPECT_FALSE(client.connect());
  14856. EXPECT_FALSE(client.is_open());
  14857. }
  14858. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14859. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14860. "/ws-echo");
  14861. ASSERT_TRUE(client.connect());
  14862. ASSERT_TRUE(client.send(""));
  14863. std::string msg;
  14864. EXPECT_EQ(ws::Text, client.read(msg));
  14865. EXPECT_EQ("", msg);
  14866. client.close();
  14867. }
  14868. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14869. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14870. "/ws-echo");
  14871. // First connection
  14872. ASSERT_TRUE(client.connect());
  14873. ASSERT_TRUE(client.send("first"));
  14874. std::string msg;
  14875. ASSERT_TRUE(client.read(msg));
  14876. EXPECT_EQ("first", msg);
  14877. client.close();
  14878. EXPECT_FALSE(client.is_open());
  14879. // Reconnect using the same client object
  14880. ASSERT_TRUE(client.connect());
  14881. ASSERT_TRUE(client.is_open());
  14882. ASSERT_TRUE(client.send("second"));
  14883. ASSERT_TRUE(client.read(msg));
  14884. EXPECT_EQ("second", msg);
  14885. client.close();
  14886. }
  14887. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14889. "/ws-close-status");
  14890. ASSERT_TRUE(client.connect());
  14891. // Trigger the server to close with GoingAway status
  14892. ASSERT_TRUE(client.send("trigger"));
  14893. // read() should return false after receiving the close frame
  14894. std::string msg;
  14895. EXPECT_FALSE(client.read(msg));
  14896. EXPECT_FALSE(client.is_open());
  14897. }
  14898. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14899. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14900. "/ws-echo");
  14901. ASSERT_TRUE(client.connect());
  14902. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14903. EXPECT_FALSE(client.is_open());
  14904. }
  14905. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14906. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14907. ws::WebSocketClient client(
  14908. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14909. ASSERT_TRUE(client.connect());
  14910. // Server should have selected graphql-ws
  14911. EXPECT_EQ("graphql-ws", client.subprotocol());
  14912. client.close();
  14913. }
  14914. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14915. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14916. ws::WebSocketClient client(
  14917. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14918. ASSERT_TRUE(client.connect());
  14919. // Server should not have selected any subprotocol
  14920. EXPECT_TRUE(client.subprotocol().empty());
  14921. client.close();
  14922. }
  14923. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14924. // Connect without requesting any subprotocol
  14925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14926. "/ws-subprotocol");
  14927. ASSERT_TRUE(client.connect());
  14928. EXPECT_TRUE(client.subprotocol().empty());
  14929. client.close();
  14930. }
  14931. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14933. "/ws-echo");
  14934. client.set_tcp_nodelay(true);
  14935. client.set_connection_timeout(3, 0);
  14936. bool socket_options_called = false;
  14937. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14938. ASSERT_TRUE(client.connect());
  14939. ASSERT_TRUE(client.is_open());
  14940. EXPECT_TRUE(socket_options_called);
  14941. ASSERT_TRUE(client.send("hello"));
  14942. std::string msg;
  14943. auto result = client.read(msg);
  14944. EXPECT_EQ(result, ws::ReadResult::Text);
  14945. EXPECT_EQ(msg, "hello");
  14946. client.close();
  14947. }
  14948. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14949. Server svr;
  14950. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14951. if (!req.has_header("Authorization")) {
  14952. res.status = StatusCode::Unauthorized_401;
  14953. res.set_content("Unauthorized", "text/plain");
  14954. return Server::HandlerResponse::Handled;
  14955. }
  14956. return Server::HandlerResponse::Unhandled;
  14957. });
  14958. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14959. std::string msg;
  14960. while (ws.read(msg)) {
  14961. ws.send(msg);
  14962. }
  14963. });
  14964. auto port = svr.bind_to_any_port("localhost");
  14965. std::thread t([&]() { svr.listen_after_bind(); });
  14966. svr.wait_until_ready();
  14967. // Without Authorization header - should be rejected before upgrade
  14968. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14969. EXPECT_FALSE(client1.connect());
  14970. // With Authorization header - should succeed
  14971. Headers headers = {{"Authorization", "Bearer token123"}};
  14972. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14973. headers);
  14974. ASSERT_TRUE(client2.connect());
  14975. ASSERT_TRUE(client2.send("hello"));
  14976. std::string msg;
  14977. ASSERT_TRUE(client2.read(msg));
  14978. EXPECT_EQ("hello", msg);
  14979. client2.close();
  14980. svr.stop();
  14981. t.join();
  14982. }
  14983. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14984. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14985. protected:
  14986. void SetUp() override {
  14987. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14988. SERVER_PRIVATE_KEY_FILE);
  14989. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14990. std::string msg;
  14991. ws::ReadResult ret;
  14992. while ((ret = ws.read(msg))) {
  14993. if (ret == ws::Binary) {
  14994. ws.send(msg.data(), msg.size());
  14995. } else {
  14996. ws.send(msg);
  14997. }
  14998. }
  14999. });
  15000. port_ = server_->bind_to_any_port(HOST);
  15001. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15002. server_->wait_until_ready();
  15003. }
  15004. void TearDown() override {
  15005. server_->stop();
  15006. if (server_thread_.joinable()) { server_thread_.join(); }
  15007. }
  15008. std::unique_ptr<SSLServer> server_;
  15009. std::thread server_thread_;
  15010. int port_ = 0;
  15011. };
  15012. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15013. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15014. "/ws-echo");
  15015. client.enable_server_certificate_verification(false);
  15016. ASSERT_TRUE(client.connect());
  15017. ASSERT_TRUE(client.is_open());
  15018. ASSERT_TRUE(client.send("Hello WSS"));
  15019. std::string msg;
  15020. EXPECT_EQ(ws::Text, client.read(msg));
  15021. EXPECT_EQ("Hello WSS", msg);
  15022. client.close();
  15023. }
  15024. #endif
  15025. #if !defined(_WIN32)
  15026. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15027. auto secret_dir = std::string("./symlink_test_secret");
  15028. auto served_dir = std::string("./symlink_test_served");
  15029. auto secret_file = secret_dir + "/secret.txt";
  15030. auto symlink_path = served_dir + "/escape";
  15031. // Setup: create directories and files
  15032. mkdir(secret_dir.c_str(), 0755);
  15033. mkdir(served_dir.c_str(), 0755);
  15034. {
  15035. std::ofstream ofs(secret_file);
  15036. ofs << "SECRET_DATA";
  15037. }
  15038. // Create symlink using absolute path so it resolves correctly
  15039. #ifdef PATH_MAX
  15040. char abs_secret[PATH_MAX];
  15041. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15042. #else
  15043. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15044. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15045. ASSERT_NE(nullptr, abs_secret);
  15046. #endif
  15047. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15048. auto se = detail::scope_exit([&] {
  15049. unlink(symlink_path.c_str());
  15050. unlink(secret_file.c_str());
  15051. rmdir(served_dir.c_str());
  15052. rmdir(secret_dir.c_str());
  15053. });
  15054. Server svr;
  15055. svr.set_mount_point("/", served_dir);
  15056. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15057. auto se2 = detail::scope_exit([&] {
  15058. svr.stop();
  15059. listen_thread.join();
  15060. });
  15061. svr.wait_until_ready();
  15062. Client cli("localhost", PORT);
  15063. // Symlink pointing outside base dir should be blocked
  15064. auto res = cli.Get("/escape/secret.txt");
  15065. ASSERT_TRUE(res);
  15066. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15067. }
  15068. #endif
  15069. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15070. // A GET request with Content-Length to a static file handler must have its
  15071. // body drained before the keep-alive connection is reused. Otherwise the
  15072. // unread body bytes are interpreted as the next HTTP request.
  15073. //
  15074. // The body is sent AFTER receiving the first response (as in the original
  15075. // PoC) so that the stream_line_reader cannot buffer it together with the
  15076. // headers of the first request.
  15077. Server svr;
  15078. svr.set_mount_point("/", "./www");
  15079. std::atomic<int> smuggled_count(0);
  15080. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15081. smuggled_count++;
  15082. res.set_content("oops", "text/plain");
  15083. });
  15084. auto port = svr.bind_to_any_port("localhost");
  15085. thread t = thread([&] { svr.listen_after_bind(); });
  15086. auto se = detail::scope_exit([&] {
  15087. svr.stop();
  15088. t.join();
  15089. });
  15090. svr.wait_until_ready();
  15091. auto error = Error::Success;
  15092. auto sock = detail::create_client_socket(
  15093. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15094. /*connection_timeout_sec=*/2, 0,
  15095. /*read_timeout_sec=*/2, 0,
  15096. /*write_timeout_sec=*/2, 0, std::string(), error);
  15097. ASSERT_NE(INVALID_SOCKET, sock);
  15098. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15099. // The "smuggled" request will be sent as the body of the outer GET
  15100. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15101. "Host: localhost\r\n"
  15102. "Connection: close\r\n"
  15103. "\r\n";
  15104. // Step 1: Send only the outer request headers (no body yet)
  15105. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15106. "Host: localhost\r\n"
  15107. "Content-Length: " +
  15108. std::to_string(smuggled.size()) +
  15109. "\r\n"
  15110. "\r\n";
  15111. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15112. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15113. // Step 2: Read the first response (server serves file without reading body)
  15114. std::string first_response;
  15115. char buf[4096];
  15116. for (;;) {
  15117. auto n = recv(sock, buf, sizeof(buf), 0);
  15118. if (n <= 0) break;
  15119. first_response.append(buf, static_cast<size_t>(n));
  15120. // Stop once we have a complete response (headers + body)
  15121. auto hdr_end = first_response.find("\r\n\r\n");
  15122. if (hdr_end != std::string::npos) {
  15123. // Check for Content-Length to know when the body is complete
  15124. auto cl_pos = first_response.find("Content-Length:");
  15125. if (cl_pos != std::string::npos) {
  15126. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15127. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15128. auto cl = std::stoul(
  15129. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15130. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15131. } else {
  15132. break; // No Content-Length, assume headers-only response
  15133. }
  15134. }
  15135. }
  15136. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15137. // Step 3: Now send the body, which looks like a new HTTP request.
  15138. // On a vulnerable server the keep-alive loop reads this as a second request.
  15139. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15140. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15141. // Step 4: Try to read a second response (should NOT exist after fix)
  15142. std::string second_response;
  15143. for (;;) {
  15144. auto n = recv(sock, buf, sizeof(buf), 0);
  15145. if (n <= 0) break;
  15146. second_response.append(buf, static_cast<size_t>(n));
  15147. }
  15148. // The smuggled request must NOT have been processed
  15149. EXPECT_EQ(0, smuggled_count.load());
  15150. }
  15151. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15152. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15153. // must be rejected with 400 Bad Request.
  15154. Server svr;
  15155. svr.Post("/test", [&](const Request &, Response &res) {
  15156. res.set_content("ok", "text/plain");
  15157. });
  15158. thread t = thread([&] { svr.listen(HOST, PORT); });
  15159. auto se = detail::scope_exit([&] {
  15160. svr.stop();
  15161. t.join();
  15162. ASSERT_FALSE(svr.is_running());
  15163. });
  15164. svr.wait_until_ready();
  15165. // Exact "chunked"
  15166. {
  15167. auto req = "POST /test HTTP/1.1\r\n"
  15168. "Host: localhost\r\n"
  15169. "Content-Length: 5\r\n"
  15170. "Transfer-Encoding: chunked\r\n"
  15171. "Connection: close\r\n"
  15172. "\r\n"
  15173. "hello";
  15174. std::string response;
  15175. ASSERT_TRUE(send_request(1, req, &response));
  15176. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15177. response.substr(0, response.find("\r\n")));
  15178. }
  15179. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15180. {
  15181. auto req = "POST /test HTTP/1.1\r\n"
  15182. "Host: localhost\r\n"
  15183. "Content-Length: 5\r\n"
  15184. "Transfer-Encoding: gzip, chunked\r\n"
  15185. "Connection: close\r\n"
  15186. "\r\n"
  15187. "hello";
  15188. std::string response;
  15189. ASSERT_TRUE(send_request(1, req, &response));
  15190. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15191. response.substr(0, response.find("\r\n")));
  15192. }
  15193. }
  15194. // Regression for issue #2450: a DELETE without Content-Length on a
  15195. // keep-alive connection must not let the post-response drain consume the
  15196. // next request's bytes.
  15197. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15198. Server svr;
  15199. std::atomic<int> delete_count(0);
  15200. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15201. delete_count++;
  15202. res.status = StatusCode::NoContent_204;
  15203. });
  15204. auto port = svr.bind_to_any_port(HOST);
  15205. thread t = thread([&] { svr.listen_after_bind(); });
  15206. auto se = detail::scope_exit([&] {
  15207. svr.stop();
  15208. t.join();
  15209. });
  15210. svr.wait_until_ready();
  15211. auto error = Error::Success;
  15212. auto sock = detail::create_client_socket(
  15213. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15214. /*connection_timeout_sec=*/2, 0,
  15215. /*read_timeout_sec=*/2, 0,
  15216. /*write_timeout_sec=*/2, 0, std::string(), error);
  15217. ASSERT_NE(INVALID_SOCKET, sock);
  15218. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15219. auto send_request_and_read_response = [&](const std::string &req,
  15220. std::string &out) -> bool {
  15221. auto sent = send(sock, req.data(), req.size(), 0);
  15222. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15223. char buf[4096];
  15224. for (;;) {
  15225. auto n = recv(sock, buf, sizeof(buf), 0);
  15226. if (n <= 0) { return !out.empty(); }
  15227. out.append(buf, static_cast<size_t>(n));
  15228. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  15229. }
  15230. };
  15231. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  15232. "Host: localhost\r\n"
  15233. "\r\n";
  15234. std::string resp1;
  15235. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  15236. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  15237. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  15238. "Host: localhost\r\n"
  15239. "Connection: close\r\n"
  15240. "\r\n";
  15241. std::string resp2;
  15242. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  15243. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  15244. EXPECT_EQ(2, delete_count.load());
  15245. }
  15246. namespace no_proxy_test {
  15247. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  15248. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  15249. // calling listen().
  15250. class ScopedServer {
  15251. public:
  15252. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  15253. ~ScopedServer() {
  15254. svr_.stop();
  15255. if (th_.joinable()) { th_.join(); }
  15256. }
  15257. Server &svr() { return svr_; }
  15258. int port() const { return port_; }
  15259. void listen() {
  15260. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15261. svr_.wait_until_ready();
  15262. }
  15263. private:
  15264. Server svr_;
  15265. std::thread th_;
  15266. int port_ = 0;
  15267. };
  15268. class ProxyAndTargetServers {
  15269. public:
  15270. ProxyAndTargetServers() {
  15271. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  15272. proxy_hits_++;
  15273. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15274. res.set_content("via-proxy", "text/plain");
  15275. });
  15276. target_.Get(".*", [this](const Request &req, Response &res) {
  15277. target_hits_++;
  15278. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15279. res.set_content("direct", "text/plain");
  15280. });
  15281. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  15282. target_port_ = target_.bind_to_any_port("127.0.0.1");
  15283. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  15284. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  15285. proxy_mock_.wait_until_ready();
  15286. target_.wait_until_ready();
  15287. }
  15288. ~ProxyAndTargetServers() {
  15289. proxy_mock_.stop();
  15290. target_.stop();
  15291. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  15292. if (target_thread_.joinable()) { target_thread_.join(); }
  15293. }
  15294. Server &proxy_mock() { return proxy_mock_; }
  15295. Server &target() { return target_; }
  15296. int proxy_port() const { return proxy_port_; }
  15297. int target_port() const { return target_port_; }
  15298. int proxy_hits() const { return proxy_hits_.load(); }
  15299. int target_hits() const { return target_hits_.load(); }
  15300. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  15301. void reset_counters() {
  15302. proxy_hits_ = 0;
  15303. target_hits_ = 0;
  15304. last_had_proxy_authz_ = false;
  15305. }
  15306. private:
  15307. Server proxy_mock_;
  15308. Server target_;
  15309. std::thread proxy_thread_;
  15310. std::thread target_thread_;
  15311. int proxy_port_ = 0;
  15312. int target_port_ = 0;
  15313. std::atomic<int> proxy_hits_{0};
  15314. std::atomic<int> target_hits_{0};
  15315. std::atomic<bool> last_had_proxy_authz_{false};
  15316. };
  15317. inline std::unique_ptr<Client> make_client(const std::string &host,
  15318. ProxyAndTargetServers &s) {
  15319. auto cli = detail::make_unique<Client>(host, s.target_port());
  15320. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  15321. cli->set_proxy("127.0.0.1", s.proxy_port());
  15322. return cli;
  15323. }
  15324. } // namespace no_proxy_test
  15325. using no_proxy_test::make_client;
  15326. using no_proxy_test::ProxyAndTargetServers;
  15327. TEST(NoProxyTest, ExactHostnameBypasses) {
  15328. ProxyAndTargetServers s;
  15329. auto cli = make_client("example.com", s);
  15330. cli->set_no_proxy({"example.com"});
  15331. auto res = cli->Get("/");
  15332. ASSERT_TRUE(res);
  15333. EXPECT_EQ(0, s.proxy_hits());
  15334. EXPECT_EQ(1, s.target_hits());
  15335. }
  15336. TEST(NoProxyTest, SubdomainBypasses) {
  15337. ProxyAndTargetServers s;
  15338. auto cli = make_client("foo.example.com", s);
  15339. cli->set_no_proxy({"example.com"});
  15340. auto res = cli->Get("/");
  15341. ASSERT_TRUE(res);
  15342. EXPECT_EQ(0, s.proxy_hits());
  15343. EXPECT_EQ(1, s.target_hits());
  15344. }
  15345. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  15346. // Regression guard: "evilexample.com" must not be considered a subdomain
  15347. // of "example.com". Without the dot-boundary rule, a naive endsWith
  15348. // check would let traffic bypass the proxy and leak credentials direct
  15349. // to the attacker host.
  15350. ProxyAndTargetServers s;
  15351. auto cli = make_client("evilexample.com", s);
  15352. cli->set_no_proxy({"example.com"});
  15353. auto res = cli->Get("/");
  15354. ASSERT_TRUE(res);
  15355. EXPECT_GE(s.proxy_hits(), 1);
  15356. EXPECT_EQ(0, s.target_hits());
  15357. }
  15358. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  15359. ProxyAndTargetServers s;
  15360. auto cli = make_client("example.com.evil.com", s);
  15361. cli->set_no_proxy({"example.com"});
  15362. auto res = cli->Get("/");
  15363. ASSERT_TRUE(res);
  15364. EXPECT_GE(s.proxy_hits(), 1);
  15365. EXPECT_EQ(0, s.target_hits());
  15366. }
  15367. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  15368. ProxyAndTargetServers s;
  15369. auto cli = make_client("example.com", s);
  15370. cli->set_no_proxy({".example.com"});
  15371. auto res = cli->Get("/");
  15372. ASSERT_TRUE(res);
  15373. EXPECT_EQ(0, s.proxy_hits());
  15374. EXPECT_EQ(1, s.target_hits());
  15375. }
  15376. TEST(NoProxyTest, CaseInsensitiveHostname) {
  15377. ProxyAndTargetServers s;
  15378. auto cli = make_client("Example.COM", s);
  15379. cli->set_no_proxy({"EXAMPLE.com"});
  15380. auto res = cli->Get("/");
  15381. ASSERT_TRUE(res);
  15382. EXPECT_EQ(0, s.proxy_hits());
  15383. EXPECT_EQ(1, s.target_hits());
  15384. }
  15385. TEST(NoProxyTest, TrailingDotIsNormalized) {
  15386. ProxyAndTargetServers s;
  15387. auto cli = make_client("example.com.", s);
  15388. cli->set_no_proxy({"example.com"});
  15389. auto res = cli->Get("/");
  15390. ASSERT_TRUE(res);
  15391. EXPECT_EQ(0, s.proxy_hits());
  15392. EXPECT_EQ(1, s.target_hits());
  15393. }
  15394. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  15395. // Trailing dots must be normalized on BOTH sides — host and entry.
  15396. // An implementation that only strips the host-side trailing dot would
  15397. // fail to match host "example.com" against entry "example.com." because
  15398. // a literal substring search would compare 11 chars against 12.
  15399. ProxyAndTargetServers s;
  15400. auto cli = make_client("example.com", s);
  15401. cli->set_no_proxy({"example.com."});
  15402. auto res = cli->Get("/");
  15403. ASSERT_TRUE(res);
  15404. EXPECT_EQ(0, s.proxy_hits());
  15405. EXPECT_EQ(1, s.target_hits());
  15406. }
  15407. TEST(NoProxyTest, WildcardBypassesEverything) {
  15408. ProxyAndTargetServers s;
  15409. auto cli = make_client("anything.invalid.test", s);
  15410. cli->set_no_proxy({"*"});
  15411. auto res = cli->Get("/");
  15412. ASSERT_TRUE(res);
  15413. EXPECT_EQ(0, s.proxy_hits());
  15414. EXPECT_EQ(1, s.target_hits());
  15415. }
  15416. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  15417. ProxyAndTargetServers s;
  15418. Client cli("127.0.0.1", s.target_port());
  15419. cli.set_proxy("127.0.0.1", s.proxy_port());
  15420. cli.set_no_proxy({"127.0.0.1"});
  15421. auto res = cli.Get("/");
  15422. ASSERT_TRUE(res);
  15423. EXPECT_EQ(0, s.proxy_hits());
  15424. EXPECT_EQ(1, s.target_hits());
  15425. }
  15426. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  15427. ProxyAndTargetServers s;
  15428. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  15429. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  15430. cli.set_proxy("127.0.0.1", s.proxy_port());
  15431. cli.set_no_proxy({"::1"});
  15432. auto res = cli.Get("/");
  15433. ASSERT_TRUE(res);
  15434. EXPECT_EQ(0, s.proxy_hits());
  15435. EXPECT_EQ(1, s.target_hits());
  15436. }
  15437. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  15438. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  15439. // must still be recognized as IPv6 for CIDR matching. Implementations
  15440. // that detect IPv6 only when the host begins with '[' would parse the
  15441. // host as a hostname and miss the match.
  15442. ProxyAndTargetServers s;
  15443. Client cli("fe80::1", s.target_port());
  15444. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  15445. cli.set_proxy("127.0.0.1", s.proxy_port());
  15446. cli.set_no_proxy({"fe80::/10"});
  15447. auto res = cli.Get("/");
  15448. ASSERT_TRUE(res);
  15449. EXPECT_EQ(0, s.proxy_hits());
  15450. EXPECT_EQ(1, s.target_hits());
  15451. }
  15452. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  15453. ProxyAndTargetServers s;
  15454. Client cli("::1", s.target_port());
  15455. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  15456. cli.set_proxy("127.0.0.1", s.proxy_port());
  15457. cli.set_no_proxy({"[::1]"});
  15458. auto res = cli.Get("/");
  15459. ASSERT_TRUE(res);
  15460. EXPECT_EQ(0, s.proxy_hits());
  15461. EXPECT_EQ(1, s.target_hits());
  15462. }
  15463. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  15464. ProxyAndTargetServers s;
  15465. Client cli("fe80::1", s.target_port());
  15466. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  15467. cli.set_proxy("127.0.0.1", s.proxy_port());
  15468. cli.set_no_proxy({"[fe80::]/10"});
  15469. auto res = cli.Get("/");
  15470. ASSERT_TRUE(res);
  15471. EXPECT_EQ(0, s.proxy_hits());
  15472. EXPECT_EQ(1, s.target_hits());
  15473. }
  15474. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  15475. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  15476. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  15477. // tricks via address-family conversion.
  15478. ProxyAndTargetServers s;
  15479. Client cli("::ffff:127.0.0.1", s.target_port());
  15480. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  15481. cli.set_proxy("127.0.0.1", s.proxy_port());
  15482. cli.set_no_proxy({"127.0.0.1"});
  15483. auto res = cli.Get("/");
  15484. ASSERT_TRUE(res);
  15485. EXPECT_GE(s.proxy_hits(), 1);
  15486. EXPECT_EQ(0, s.target_hits());
  15487. }
  15488. TEST(NoProxyTest, IPv4CidrMatch) {
  15489. ProxyAndTargetServers s;
  15490. Client cli("127.0.0.1", s.target_port());
  15491. cli.set_proxy("127.0.0.1", s.proxy_port());
  15492. cli.set_no_proxy({"127.0.0.0/8"});
  15493. auto res = cli.Get("/");
  15494. ASSERT_TRUE(res);
  15495. EXPECT_EQ(0, s.proxy_hits());
  15496. EXPECT_EQ(1, s.target_hits());
  15497. }
  15498. TEST(NoProxyTest, IPv4CidrNonMatch) {
  15499. ProxyAndTargetServers s;
  15500. Client cli("127.0.0.1", s.target_port());
  15501. cli.set_proxy("127.0.0.1", s.proxy_port());
  15502. cli.set_no_proxy({"10.0.0.0/8"});
  15503. auto res = cli.Get("/");
  15504. ASSERT_TRUE(res);
  15505. EXPECT_GE(s.proxy_hits(), 1);
  15506. EXPECT_EQ(0, s.target_hits());
  15507. }
  15508. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  15509. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  15510. // IPv4 target matches.
  15511. ProxyAndTargetServers s;
  15512. Client cli("127.0.0.1", s.target_port());
  15513. cli.set_proxy("127.0.0.1", s.proxy_port());
  15514. cli.set_no_proxy({"0.0.0.0/0"});
  15515. auto res = cli.Get("/");
  15516. ASSERT_TRUE(res);
  15517. EXPECT_EQ(0, s.proxy_hits());
  15518. EXPECT_EQ(1, s.target_hits());
  15519. }
  15520. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  15521. ProxyAndTargetServers s;
  15522. Client cli("127.0.0.1", s.target_port());
  15523. cli.set_proxy("127.0.0.1", s.proxy_port());
  15524. cli.set_no_proxy({"127.0.0.1"});
  15525. auto res = cli.Get("/");
  15526. ASSERT_TRUE(res);
  15527. EXPECT_EQ(0, s.proxy_hits());
  15528. EXPECT_EQ(1, s.target_hits());
  15529. }
  15530. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  15531. ProxyAndTargetServers s;
  15532. Client cli("127.0.0.1", s.target_port());
  15533. cli.set_proxy("127.0.0.1", s.proxy_port());
  15534. cli.set_no_proxy({"127.0.0.0/33"});
  15535. auto res = cli.Get("/");
  15536. ASSERT_TRUE(res);
  15537. EXPECT_GE(s.proxy_hits(), 1);
  15538. EXPECT_EQ(0, s.target_hits());
  15539. }
  15540. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  15541. // Empty prefix after the slash must be rejected, not silently treated as /32.
  15542. ProxyAndTargetServers s;
  15543. Client cli("127.0.0.1", s.target_port());
  15544. cli.set_proxy("127.0.0.1", s.proxy_port());
  15545. cli.set_no_proxy({"127.0.0.1/"});
  15546. auto res = cli.Get("/");
  15547. ASSERT_TRUE(res);
  15548. EXPECT_GE(s.proxy_hits(), 1);
  15549. EXPECT_EQ(0, s.target_hits());
  15550. }
  15551. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  15552. ProxyAndTargetServers s;
  15553. auto cli = make_client("internal.corp", s);
  15554. cli->set_proxy_basic_auth("u", "p");
  15555. cli->set_no_proxy({"internal.corp"});
  15556. auto res = cli->Get("/");
  15557. ASSERT_TRUE(res);
  15558. EXPECT_EQ(1, s.target_hits());
  15559. EXPECT_EQ(0, s.proxy_hits());
  15560. EXPECT_FALSE(s.last_had_proxy_authz())
  15561. << "Proxy-Authorization must not be sent direct to the target";
  15562. }
  15563. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  15564. ProxyAndTargetServers s;
  15565. auto cli = make_client("public.example", s);
  15566. cli->set_proxy_basic_auth("u", "p");
  15567. cli->set_no_proxy({"internal.corp"}); // does not match
  15568. auto res = cli->Get("/");
  15569. ASSERT_TRUE(res);
  15570. EXPECT_GE(s.proxy_hits(), 1);
  15571. EXPECT_TRUE(s.last_had_proxy_authz());
  15572. }
  15573. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  15574. ProxyAndTargetServers s;
  15575. auto cli = make_client("anything.test", s);
  15576. auto res = cli->Get("/");
  15577. ASSERT_TRUE(res);
  15578. EXPECT_GE(s.proxy_hits(), 1);
  15579. EXPECT_EQ(0, s.target_hits());
  15580. }
  15581. TEST(NoProxyTest, PortSpecificEntryRejected) {
  15582. ProxyAndTargetServers s;
  15583. auto cli = make_client("example.com", s);
  15584. cli->set_no_proxy({"example.com:8080"});
  15585. auto res = cli->Get("/");
  15586. ASSERT_TRUE(res);
  15587. EXPECT_GE(s.proxy_hits(), 1);
  15588. EXPECT_EQ(0, s.target_hits());
  15589. }
  15590. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  15591. ProxyAndTargetServers s;
  15592. auto cli = make_client("anything.test", s);
  15593. cli->set_no_proxy({"", " ", "\t"});
  15594. auto res = cli->Get("/");
  15595. ASSERT_TRUE(res);
  15596. EXPECT_GE(s.proxy_hits(), 1);
  15597. EXPECT_EQ(0, s.target_hits());
  15598. }
  15599. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  15600. // An entry with leading/trailing whitespace must still match — env-style
  15601. // values are commonly pasted with stray spaces and an implementation
  15602. // that feeds the raw token directly to inet_pton would fail to match
  15603. // valid CIDRs because of the spaces.
  15604. ProxyAndTargetServers s;
  15605. Client cli("127.0.0.1", s.target_port());
  15606. cli.set_proxy("127.0.0.1", s.proxy_port());
  15607. cli.set_no_proxy({" 127.0.0.0/8 "});
  15608. auto res = cli.Get("/");
  15609. ASSERT_TRUE(res);
  15610. EXPECT_EQ(0, s.proxy_hits());
  15611. EXPECT_EQ(1, s.target_hits());
  15612. }
  15613. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  15614. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  15615. // go direct and must NOT carry Proxy-Authorization.
  15616. std::atomic<int> proxy_hits{0};
  15617. std::atomic<int> target_hits{0};
  15618. std::atomic<bool> target_saw_authz{false};
  15619. no_proxy_test::ScopedServer proxy_mock, target;
  15620. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  15621. proxy_hits++;
  15622. res.status = 302;
  15623. res.set_header("Location", "http://127.0.0.1:" +
  15624. std::to_string(target.port()) + "/landed");
  15625. });
  15626. target.svr().Get(".*", [&](const Request &req, Response &res) {
  15627. target_hits++;
  15628. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  15629. res.set_content("direct", "text/plain");
  15630. });
  15631. proxy_mock.listen();
  15632. target.listen();
  15633. Client cli("public.example", target.port());
  15634. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15635. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15636. cli.set_proxy_basic_auth("u", "p");
  15637. cli.set_no_proxy({"127.0.0.1"});
  15638. cli.set_follow_location(true);
  15639. auto res = cli.Get("/redir");
  15640. ASSERT_TRUE(res);
  15641. EXPECT_GE(proxy_hits.load(), 1);
  15642. EXPECT_GE(target_hits.load(), 1);
  15643. EXPECT_FALSE(target_saw_authz.load());
  15644. }
  15645. #ifdef CPPHTTPLIB_SSL_ENABLED
  15646. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  15647. // Direct origin replying 407 must not trigger the digest retry; otherwise
  15648. // proxy creds would be sent to the (possibly hostile) origin.
  15649. std::atomic<int> target_hits{0};
  15650. std::atomic<bool> target_saw_proxy_authz{false};
  15651. no_proxy_test::ScopedServer target;
  15652. target.svr().Get(".*", [&](const Request &req, Response &res) {
  15653. target_hits++;
  15654. if (req.has_header("Proxy-Authorization")) {
  15655. target_saw_proxy_authz = true;
  15656. }
  15657. res.status = StatusCode::ProxyAuthenticationRequired_407;
  15658. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  15659. "nonce=\"abc\", algorithm=MD5");
  15660. });
  15661. target.listen();
  15662. // The proxy address is set to the target's port: the bypass MUST kick in;
  15663. // if it doesn't, the test still routes "via proxy" to the same server and
  15664. // the Proxy-Authorization assertion below catches the leak.
  15665. Client cli("evil.example", target.port());
  15666. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  15667. cli.set_proxy("127.0.0.1", target.port());
  15668. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  15669. cli.set_no_proxy({"evil.example"});
  15670. auto res = cli.Get("/x");
  15671. ASSERT_TRUE(res);
  15672. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  15673. EXPECT_EQ(1, target_hits.load());
  15674. EXPECT_FALSE(target_saw_proxy_authz.load());
  15675. }
  15676. #endif
  15677. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  15678. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  15679. std::atomic<int> proxy_hits{0};
  15680. std::atomic<int> bypass_hits{0};
  15681. std::atomic<bool> proxy_saw_c_url{false};
  15682. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  15683. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  15684. proxy_hits++;
  15685. if (req.path.find("/start") != std::string::npos) {
  15686. res.status = 302;
  15687. res.set_header("Location", "http://127.0.0.1:" +
  15688. std::to_string(bypass_server.port()) +
  15689. "/middle");
  15690. return;
  15691. }
  15692. if (req.path.find("/end") != std::string::npos) {
  15693. proxy_saw_c_url = true;
  15694. res.set_content("c-via-proxy", "text/plain");
  15695. return;
  15696. }
  15697. res.set_content("unexpected", "text/plain");
  15698. });
  15699. // public.example's "advertised" port is arbitrary (the request never lands
  15700. // there — it goes through the proxy), but use a dynamic value to stay
  15701. // friendly with sharded parallel runs.
  15702. int public_port = bypass_server.port();
  15703. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  15704. bypass_hits++;
  15705. res.status = 302;
  15706. res.set_header("Location", "http://public.example:" +
  15707. std::to_string(public_port) + "/end");
  15708. });
  15709. proxy_mock.listen();
  15710. bypass_server.listen();
  15711. Client cli("public.example", public_port);
  15712. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15713. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15714. cli.set_no_proxy({"127.0.0.1"});
  15715. cli.set_follow_location(true);
  15716. auto res = cli.Get("/start");
  15717. ASSERT_TRUE(res);
  15718. EXPECT_EQ(StatusCode::OK_200, res->status);
  15719. EXPECT_EQ("c-via-proxy", res->body);
  15720. EXPECT_GE(proxy_hits.load(), 2);
  15721. EXPECT_GE(bypass_hits.load(), 1);
  15722. EXPECT_TRUE(proxy_saw_c_url.load());
  15723. }
  15724. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  15725. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  15726. // request reconnects to the correct endpoint.
  15727. std::atomic<int> proxy_hits{0};
  15728. std::atomic<int> target_hits{0};
  15729. no_proxy_test::ScopedServer proxy_mock, target;
  15730. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  15731. proxy_hits++;
  15732. res.set_content("via-proxy", "text/plain");
  15733. });
  15734. target.svr().Get(".*", [&](const Request &, Response &res) {
  15735. target_hits++;
  15736. res.set_content("direct", "text/plain");
  15737. });
  15738. proxy_mock.listen();
  15739. target.listen();
  15740. Client cli("public.example", target.port());
  15741. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15742. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15743. cli.set_keep_alive(true);
  15744. auto res1 = cli.Get("/a");
  15745. ASSERT_TRUE(res1);
  15746. EXPECT_EQ("via-proxy", res1->body);
  15747. EXPECT_EQ(1, proxy_hits.load());
  15748. EXPECT_EQ(0, target_hits.load());
  15749. cli.set_no_proxy({"public.example"});
  15750. auto res2 = cli.Get("/b");
  15751. ASSERT_TRUE(res2);
  15752. EXPECT_EQ("direct", res2->body);
  15753. EXPECT_EQ(1, proxy_hits.load());
  15754. EXPECT_EQ(1, target_hits.load());
  15755. }
  15756. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  15757. namespace proxy_tunnel_test {
  15758. // SSLServer counterpart to no_proxy_test::ScopedServer.
  15759. class ScopedSSLServer {
  15760. public:
  15761. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  15762. port_ = svr_.bind_to_any_port("127.0.0.1");
  15763. }
  15764. ~ScopedSSLServer() {
  15765. svr_.stop();
  15766. if (th_.joinable()) { th_.join(); }
  15767. }
  15768. SSLServer &svr() { return svr_; }
  15769. int port() const { return port_; }
  15770. void listen() {
  15771. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15772. svr_.wait_until_ready();
  15773. }
  15774. private:
  15775. SSLServer svr_;
  15776. std::thread th_;
  15777. int port_ = 0;
  15778. };
  15779. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  15780. class ScopedConnectProxy {
  15781. public:
  15782. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  15783. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  15784. if (listen_fd_ < 0) { return; }
  15785. int yes = 1;
  15786. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  15787. sockaddr_in a{};
  15788. a.sin_family = AF_INET;
  15789. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  15790. a.sin_port = 0;
  15791. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  15792. return;
  15793. }
  15794. socklen_t alen = sizeof(a);
  15795. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  15796. 0) {
  15797. return;
  15798. }
  15799. port_ = ntohs(a.sin_port);
  15800. if (::listen(listen_fd_, 1) != 0) { return; }
  15801. th_ = std::thread([this] { run(); });
  15802. }
  15803. ~ScopedConnectProxy() {
  15804. stop_ = true;
  15805. if (listen_fd_ >= 0) {
  15806. ::shutdown(listen_fd_, SHUT_RDWR);
  15807. ::close(listen_fd_);
  15808. }
  15809. if (th_.joinable()) { th_.join(); }
  15810. }
  15811. int port() const { return port_; }
  15812. int connect_hits() const { return connect_hits_.load(); }
  15813. private:
  15814. void run() {
  15815. while (!stop_.load()) {
  15816. fd_set rfds;
  15817. FD_ZERO(&rfds);
  15818. FD_SET(listen_fd_, &rfds);
  15819. timeval tv{0, 100 * 1000};
  15820. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  15821. if (sel <= 0) { continue; }
  15822. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  15823. if (client_fd < 0) { continue; }
  15824. std::string req;
  15825. char buf[2048];
  15826. while (req.find("\r\n\r\n") == std::string::npos) {
  15827. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  15828. if (n <= 0) { break; }
  15829. req.append(buf, static_cast<size_t>(n));
  15830. }
  15831. if (req.compare(0, 7, "CONNECT") != 0) {
  15832. ::close(client_fd);
  15833. continue;
  15834. }
  15835. connect_hits_++;
  15836. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  15837. ::send(client_fd, ok, std::strlen(ok), 0);
  15838. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  15839. sockaddr_in o{};
  15840. o.sin_family = AF_INET;
  15841. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  15842. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  15843. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  15844. 0) {
  15845. ::close(client_fd);
  15846. ::close(origin_fd);
  15847. continue;
  15848. }
  15849. auto forward = [](int from, int to) {
  15850. char b[8192];
  15851. for (;;) {
  15852. ssize_t n = ::recv(from, b, sizeof(b), 0);
  15853. if (n <= 0) { break; }
  15854. ssize_t off = 0;
  15855. while (off < n) {
  15856. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  15857. if (s <= 0) {
  15858. off = n;
  15859. break;
  15860. }
  15861. off += s;
  15862. }
  15863. }
  15864. ::shutdown(to, SHUT_WR);
  15865. };
  15866. std::thread t1([&] { forward(client_fd, origin_fd); });
  15867. std::thread t2([&] { forward(origin_fd, client_fd); });
  15868. t1.join();
  15869. t2.join();
  15870. ::close(client_fd);
  15871. ::close(origin_fd);
  15872. }
  15873. }
  15874. int forward_port_ = -1;
  15875. int listen_fd_ = -1;
  15876. int port_ = 0;
  15877. std::thread th_;
  15878. std::atomic<bool> stop_{false};
  15879. std::atomic<int> connect_hits_{0};
  15880. };
  15881. } // namespace proxy_tunnel_test
  15882. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  15883. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  15884. // retry; otherwise proxy creds would be sent to the origin.
  15885. std::atomic<int> origin_hits{0};
  15886. std::atomic<bool> origin_saw_proxy_authz{false};
  15887. proxy_tunnel_test::ScopedSSLServer origin;
  15888. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  15889. origin_hits++;
  15890. if (req.has_header("Proxy-Authorization")) {
  15891. origin_saw_proxy_authz = true;
  15892. }
  15893. res.status = StatusCode::ProxyAuthenticationRequired_407;
  15894. res.set_header("Proxy-Authenticate",
  15895. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  15896. "algorithm=MD5");
  15897. });
  15898. origin.listen();
  15899. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  15900. ASSERT_NE(0, proxy.port());
  15901. SSLClient cli(HOST, origin.port());
  15902. cli.enable_server_certificate_verification(false);
  15903. cli.set_proxy(HOST, proxy.port());
  15904. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  15905. auto res = cli.Get("/x");
  15906. ASSERT_TRUE(res);
  15907. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  15908. EXPECT_EQ(1, origin_hits.load());
  15909. EXPECT_FALSE(origin_saw_proxy_authz.load());
  15910. EXPECT_EQ(1, proxy.connect_hits());
  15911. }
  15912. #endif