test.cc 615 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  47. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  48. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  49. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  50. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  51. #ifdef CPPHTTPLIB_SSL_ENABLED
  52. namespace httplib {
  53. namespace tls {
  54. // Declared here for the split build, where the TLS abstraction declarations
  55. // live below the split border; the definition is linked from httplib.cc.
  56. ca_store_t create_ca_store(const char *pem, size_t len);
  57. } // namespace tls
  58. } // namespace httplib
  59. #endif
  60. using namespace std;
  61. using namespace httplib;
  62. const char *HOST = "localhost";
  63. static int get_base_port() {
  64. const char *shard = getenv("GTEST_SHARD_INDEX");
  65. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  66. }
  67. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  68. // New standalone tests MUST use svr.bind_to_any_port() instead.
  69. const int PORT = get_base_port();
  70. const string LONG_QUERY_VALUE = string(25000, '@');
  71. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  72. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  73. const string TOO_LONG_QUERY_URL =
  74. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  75. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  76. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  77. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  78. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  79. return file.name == key;
  80. });
  81. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  82. return *it;
  83. #else
  84. if (it != items.end()) { return *it; }
  85. throw std::runtime_error("invalid multipart form data name error");
  86. #endif
  87. }
  88. static void read_file(const std::string &path, std::string &out) {
  89. std::ifstream fs(path, std::ios_base::binary);
  90. if (!fs) {
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return;
  93. #else
  94. throw std::runtime_error("File not found: " + path);
  95. #endif
  96. }
  97. fs.seekg(0, std::ios_base::end);
  98. auto size = fs.tellg();
  99. fs.seekg(0);
  100. out.resize(static_cast<size_t>(size));
  101. fs.read(&out[0], static_cast<std::streamsize>(size));
  102. }
  103. class UnixSocketTest : public ::testing::Test {
  104. protected:
  105. void TearDown() override { std::remove(pathname_.c_str()); }
  106. void client_GET(const std::string &addr) {
  107. httplib::Client cli{addr};
  108. cli.set_address_family(AF_UNIX);
  109. ASSERT_TRUE(cli.is_valid());
  110. const auto &result = cli.Get(pattern_);
  111. ASSERT_TRUE(result) << "error: " << result.error();
  112. const auto &resp = result.value();
  113. EXPECT_EQ(resp.status, StatusCode::OK_200);
  114. EXPECT_EQ(resp.body, content_);
  115. }
  116. static std::string make_sock_path() {
  117. const char *shard = getenv("GTEST_SHARD_INDEX");
  118. return shard ? std::string("./httplib-server-") + shard + ".sock"
  119. : "./httplib-server.sock";
  120. }
  121. const std::string pathname_{make_sock_path()};
  122. const std::string pattern_{"/hi"};
  123. const std::string content_{"Hello World!"};
  124. };
  125. TEST_F(UnixSocketTest, pathname) {
  126. httplib::Server svr;
  127. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  128. res.set_content(content_, "text/plain");
  129. });
  130. std::thread t{[&] {
  131. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  132. }};
  133. auto se = detail::scope_exit([&] {
  134. svr.stop();
  135. t.join();
  136. ASSERT_FALSE(svr.is_running());
  137. });
  138. svr.wait_until_ready();
  139. ASSERT_TRUE(svr.is_running());
  140. client_GET(pathname_);
  141. }
  142. #if defined(__linux__) || \
  143. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  144. TEST_F(UnixSocketTest, PeerPid) {
  145. httplib::Server svr;
  146. std::string remote_port_val;
  147. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  148. res.set_content(content_, "text/plain");
  149. remote_port_val = std::to_string(req.remote_port);
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  163. }
  164. #endif
  165. #ifdef __linux__
  166. TEST_F(UnixSocketTest, abstract) {
  167. constexpr char svr_path[]{"\x00httplib-server.sock"};
  168. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  169. httplib::Server svr;
  170. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  171. res.set_content(content_, "text/plain");
  172. });
  173. std::thread t{[&] {
  174. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  175. }};
  176. auto se = detail::scope_exit([&] {
  177. svr.stop();
  178. t.join();
  179. ASSERT_FALSE(svr.is_running());
  180. });
  181. svr.wait_until_ready();
  182. ASSERT_TRUE(svr.is_running());
  183. client_GET(abstract_addr);
  184. }
  185. #endif
  186. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  187. httplib::Server svr;
  188. std::string received_host_header;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. // Capture the Host header sent by the client
  191. auto host_iter = req.headers.find("Host");
  192. if (host_iter != req.headers.end()) {
  193. received_host_header = host_iter->second;
  194. }
  195. res.set_content(content_, "text/plain");
  196. });
  197. std::thread t{[&] {
  198. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  199. }};
  200. auto se = detail::scope_exit([&] {
  201. svr.stop();
  202. t.join();
  203. ASSERT_FALSE(svr.is_running());
  204. });
  205. svr.wait_until_ready();
  206. ASSERT_TRUE(svr.is_running());
  207. // Test that Host header is automatically set to "localhost" for Unix socket
  208. // connections
  209. httplib::Client cli{pathname_};
  210. cli.set_address_family(AF_UNIX);
  211. ASSERT_TRUE(cli.is_valid());
  212. const auto &result = cli.Get(pattern_);
  213. ASSERT_TRUE(result) << "error: " << result.error();
  214. const auto &resp = result.value();
  215. EXPECT_EQ(resp.status, StatusCode::OK_200);
  216. EXPECT_EQ(resp.body, content_);
  217. // Verify that Host header was automatically set to "localhost"
  218. EXPECT_EQ(received_host_header, "localhost");
  219. }
  220. #ifndef _WIN32
  221. TEST(SocketStream, wait_writable_UNIX) {
  222. int fds[2];
  223. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  224. const auto asSocketStream = [&](socket_t fd,
  225. std::function<bool(Stream &)> func) {
  226. return detail::process_client_socket(
  227. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  228. };
  229. asSocketStream(fds[0], [&](Stream &s0) {
  230. EXPECT_EQ(s0.socket(), fds[0]);
  231. EXPECT_TRUE(s0.wait_writable());
  232. EXPECT_TRUE(s0.is_peer_alive());
  233. EXPECT_EQ(0, close(fds[1]));
  234. EXPECT_FALSE(s0.is_peer_alive());
  235. return true;
  236. });
  237. EXPECT_EQ(0, close(fds[0]));
  238. }
  239. TEST(SocketStream, wait_writable_INET) {
  240. sockaddr_in addr;
  241. memset(&addr, 0, sizeof(addr));
  242. addr.sin_family = AF_INET;
  243. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  244. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  245. int disconnected_svr_sock = -1;
  246. std::thread svr{[&] {
  247. const int s = socket(AF_INET, SOCK_STREAM, 0);
  248. ASSERT_LE(0, s);
  249. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  250. ASSERT_EQ(0, listen(s, 1));
  251. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  252. ASSERT_EQ(0, close(s));
  253. }};
  254. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  255. std::thread cli{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  259. ASSERT_EQ(0, close(s));
  260. }};
  261. cli.join();
  262. svr.join();
  263. ASSERT_NE(disconnected_svr_sock, -1);
  264. const auto asSocketStream = [&](socket_t fd,
  265. std::function<bool(Stream &)> func) {
  266. return detail::process_client_socket(
  267. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  268. };
  269. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  270. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  271. // wait_writable() returns true because select_write() only checks if the
  272. // send buffer has space. Peer disconnection is detected later by send().
  273. EXPECT_TRUE(ss.wait_writable());
  274. return true;
  275. });
  276. ASSERT_EQ(0, close(disconnected_svr_sock));
  277. }
  278. #endif // #ifndef _WIN32
  279. TEST(SetSocketOptTest, TcpNoDelay) {
  280. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  281. ASSERT_NE(sock, INVALID_SOCKET);
  282. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  283. int val = 0;
  284. socklen_t len = sizeof(val);
  285. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  286. reinterpret_cast<char *>(&val), &len));
  287. EXPECT_NE(val, 0);
  288. detail::close_socket(sock);
  289. }
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. U8("descrip=Gastos áéíóúñÑ 6"));
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(DecodePathTest, UnicodeEncoding) {
  319. // %u0041 = 'A' (1-byte UTF-8)
  320. EXPECT_EQ("A", decode_path_component("%u0041"));
  321. // %u00E9 = 'é' (2-byte UTF-8)
  322. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  323. // %u3042 = 'あ' (3-byte UTF-8)
  324. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  325. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  326. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  327. // %uD800 = surrogate (invalid, silently dropped)
  328. EXPECT_EQ("", decode_path_component("%uD800"));
  329. }
  330. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  331. // A sign or whitespace inside the two-character escape window must not be
  332. // accepted as a valid percent-encoding; the sequence is passed through
  333. // literally, matching decode_uri_component / decode_path_component.
  334. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  335. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  336. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  337. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  338. // Well-formed escapes still decode.
  339. EXPECT_EQ("-", decode_query_component("%2D", false));
  340. EXPECT_EQ("A", decode_query_component("%41", false));
  341. }
  342. TEST(SanitizeFilenameTest, VariousPatterns) {
  343. // Path traversal
  344. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  345. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  346. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  347. // Normal and edge cases
  348. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  349. EXPECT_EQ("filename.txt",
  350. httplib::sanitize_filename("/path/to/filename.txt"));
  351. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  352. EXPECT_EQ("", httplib::sanitize_filename(".."));
  353. EXPECT_EQ("", httplib::sanitize_filename(""));
  354. // Null bytes stripped
  355. EXPECT_EQ("safe.txt",
  356. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  357. // Whitespace-only rejected
  358. EXPECT_EQ("", httplib::sanitize_filename(" "));
  359. }
  360. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  361. string unescapedCharacters = "-_.!~*'()";
  362. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  363. }
  364. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  365. string reservedCharacters = ";,/?:@&=+$";
  366. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  367. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  368. }
  369. TEST(ClientQueryOrder, PreserveOrder) {
  370. // This test reproduces Issue #2259: client may reorder query parameters
  371. // when sending a GET request. The expected behavior is that the client
  372. // preserves the original query string order when the caller supplied it
  373. // as part of the path.
  374. Server svr;
  375. svr.Get("/", [&](const Request &req, Response &res) {
  376. // Echo back the raw target so the test can assert ordering
  377. res.set_content(req.target, "text/plain");
  378. });
  379. std::thread t{[&] { svr.listen(HOST, PORT); }};
  380. auto se = detail::scope_exit([&] {
  381. svr.stop();
  382. t.join();
  383. ASSERT_FALSE(svr.is_running());
  384. });
  385. svr.wait_until_ready();
  386. Client cli(HOST, PORT);
  387. ASSERT_TRUE(cli.is_valid());
  388. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  389. auto res = cli.Get(original);
  390. ASSERT_TRUE(res);
  391. // Expect the echoed target to exactly match the original path (order
  392. // preserved)
  393. EXPECT_EQ(res->body, original);
  394. }
  395. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  396. string chineseCharacters = U8("中国語");
  397. string russianCharacters = U8("дом");
  398. string brazilianCharacters = U8("óculos");
  399. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  400. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  401. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  402. "%D0%B4%D0%BE%D0%BC");
  403. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  404. }
  405. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  406. string unescapedCharacters = "-_.!~*'()";
  407. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  408. }
  409. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  410. string reservedCharacters = ";,/?:@&=+$";
  411. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  412. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  413. }
  414. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  415. string chineseCharacters = U8("中国語");
  416. string russianCharacters = U8("дом");
  417. string brazilianCharacters = U8("óculos");
  418. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  419. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  420. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  421. "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  425. // Issue #2082 use case: encoding path component with ampersand
  426. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  427. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  428. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  429. }
  430. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  431. string unescapedCharacters = "-_.!~*'()";
  432. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  433. }
  434. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  435. string reservedCharacters = ";,/?:@&=+$#";
  436. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  437. }
  438. TEST(EncodeUriTest, TestUTF8Characters) {
  439. string chineseCharacters = U8("中国語");
  440. string russianCharacters = U8("дом");
  441. string brazilianCharacters = U8("óculos");
  442. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  443. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  444. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  445. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  446. }
  447. TEST(EncodeUriTest, TestCompleteUri) {
  448. string uri =
  449. "https://example.com/path/to/resource?query=value&param=test#fragment";
  450. EXPECT_EQ(
  451. httplib::encode_uri(uri),
  452. "https://example.com/path/to/resource?query=value&param=test#fragment");
  453. }
  454. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  455. string uri =
  456. "https://example.com/path with spaces/file name.html?q=hello world";
  457. EXPECT_EQ(httplib::encode_uri(uri),
  458. "https://example.com/path%20with%20spaces/"
  459. "file%20name.html?q=hello%20world");
  460. }
  461. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  462. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  463. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  464. }
  465. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  466. string unescapedCharacters = "-_.!~*'()";
  467. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  468. }
  469. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  470. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  471. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  472. string encodedBrazilian = "%C3%B3culos";
  473. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  474. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  475. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  476. }
  477. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  478. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  479. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  480. "Piri Tommy Villiers - on & on");
  481. }
  482. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  483. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  484. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  485. }
  486. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  487. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  488. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  489. }
  490. TEST(DecodeUriTest, TestUTF8Characters) {
  491. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  492. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  493. string encodedBrazilian = "%C3%B3culos";
  494. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  495. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  496. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  497. }
  498. TEST(DecodeUriTest, TestCompleteUri) {
  499. string encodedUri = "https://example.com/path%20with%20spaces/"
  500. "file%20name.html?q=hello%20world";
  501. EXPECT_EQ(
  502. httplib::decode_uri(encodedUri),
  503. "https://example.com/path with spaces/file name.html?q=hello world");
  504. }
  505. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  506. string original =
  507. "https://example.com/path with spaces/file name.html?q=hello world";
  508. string encoded = httplib::encode_uri(original);
  509. string decoded = httplib::decode_uri(encoded);
  510. EXPECT_EQ(decoded, original);
  511. }
  512. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  513. string original = "Piri Tommy Villiers - on & on";
  514. string encoded = httplib::encode_uri_component(original);
  515. string decoded = httplib::decode_uri_component(encoded);
  516. EXPECT_EQ(decoded, original);
  517. }
  518. TEST(TrimTests, TrimStringTests) {
  519. EXPECT_EQ("abc", detail::trim_copy("abc"));
  520. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  521. EXPECT_TRUE(detail::trim_copy("").empty());
  522. }
  523. TEST(FromCharsTest, Double) {
  524. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  525. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  526. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  527. auto parse = [](const std::string &s, double &v) {
  528. return detail::from_chars(s.data(), s.data() + s.size(), v);
  529. };
  530. double v = -1.0;
  531. // Representative quality values.
  532. EXPECT_EQ(parse("0", v).ec, std::errc{});
  533. EXPECT_DOUBLE_EQ(v, 0.0);
  534. EXPECT_EQ(parse("1", v).ec, std::errc{});
  535. EXPECT_DOUBLE_EQ(v, 1.0);
  536. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  537. EXPECT_DOUBLE_EQ(v, 0.8);
  538. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  539. EXPECT_DOUBLE_EQ(v, 0.001);
  540. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  541. EXPECT_DOUBLE_EQ(v, 1.0);
  542. // A missing integer or fractional part is tolerated.
  543. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  544. EXPECT_DOUBLE_EQ(v, 0.5);
  545. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  546. EXPECT_DOUBLE_EQ(v, 5.0);
  547. // Values outside [0, 1] still parse; the caller range-checks them.
  548. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  549. EXPECT_DOUBLE_EQ(v, 123.456);
  550. // Stops at the first byte that is not part of the number and reports where.
  551. std::string trailing = "0.9, text/html";
  552. auto r = parse(trailing, v);
  553. EXPECT_EQ(r.ec, std::errc{});
  554. EXPECT_DOUBLE_EQ(v, 0.9);
  555. EXPECT_EQ(*r.ptr, ',');
  556. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  557. // outright, and an 'e'/'E' simply ends the number.
  558. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  559. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  560. std::string exp_input = "1.5e3";
  561. r = parse(exp_input, v);
  562. EXPECT_EQ(r.ec, std::errc{});
  563. EXPECT_DOUBLE_EQ(v, 1.5);
  564. EXPECT_EQ(*r.ptr, 'e');
  565. // Invalid inputs.
  566. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  567. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  568. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  569. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  570. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  571. // Pathological but well-formed inputs must stay bounded (no overflow, no
  572. // out-of-bounds table access) and stay within [0, 1] for the caller.
  573. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  574. std::errc{});
  575. EXPECT_DOUBLE_EQ(v, 0.0);
  576. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  577. std::errc{});
  578. EXPECT_GE(v, 0.0);
  579. EXPECT_LE(v, 1.0);
  580. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  581. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  582. }
  583. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  584. // Simple case without quality values
  585. std::vector<std::string> result1;
  586. EXPECT_TRUE(detail::parse_accept_header(
  587. "text/html,application/json,text/plain", result1));
  588. EXPECT_EQ(result1.size(), 3U);
  589. EXPECT_EQ(result1[0], "text/html");
  590. EXPECT_EQ(result1[1], "application/json");
  591. EXPECT_EQ(result1[2], "text/plain");
  592. // With quality values
  593. std::vector<std::string> result2;
  594. EXPECT_TRUE(detail::parse_accept_header(
  595. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  596. EXPECT_EQ(result2.size(), 3U);
  597. EXPECT_EQ(result2[0], "application/json"); // highest q value
  598. EXPECT_EQ(result2[1], "text/html");
  599. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  600. }
  601. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  602. // Mixed with and without quality values
  603. std::vector<std::string> result;
  604. EXPECT_TRUE(detail::parse_accept_header(
  605. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  606. EXPECT_EQ(result.size(), 3U);
  607. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  608. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  609. EXPECT_EQ(result[2], "application/json"); // q=0.5
  610. }
  611. TEST(ParseAcceptHeaderTest, EdgeCases) {
  612. // Empty header
  613. std::vector<std::string> empty_result;
  614. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  615. EXPECT_TRUE(empty_result.empty());
  616. // Single type
  617. std::vector<std::string> single_result;
  618. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  619. EXPECT_EQ(single_result.size(), 1U);
  620. EXPECT_EQ(single_result[0], "application/json");
  621. // Wildcard types
  622. std::vector<std::string> wildcard_result;
  623. EXPECT_TRUE(detail::parse_accept_header(
  624. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  625. EXPECT_EQ(wildcard_result.size(), 3U);
  626. EXPECT_EQ(wildcard_result[0], "application/json");
  627. EXPECT_EQ(wildcard_result[1], "text/*");
  628. EXPECT_EQ(wildcard_result[2], "*/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  631. // Common browser Accept header
  632. std::vector<std::string> browser_result;
  633. EXPECT_TRUE(
  634. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  635. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  636. browser_result));
  637. EXPECT_EQ(browser_result.size(), 6U);
  638. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  639. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  640. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  641. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  642. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  643. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  644. // API client header
  645. std::vector<std::string> api_result;
  646. EXPECT_TRUE(detail::parse_accept_header(
  647. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  648. api_result));
  649. EXPECT_EQ(api_result.size(), 3U);
  650. EXPECT_EQ(api_result[0], "application/json");
  651. EXPECT_EQ(api_result[1], "application/xml");
  652. EXPECT_EQ(api_result[2], "text/plain");
  653. }
  654. TEST(ParseAcceptHeaderTest, SpecialCases) {
  655. // Quality value with 3 decimal places
  656. std::vector<std::string> decimal_result;
  657. EXPECT_TRUE(detail::parse_accept_header(
  658. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  659. EXPECT_EQ(decimal_result.size(), 2U);
  660. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  661. EXPECT_EQ(decimal_result[1], "text/html");
  662. // Zero quality (should still be included but with lowest priority)
  663. std::vector<std::string> zero_q_result;
  664. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  665. zero_q_result));
  666. EXPECT_EQ(zero_q_result.size(), 2U);
  667. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  668. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  669. // No spaces around commas
  670. std::vector<std::string> no_space_result;
  671. EXPECT_TRUE(detail::parse_accept_header(
  672. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  673. no_space_result));
  674. EXPECT_EQ(no_space_result.size(), 3U);
  675. EXPECT_EQ(no_space_result[0], "text/html");
  676. EXPECT_EQ(no_space_result[1], "application/json");
  677. EXPECT_EQ(no_space_result[2], "text/plain");
  678. }
  679. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  680. // Quality values always use '.' as the decimal separator, so parsing must
  681. // not depend on the process locale. An embedding application may have
  682. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  683. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  684. std::string saved = cur ? cur : "C";
  685. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  686. "fr_FR.UTF-8"};
  687. bool switched = false;
  688. for (const auto loc : comma_locales) {
  689. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  690. std::localeconv()->decimal_point[0] == ',') {
  691. switched = true;
  692. break;
  693. }
  694. }
  695. if (!switched) {
  696. std::setlocale(LC_NUMERIC, saved.c_str());
  697. GTEST_SKIP() << "no comma-decimal locale available on this host";
  698. }
  699. // The higher-weighted type appears later in the list, so a correct parse
  700. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  701. // sensitive parse reads both weights as 0 and leaves the original order.
  702. std::vector<std::string> result;
  703. EXPECT_TRUE(detail::parse_accept_header(
  704. "application/json;q=0.1,text/html;q=0.9", result));
  705. ASSERT_EQ(result.size(), 2U);
  706. EXPECT_EQ(result[0], "text/html");
  707. EXPECT_EQ(result[1], "application/json");
  708. std::setlocale(LC_NUMERIC, saved.c_str());
  709. }
  710. TEST(ParseAcceptHeaderTest, InvalidCases) {
  711. std::vector<std::string> result;
  712. // Invalid quality value (> 1.0)
  713. EXPECT_FALSE(
  714. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  715. // Invalid quality value (< 0.0)
  716. EXPECT_FALSE(
  717. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  718. // Invalid quality value (not a number)
  719. EXPECT_FALSE(detail::parse_accept_header(
  720. "text/html;q=invalid,application/json", result));
  721. // Empty quality value
  722. EXPECT_FALSE(
  723. detail::parse_accept_header("text/html;q=,application/json", result));
  724. // Invalid media type format (no slash and not wildcard)
  725. EXPECT_FALSE(
  726. detail::parse_accept_header("invalidtype,application/json", result));
  727. // Empty media type
  728. result.clear();
  729. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  730. // Only commas
  731. result.clear();
  732. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  733. // Valid cases should still work
  734. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  735. EXPECT_EQ(result.size(), 1U);
  736. EXPECT_EQ(result[0], "*/*");
  737. EXPECT_TRUE(detail::parse_accept_header("*", result));
  738. EXPECT_EQ(result.size(), 1U);
  739. EXPECT_EQ(result[0], "*");
  740. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  741. EXPECT_EQ(result.size(), 1U);
  742. EXPECT_EQ(result[0], "text/*");
  743. }
  744. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  745. Server svr;
  746. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  747. EXPECT_EQ(req.accept_content_types.size(), 3U);
  748. EXPECT_EQ(req.accept_content_types[0], "application/json");
  749. EXPECT_EQ(req.accept_content_types[1], "text/html");
  750. EXPECT_EQ(req.accept_content_types[2], "*/*");
  751. res.set_content("ok", "text/plain");
  752. });
  753. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  754. EXPECT_TRUE(false);
  755. res.set_content("bad request", "text/plain");
  756. });
  757. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  758. auto se = detail::scope_exit([&] {
  759. svr.stop();
  760. listen_thread.join();
  761. ASSERT_FALSE(svr.is_running());
  762. });
  763. svr.wait_until_ready();
  764. Client cli("localhost", PORT);
  765. {
  766. auto res =
  767. cli.Get("/accept_ok",
  768. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  769. ASSERT_TRUE(res);
  770. EXPECT_EQ(StatusCode::OK_200, res->status);
  771. }
  772. {
  773. auto res = cli.Get("/accept_bad_request",
  774. {{"Accept", "text/html;q=abc,application/json"}});
  775. ASSERT_TRUE(res);
  776. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  777. }
  778. }
  779. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  780. Server svr;
  781. svr.Get("/", [](const Request & /*req*/, Response &res) {
  782. res.set_content("ok", "text/plain");
  783. });
  784. std::atomic<int> start_count{0};
  785. std::atomic<bool> running_when_called{false};
  786. svr.set_start_handler([&]() {
  787. running_when_called = svr.is_running();
  788. start_count++;
  789. });
  790. auto port = svr.bind_to_any_port(HOST);
  791. std::thread t([&]() { svr.listen_after_bind(); });
  792. auto se = detail::scope_exit([&] {
  793. svr.stop();
  794. t.join();
  795. ASSERT_FALSE(svr.is_running());
  796. });
  797. svr.wait_until_ready();
  798. // A successful request proves the accept loop is running, which the start
  799. // handler precedes; so by now the handler must have run exactly once.
  800. Client cli(HOST, port);
  801. cli.set_connection_timeout(std::chrono::seconds(5));
  802. auto res = cli.Get("/");
  803. ASSERT_TRUE(res);
  804. EXPECT_EQ(StatusCode::OK_200, res->status);
  805. EXPECT_EQ(1, start_count.load());
  806. EXPECT_TRUE(running_when_called.load());
  807. }
  808. TEST(DivideTest, DivideStringTests) {
  809. auto divide = [](const std::string &str, char d) {
  810. std::string lhs;
  811. std::string rhs;
  812. detail::divide(str, d,
  813. [&](const char *lhs_data, std::size_t lhs_size,
  814. const char *rhs_data, std::size_t rhs_size) {
  815. lhs.assign(lhs_data, lhs_size);
  816. rhs.assign(rhs_data, rhs_size);
  817. });
  818. return std::make_pair(std::move(lhs), std::move(rhs));
  819. };
  820. {
  821. const auto res = divide("", '=');
  822. EXPECT_EQ(res.first, "");
  823. EXPECT_EQ(res.second, "");
  824. }
  825. {
  826. const auto res = divide("=", '=');
  827. EXPECT_EQ(res.first, "");
  828. EXPECT_EQ(res.second, "");
  829. }
  830. {
  831. const auto res = divide(" ", '=');
  832. EXPECT_EQ(res.first, " ");
  833. EXPECT_EQ(res.second, "");
  834. }
  835. {
  836. const auto res = divide("a", '=');
  837. EXPECT_EQ(res.first, "a");
  838. EXPECT_EQ(res.second, "");
  839. }
  840. {
  841. const auto res = divide("a=", '=');
  842. EXPECT_EQ(res.first, "a");
  843. EXPECT_EQ(res.second, "");
  844. }
  845. {
  846. const auto res = divide("=b", '=');
  847. EXPECT_EQ(res.first, "");
  848. EXPECT_EQ(res.second, "b");
  849. }
  850. {
  851. const auto res = divide("a=b", '=');
  852. EXPECT_EQ(res.first, "a");
  853. EXPECT_EQ(res.second, "b");
  854. }
  855. {
  856. const auto res = divide("a=b=", '=');
  857. EXPECT_EQ(res.first, "a");
  858. EXPECT_EQ(res.second, "b=");
  859. }
  860. {
  861. const auto res = divide("a=b=c", '=');
  862. EXPECT_EQ(res.first, "a");
  863. EXPECT_EQ(res.second, "b=c");
  864. }
  865. }
  866. TEST(SplitTest, ParseQueryString) {
  867. string s = "key1=val1&key2=val2&key3=val3";
  868. Params dic;
  869. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  870. [&](const char *b, const char *e) {
  871. string key, val;
  872. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  873. if (key.empty()) {
  874. key.assign(b2, e2);
  875. } else {
  876. val.assign(b2, e2);
  877. }
  878. });
  879. dic.emplace(key, val);
  880. });
  881. EXPECT_EQ("val1", dic.find("key1")->second);
  882. EXPECT_EQ("val2", dic.find("key2")->second);
  883. EXPECT_EQ("val3", dic.find("key3")->second);
  884. }
  885. TEST(SplitTest, ParseInvalidQueryTests) {
  886. {
  887. string s = " ";
  888. Params dict;
  889. detail::parse_query_text(s, dict);
  890. EXPECT_TRUE(dict.empty());
  891. }
  892. {
  893. string s = " = =";
  894. Params dict;
  895. detail::parse_query_text(s, dict);
  896. EXPECT_TRUE(dict.empty());
  897. }
  898. }
  899. TEST(ParseQueryTest, ParseQueryString) {
  900. {
  901. std::string s = "key1=val1&key2=val2&key3=val3";
  902. Params dic;
  903. detail::parse_query_text(s, dic);
  904. EXPECT_EQ("val1", dic.find("key1")->second);
  905. EXPECT_EQ("val2", dic.find("key2")->second);
  906. EXPECT_EQ("val3", dic.find("key3")->second);
  907. }
  908. {
  909. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  910. Params dic;
  911. detail::parse_query_text(s, dic);
  912. EXPECT_EQ("", dic.find("key1")->second);
  913. EXPECT_EQ("val1", dic.find("key2")->second);
  914. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  915. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  916. }
  917. }
  918. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  919. Params dic;
  920. EXPECT_EQ(detail::params_to_query_str(dic), "");
  921. dic.emplace("key1", "val1");
  922. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  923. dic.emplace("key2", "val2");
  924. dic.emplace("key3", "val3");
  925. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  926. }
  927. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  928. string content_type = "multipart/form-data; boundary=something";
  929. string boundary;
  930. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(boundary, "something");
  933. }
  934. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  935. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  936. string boundary;
  937. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  938. EXPECT_TRUE(ret);
  939. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  940. }
  941. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  942. string content_type =
  943. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  944. string boundary;
  945. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  946. EXPECT_TRUE(ret);
  947. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  948. }
  949. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  950. string content_type =
  951. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  952. string boundary;
  953. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  954. EXPECT_TRUE(ret);
  955. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  956. }
  957. TEST(GetHeaderValueTest, DefaultValue) {
  958. Headers headers = {{"Dummy", "Dummy"}};
  959. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  960. EXPECT_STREQ("text/plain", val);
  961. }
  962. TEST(GetHeaderValueTest, DefaultValueInt) {
  963. Headers headers = {{"Dummy", "Dummy"}};
  964. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  965. EXPECT_EQ(100ull, val);
  966. }
  967. TEST(GetHeaderValueTest, RegularValue) {
  968. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  969. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  970. EXPECT_STREQ("text/html", val);
  971. }
  972. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  973. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  974. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  975. EXPECT_STREQ("text/html", val);
  976. }
  977. TEST(GetHeaderValueTest, SetContent) {
  978. Response res;
  979. res.set_content("html", "text/html");
  980. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  981. res.set_content("text", "text/plain");
  982. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  983. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  984. }
  985. TEST(GetHeaderValueTest, RegularValueInt) {
  986. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  987. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  988. EXPECT_EQ(100ull, val);
  989. }
  990. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  991. Headers headers = {{"Content-Length", "x"}};
  992. auto is_invalid_value = false;
  993. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  994. is_invalid_value);
  995. EXPECT_EQ(0ull, val);
  996. EXPECT_TRUE(is_invalid_value);
  997. }
  998. TEST(GetHeaderValueTest, Range) {
  999. {
  1000. Headers headers = {make_range_header({{1, -1}})};
  1001. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1002. EXPECT_STREQ("bytes=1-", val);
  1003. }
  1004. {
  1005. Headers headers = {make_range_header({{-1, 1}})};
  1006. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1007. EXPECT_STREQ("bytes=-1", val);
  1008. }
  1009. {
  1010. Headers headers = {make_range_header({{1, 10}})};
  1011. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1012. EXPECT_STREQ("bytes=1-10", val);
  1013. }
  1014. {
  1015. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1016. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1017. EXPECT_STREQ("bytes=1-10, 100-", val);
  1018. }
  1019. {
  1020. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1021. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1022. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1023. }
  1024. {
  1025. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1026. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1027. EXPECT_STREQ("bytes=0-0, -1", val);
  1028. }
  1029. }
  1030. TEST(ParseHeaderValueTest, Range) {
  1031. {
  1032. Ranges ranges;
  1033. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1034. EXPECT_TRUE(ret);
  1035. EXPECT_EQ(1u, ranges.size());
  1036. EXPECT_EQ(1u, ranges[0].first);
  1037. EXPECT_EQ(-1, ranges[0].second);
  1038. }
  1039. {
  1040. Ranges ranges;
  1041. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1042. EXPECT_TRUE(ret);
  1043. EXPECT_EQ(1u, ranges.size());
  1044. EXPECT_EQ(-1, ranges[0].first);
  1045. EXPECT_EQ(1u, ranges[0].second);
  1046. }
  1047. {
  1048. Ranges ranges;
  1049. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1050. EXPECT_TRUE(ret);
  1051. EXPECT_EQ(1u, ranges.size());
  1052. EXPECT_EQ(1u, ranges[0].first);
  1053. EXPECT_EQ(10u, ranges[0].second);
  1054. }
  1055. {
  1056. Ranges ranges;
  1057. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1058. EXPECT_FALSE(ret);
  1059. }
  1060. {
  1061. Ranges ranges;
  1062. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1063. EXPECT_TRUE(ret);
  1064. EXPECT_EQ(2u, ranges.size());
  1065. EXPECT_EQ(1u, ranges[0].first);
  1066. EXPECT_EQ(10u, ranges[0].second);
  1067. EXPECT_EQ(100u, ranges[1].first);
  1068. EXPECT_EQ(-1, ranges[1].second);
  1069. }
  1070. {
  1071. Ranges ranges;
  1072. auto ret =
  1073. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1074. EXPECT_TRUE(ret);
  1075. EXPECT_EQ(3u, ranges.size());
  1076. EXPECT_EQ(1u, ranges[0].first);
  1077. EXPECT_EQ(10u, ranges[0].second);
  1078. EXPECT_EQ(100u, ranges[1].first);
  1079. EXPECT_EQ(200u, ranges[1].second);
  1080. EXPECT_EQ(300u, ranges[2].first);
  1081. EXPECT_EQ(400u, ranges[2].second);
  1082. }
  1083. {
  1084. Ranges ranges;
  1085. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1086. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1087. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1088. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1089. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1090. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1091. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1092. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1093. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1094. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1095. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1096. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1097. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1098. EXPECT_TRUE(ranges.empty());
  1099. }
  1100. }
  1101. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1102. Request req;
  1103. req.set_header("Accept-Encoding", "gzip");
  1104. Response res;
  1105. res.set_header("Content-Type", "text/plain");
  1106. auto ret = detail::encoding_type(req, res);
  1107. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1108. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1109. #else
  1110. EXPECT_TRUE(ret == detail::EncodingType::None);
  1111. #endif
  1112. }
  1113. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1114. Request req;
  1115. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1116. Response res;
  1117. res.set_header("Content-Type", "text/plain");
  1118. auto ret = detail::encoding_type(req, res);
  1119. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1120. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1121. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1122. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1123. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1124. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1125. #else
  1126. EXPECT_TRUE(ret == detail::EncodingType::None);
  1127. #endif
  1128. }
  1129. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1130. Request req;
  1131. req.set_header("Accept-Encoding",
  1132. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1133. Response res;
  1134. res.set_header("Content-Type", "text/plain");
  1135. auto ret = detail::encoding_type(req, res);
  1136. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1137. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1138. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1139. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1140. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1141. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1142. #else
  1143. EXPECT_TRUE(ret == detail::EncodingType::None);
  1144. #endif
  1145. }
  1146. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1147. // All supported encodings rejected with q=0 should return None
  1148. Request req;
  1149. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1150. Response res;
  1151. res.set_header("Content-Type", "text/plain");
  1152. auto ret = detail::encoding_type(req, res);
  1153. EXPECT_TRUE(ret == detail::EncodingType::None);
  1154. }
  1155. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1156. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1157. Request req;
  1158. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1159. Response res;
  1160. res.set_header("Content-Type", "text/plain");
  1161. auto ret = detail::encoding_type(req, res);
  1162. EXPECT_TRUE(ret == detail::EncodingType::None);
  1163. }
  1164. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1165. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1166. Request req;
  1167. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1168. Response res;
  1169. res.set_header("Content-Type", "text/plain");
  1170. auto ret = detail::encoding_type(req, res);
  1171. EXPECT_TRUE(ret == detail::EncodingType::None);
  1172. }
  1173. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1174. // RFC 7231: Accept-Encoding values are case-insensitive
  1175. Request req;
  1176. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1177. Response res;
  1178. res.set_header("Content-Type", "text/plain");
  1179. auto ret = detail::encoding_type(req, res);
  1180. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1181. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1182. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1183. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1184. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1185. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1186. #else
  1187. EXPECT_TRUE(ret == detail::EncodingType::None);
  1188. #endif
  1189. }
  1190. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1191. // q value should determine priority, not hardcoded order
  1192. Request req;
  1193. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1194. Response res;
  1195. res.set_header("Content-Type", "text/plain");
  1196. auto ret = detail::encoding_type(req, res);
  1197. // gzip has highest q=1.0, so it should be selected even though
  1198. // br and zstd are also supported
  1199. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1200. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1201. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1202. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1203. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1204. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1205. #else
  1206. EXPECT_TRUE(ret == detail::EncodingType::None);
  1207. #endif
  1208. }
  1209. TEST(BufferStreamTest, read) {
  1210. detail::BufferStream strm1;
  1211. Stream &strm = strm1;
  1212. EXPECT_EQ(5, strm.write("hello"));
  1213. char buf[512];
  1214. EXPECT_EQ(2, strm.read(buf, 2));
  1215. EXPECT_EQ('h', buf[0]);
  1216. EXPECT_EQ('e', buf[1]);
  1217. EXPECT_EQ(2, strm.read(buf, 2));
  1218. EXPECT_EQ('l', buf[0]);
  1219. EXPECT_EQ('l', buf[1]);
  1220. EXPECT_EQ(1, strm.read(buf, 1));
  1221. EXPECT_EQ('o', buf[0]);
  1222. EXPECT_EQ(0, strm.read(buf, 1));
  1223. }
  1224. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1225. auto host = "www.httpwatch.com";
  1226. auto ip = hosted_at(host);
  1227. EXPECT_EQ("23.96.13.243", ip);
  1228. std::vector<std::string> addrs;
  1229. hosted_at(host, addrs);
  1230. EXPECT_EQ(1u, addrs.size());
  1231. }
  1232. #if 0 // It depends on each test environment...
  1233. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1234. auto host = "www.youtube.com";
  1235. std::vector<std::string> addrs;
  1236. hosted_at(host, addrs);
  1237. EXPECT_EQ(20u, addrs.size());
  1238. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1239. EXPECT_TRUE(it != addrs.end());
  1240. }
  1241. #endif
  1242. class ChunkedEncodingTest : public ::testing::Test {
  1243. protected:
  1244. ChunkedEncodingTest()
  1245. : cli_(HOST, PORT)
  1246. #ifdef CPPHTTPLIB_SSL_ENABLED
  1247. ,
  1248. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1249. #endif
  1250. {
  1251. cli_.set_connection_timeout(2);
  1252. #ifdef CPPHTTPLIB_SSL_ENABLED
  1253. cli_.enable_server_certificate_verification(false);
  1254. #endif
  1255. }
  1256. virtual void SetUp() {
  1257. read_file("./image.jpg", image_data_);
  1258. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1259. res.set_content("Hello World!", "text/plain");
  1260. });
  1261. svr_.Get(
  1262. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1263. res.set_chunked_content_provider(
  1264. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1265. size_t remaining = image_data_.size() - offset;
  1266. if (remaining == 0) {
  1267. sink.done();
  1268. } else {
  1269. constexpr size_t CHUNK_SIZE = 1024;
  1270. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1271. sink.write(&image_data_[offset], send_size);
  1272. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1273. }
  1274. return true;
  1275. });
  1276. });
  1277. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1278. svr_.wait_until_ready();
  1279. }
  1280. virtual void TearDown() {
  1281. svr_.stop();
  1282. if (!request_threads_.empty()) {
  1283. std::this_thread::sleep_for(std::chrono::seconds(1));
  1284. for (auto &t : request_threads_) {
  1285. t.join();
  1286. }
  1287. }
  1288. t_.join();
  1289. }
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. SSLClient cli_;
  1292. SSLServer svr_;
  1293. #else
  1294. Client cli_;
  1295. Server svr_;
  1296. #endif
  1297. thread t_;
  1298. std::vector<thread> request_threads_;
  1299. std::string image_data_;
  1300. };
  1301. TEST_F(ChunkedEncodingTest, NormalGet) {
  1302. auto res = cli_.Get("/chunked");
  1303. ASSERT_TRUE(res);
  1304. std::string out;
  1305. read_file("./image.jpg", out);
  1306. EXPECT_EQ(StatusCode::OK_200, res->status);
  1307. EXPECT_EQ(out, res->body);
  1308. }
  1309. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1310. std::string body;
  1311. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1312. body.append(data, data_length);
  1313. return true;
  1314. });
  1315. ASSERT_TRUE(res);
  1316. std::string out;
  1317. read_file("./image.jpg", out);
  1318. EXPECT_EQ(StatusCode::OK_200, res->status);
  1319. EXPECT_EQ(out, body);
  1320. }
  1321. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1322. std::string body;
  1323. auto res = cli_.Get(
  1324. "/chunked",
  1325. [&](const Response &response) {
  1326. EXPECT_EQ(StatusCode::OK_200, response.status);
  1327. return true;
  1328. },
  1329. [&](const char *data, size_t data_length) {
  1330. body.append(data, data_length);
  1331. return true;
  1332. });
  1333. ASSERT_TRUE(res);
  1334. std::string out;
  1335. read_file("./image.jpg", out);
  1336. EXPECT_EQ(StatusCode::OK_200, res->status);
  1337. EXPECT_EQ(out, body);
  1338. }
  1339. TEST(RangeTest, FromHTTPBin_Online) {
  1340. auto host = "httpbingo.org";
  1341. auto path = std::string{"/range/32"};
  1342. #ifdef CPPHTTPLIB_SSL_ENABLED
  1343. auto port = 443;
  1344. SSLClient cli(host, port);
  1345. #else
  1346. auto port = 80;
  1347. Client cli(host, port);
  1348. #endif
  1349. cli.set_connection_timeout(5);
  1350. {
  1351. auto res = cli.Get(path);
  1352. ASSERT_TRUE(res);
  1353. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1354. EXPECT_EQ(StatusCode::OK_200, res->status);
  1355. }
  1356. {
  1357. Headers headers = {make_range_header({{1, -1}})};
  1358. auto res = cli.Get(path, headers);
  1359. ASSERT_TRUE(res);
  1360. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1361. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1362. }
  1363. {
  1364. Headers headers = {make_range_header({{1, 10}})};
  1365. auto res = cli.Get(path, headers);
  1366. ASSERT_TRUE(res);
  1367. EXPECT_EQ("bcdefghijk", res->body);
  1368. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1369. }
  1370. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1371. // entire resource, while the original httpbin returned 200. Both are
  1372. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1373. {
  1374. Headers headers = {make_range_header({{0, 31}})};
  1375. auto res = cli.Get(path, headers);
  1376. ASSERT_TRUE(res);
  1377. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1378. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1379. res->status == StatusCode::PartialContent_206);
  1380. }
  1381. {
  1382. Headers headers = {make_range_header({{0, -1}})};
  1383. auto res = cli.Get(path, headers);
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1386. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1387. res->status == StatusCode::PartialContent_206);
  1388. }
  1389. // go-httpbin returns 206 with clamped range for over-range requests,
  1390. // while the original httpbin returned 416. Both behaviors are observed
  1391. // in real servers, so we only verify the request succeeds.
  1392. {
  1393. Headers headers = {make_range_header({{0, 32}})};
  1394. auto res = cli.Get(path, headers);
  1395. ASSERT_TRUE(res);
  1396. }
  1397. }
  1398. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1399. auto host = "unresolvableaddress.local";
  1400. auto path = std::string{"/"};
  1401. #ifdef CPPHTTPLIB_SSL_ENABLED
  1402. auto port = 443;
  1403. SSLClient cli(host, port);
  1404. #else
  1405. auto port = 80;
  1406. Client cli(host, port);
  1407. #endif
  1408. cli.set_connection_timeout(1);
  1409. {
  1410. auto res = cli.Get(path);
  1411. ASSERT_FALSE(res);
  1412. }
  1413. std::this_thread::sleep_for(std::chrono::seconds(8));
  1414. }
  1415. #if defined(__linux__) && defined(__GLIBC__) && \
  1416. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1417. // Forward declaration: in split builds split.py strips `inline` and moves the
  1418. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1419. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1420. // against the symbol in both header-only and split builds.
  1421. namespace httplib {
  1422. namespace detail {
  1423. int getaddrinfo_with_timeout(const char *node, const char *service,
  1424. const struct addrinfo *hints,
  1425. struct addrinfo **res, time_t timeout_sec);
  1426. } // namespace detail
  1427. } // namespace httplib
  1428. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1429. //
  1430. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1431. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1432. // gai_suspend() call hits the connection timeout the function calls
  1433. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1434. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1435. // still alive and still references the now-destroyed stack frame.
  1436. //
  1437. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1438. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1439. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1440. // and runs them in a container.
  1441. namespace {
  1442. bool should_run_issue_2431_tests() {
  1443. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1444. return v && *v && std::string(v) != "0";
  1445. }
  1446. std::string unique_unresolvable_host(int n) {
  1447. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1448. // glibc still asks the configured nameserver — which is exactly the path
  1449. // we want to exercise. A unique label per call avoids the resolver cache.
  1450. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1451. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1452. std::to_string(n) + ".invalid";
  1453. }
  1454. } // namespace
  1455. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1456. if (!should_run_issue_2431_tests()) {
  1457. GTEST_SKIP()
  1458. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1459. }
  1460. for (int i = 0; i < 8; ++i) {
  1461. struct addrinfo hints;
  1462. memset(&hints, 0, sizeof(hints));
  1463. hints.ai_family = AF_UNSPEC;
  1464. hints.ai_socktype = SOCK_STREAM;
  1465. auto host = unique_unresolvable_host(i);
  1466. struct addrinfo *result = nullptr;
  1467. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1468. &result, /*timeout_sec=*/1);
  1469. if (rc == 0 && result) { freeaddrinfo(result); }
  1470. }
  1471. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1472. // stack region they still believe holds their gaicb.
  1473. std::this_thread::sleep_for(std::chrono::seconds(3));
  1474. }
  1475. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1476. if (!should_run_issue_2431_tests()) {
  1477. GTEST_SKIP()
  1478. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1479. }
  1480. std::atomic<bool> stop{false};
  1481. std::vector<std::thread> threads;
  1482. for (int t = 0; t < 8; ++t) {
  1483. threads.emplace_back([t, &stop] {
  1484. int i = 0;
  1485. while (!stop.load(std::memory_order_relaxed)) {
  1486. struct addrinfo hints;
  1487. memset(&hints, 0, sizeof(hints));
  1488. hints.ai_family = AF_UNSPEC;
  1489. hints.ai_socktype = SOCK_STREAM;
  1490. auto host = unique_unresolvable_host(t * 100000 + i++);
  1491. struct addrinfo *result = nullptr;
  1492. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1493. &result, /*timeout_sec=*/1);
  1494. if (rc == 0 && result) { freeaddrinfo(result); }
  1495. }
  1496. });
  1497. }
  1498. std::this_thread::sleep_for(std::chrono::seconds(8));
  1499. stop.store(true, std::memory_order_relaxed);
  1500. for (auto &th : threads) {
  1501. th.join();
  1502. }
  1503. std::this_thread::sleep_for(std::chrono::seconds(3));
  1504. }
  1505. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1506. if (!should_run_issue_2431_tests()) {
  1507. GTEST_SKIP()
  1508. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1509. }
  1510. std::atomic<bool> stop{false};
  1511. std::vector<std::thread> threads;
  1512. for (int t = 0; t < 8; ++t) {
  1513. threads.emplace_back([t, &stop] {
  1514. int i = 0;
  1515. while (!stop.load(std::memory_order_relaxed)) {
  1516. auto host = unique_unresolvable_host(t * 100000 + i++);
  1517. Client cli(host, 80);
  1518. cli.set_connection_timeout(1, 0);
  1519. cli.set_read_timeout(1, 0);
  1520. cli.set_write_timeout(1, 0);
  1521. (void)cli.Get("/");
  1522. }
  1523. });
  1524. }
  1525. std::this_thread::sleep_for(std::chrono::seconds(8));
  1526. stop.store(true, std::memory_order_relaxed);
  1527. for (auto &th : threads) {
  1528. th.join();
  1529. }
  1530. std::this_thread::sleep_for(std::chrono::seconds(3));
  1531. }
  1532. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1533. TEST(ConnectionErrorTest, InvalidHost) {
  1534. auto host = "-abcde.com";
  1535. #ifdef CPPHTTPLIB_SSL_ENABLED
  1536. auto port = 443;
  1537. SSLClient cli(host, port);
  1538. #else
  1539. auto port = 80;
  1540. Client cli(host, port);
  1541. #endif
  1542. cli.set_connection_timeout(std::chrono::seconds(2));
  1543. auto res = cli.Get("/");
  1544. ASSERT_TRUE(!res);
  1545. EXPECT_EQ(Error::Connection, res.error());
  1546. }
  1547. TEST(ConnectionErrorTest, InvalidHost2) {
  1548. auto host = "httpcan.org/";
  1549. #ifdef CPPHTTPLIB_SSL_ENABLED
  1550. SSLClient cli(host);
  1551. #else
  1552. Client cli(host);
  1553. #endif
  1554. cli.set_connection_timeout(std::chrono::seconds(2));
  1555. auto res = cli.Get("/");
  1556. ASSERT_TRUE(!res);
  1557. EXPECT_EQ(Error::Connection, res.error());
  1558. }
  1559. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1560. auto host = "httpcan.org/";
  1561. #ifdef CPPHTTPLIB_SSL_ENABLED
  1562. SSLClient cli(host);
  1563. #else
  1564. Client cli(host);
  1565. #endif
  1566. cli.set_connection_timeout(std::chrono::seconds(2));
  1567. auto res = cli.Get("/");
  1568. ASSERT_TRUE(!res);
  1569. stringstream s;
  1570. s << "error code: " << res.error();
  1571. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1572. }
  1573. TEST(ConnectionErrorTest, InvalidPort) {
  1574. auto host = "localhost";
  1575. auto port = 44380;
  1576. #ifdef CPPHTTPLIB_SSL_ENABLED
  1577. SSLClient cli(host, port);
  1578. #else
  1579. Client cli(host, port);
  1580. #endif
  1581. cli.set_connection_timeout(std::chrono::seconds(2));
  1582. auto res = cli.Get("/");
  1583. ASSERT_TRUE(!res);
  1584. EXPECT_TRUE(Error::Connection == res.error() ||
  1585. Error::ConnectionTimeout == res.error());
  1586. }
  1587. TEST(ConnectionErrorTest, Timeout_Online) {
  1588. auto host = "google.com";
  1589. #ifdef CPPHTTPLIB_SSL_ENABLED
  1590. auto port = 44380;
  1591. SSLClient cli(host, port);
  1592. #else
  1593. auto port = 8080;
  1594. Client cli(host, port);
  1595. #endif
  1596. cli.set_connection_timeout(std::chrono::seconds(2));
  1597. // only probe one address type so that the error reason
  1598. // correlates to the timed-out IPv4, not the unsupported
  1599. // IPv6 connection attempt
  1600. cli.set_address_family(AF_INET);
  1601. auto res = cli.Get("/");
  1602. ASSERT_TRUE(!res);
  1603. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1604. }
  1605. TEST(CancelTest, NoCancel_Online) {
  1606. auto host = "httpbingo.org";
  1607. auto path = std::string{"/range/32"};
  1608. #ifdef CPPHTTPLIB_SSL_ENABLED
  1609. auto port = 443;
  1610. SSLClient cli(host, port);
  1611. #else
  1612. auto port = 80;
  1613. Client cli(host, port);
  1614. #endif
  1615. cli.set_connection_timeout(std::chrono::seconds(5));
  1616. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1617. ASSERT_TRUE(res);
  1618. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1619. EXPECT_EQ(StatusCode::OK_200, res->status);
  1620. }
  1621. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1622. // Use /bytes with a large payload so that the DownloadProgress callback
  1623. // (which only fires for Content-Length responses) is invoked before the
  1624. // entire body is received, giving cancellation a chance to fire.
  1625. auto host = "httpbingo.org";
  1626. auto path = std::string{"/bytes/524288"};
  1627. #ifdef CPPHTTPLIB_SSL_ENABLED
  1628. auto port = 443;
  1629. SSLClient cli(host, port);
  1630. #else
  1631. auto port = 80;
  1632. Client cli(host, port);
  1633. #endif
  1634. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1635. cli.set_connection_timeout(std::chrono::seconds(5));
  1636. ASSERT_TRUE(!res);
  1637. EXPECT_EQ(Error::Canceled, res.error());
  1638. }
  1639. TEST(CancelTest, WithCancelLargePayload_Online) {
  1640. auto host = "httpbingo.org";
  1641. auto path = std::string{"/bytes/524288"};
  1642. #ifdef CPPHTTPLIB_SSL_ENABLED
  1643. auto port = 443;
  1644. SSLClient cli(host, port);
  1645. #else
  1646. auto port = 80;
  1647. Client cli(host, port);
  1648. #endif
  1649. cli.set_connection_timeout(std::chrono::seconds(5));
  1650. uint32_t count = 0;
  1651. auto res =
  1652. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1653. ASSERT_TRUE(!res);
  1654. EXPECT_EQ(Error::Canceled, res.error());
  1655. }
  1656. TEST(CancelTest, NoCancelPost) {
  1657. Server svr;
  1658. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1659. res.set_content("Hello World!", "text/plain");
  1660. });
  1661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1662. auto se = detail::scope_exit([&] {
  1663. svr.stop();
  1664. thread.join();
  1665. ASSERT_FALSE(svr.is_running());
  1666. });
  1667. svr.wait_until_ready();
  1668. Client cli(HOST, PORT);
  1669. cli.set_connection_timeout(std::chrono::seconds(5));
  1670. auto res =
  1671. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1672. "application/json", [](uint64_t, uint64_t) { return true; });
  1673. ASSERT_TRUE(res);
  1674. EXPECT_EQ("Hello World!", res->body);
  1675. EXPECT_EQ(StatusCode::OK_200, res->status);
  1676. }
  1677. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1678. Server svr;
  1679. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1680. res.set_content("Hello World!", "text/plain");
  1681. });
  1682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1683. auto se = detail::scope_exit([&] {
  1684. svr.stop();
  1685. thread.join();
  1686. ASSERT_FALSE(svr.is_running());
  1687. });
  1688. svr.wait_until_ready();
  1689. Client cli(HOST, PORT);
  1690. cli.set_connection_timeout(std::chrono::seconds(5));
  1691. auto res =
  1692. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1693. "application/json", [](uint64_t, uint64_t) { return false; });
  1694. ASSERT_TRUE(!res);
  1695. EXPECT_EQ(Error::Canceled, res.error());
  1696. }
  1697. TEST(CancelTest, WithCancelLargePayloadPost) {
  1698. Server svr;
  1699. svr.set_payload_max_length(200 * 1024 * 1024);
  1700. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1701. res.set_content(LARGE_DATA, "text/plain");
  1702. });
  1703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1704. auto se = detail::scope_exit([&] {
  1705. svr.stop();
  1706. thread.join();
  1707. ASSERT_FALSE(svr.is_running());
  1708. });
  1709. svr.wait_until_ready();
  1710. Client cli(HOST, PORT);
  1711. cli.set_payload_max_length(200 * 1024 * 1024);
  1712. cli.set_connection_timeout(std::chrono::seconds(5));
  1713. auto res =
  1714. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1715. "application/json", [](uint64_t, uint64_t) { return false; });
  1716. ASSERT_TRUE(!res);
  1717. EXPECT_EQ(Error::Canceled, res.error());
  1718. }
  1719. TEST(CancelTest, NoCancelPut) {
  1720. Server svr;
  1721. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1722. res.set_content("Hello World!", "text/plain");
  1723. });
  1724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1725. auto se = detail::scope_exit([&] {
  1726. svr.stop();
  1727. thread.join();
  1728. ASSERT_FALSE(svr.is_running());
  1729. });
  1730. svr.wait_until_ready();
  1731. Client cli(HOST, PORT);
  1732. cli.set_connection_timeout(std::chrono::seconds(5));
  1733. auto res =
  1734. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1735. "application/json", [](uint64_t, uint64_t) { return true; });
  1736. ASSERT_TRUE(res);
  1737. EXPECT_EQ("Hello World!", res->body);
  1738. EXPECT_EQ(StatusCode::OK_200, res->status);
  1739. }
  1740. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1741. Server svr;
  1742. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1743. res.set_content("Hello World!", "text/plain");
  1744. });
  1745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1746. auto se = detail::scope_exit([&] {
  1747. svr.stop();
  1748. thread.join();
  1749. ASSERT_FALSE(svr.is_running());
  1750. });
  1751. svr.wait_until_ready();
  1752. Client cli(HOST, PORT);
  1753. cli.set_connection_timeout(std::chrono::seconds(5));
  1754. auto res =
  1755. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1756. "application/json", [](uint64_t, uint64_t) { return false; });
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::Canceled, res.error());
  1759. }
  1760. TEST(CancelTest, WithCancelLargePayloadPut) {
  1761. Server svr;
  1762. svr.set_payload_max_length(200 * 1024 * 1024);
  1763. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1764. res.set_content(LARGE_DATA, "text/plain");
  1765. });
  1766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1767. auto se = detail::scope_exit([&] {
  1768. svr.stop();
  1769. thread.join();
  1770. ASSERT_FALSE(svr.is_running());
  1771. });
  1772. svr.wait_until_ready();
  1773. Client cli(HOST, PORT);
  1774. cli.set_payload_max_length(200 * 1024 * 1024);
  1775. cli.set_connection_timeout(std::chrono::seconds(5));
  1776. auto res =
  1777. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1778. "application/json", [](uint64_t, uint64_t) { return false; });
  1779. ASSERT_TRUE(!res);
  1780. EXPECT_EQ(Error::Canceled, res.error());
  1781. }
  1782. TEST(CancelTest, NoCancelPatch) {
  1783. Server svr;
  1784. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1785. res.set_content("Hello World!", "text/plain");
  1786. });
  1787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1788. auto se = detail::scope_exit([&] {
  1789. svr.stop();
  1790. thread.join();
  1791. ASSERT_FALSE(svr.is_running());
  1792. });
  1793. svr.wait_until_ready();
  1794. Client cli(HOST, PORT);
  1795. cli.set_connection_timeout(std::chrono::seconds(5));
  1796. auto res =
  1797. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1798. "application/json", [](uint64_t, uint64_t) { return true; });
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ("Hello World!", res->body);
  1801. EXPECT_EQ(StatusCode::OK_200, res->status);
  1802. }
  1803. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1804. Server svr;
  1805. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1806. res.set_content("Hello World!", "text/plain");
  1807. });
  1808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1809. auto se = detail::scope_exit([&] {
  1810. svr.stop();
  1811. thread.join();
  1812. ASSERT_FALSE(svr.is_running());
  1813. });
  1814. svr.wait_until_ready();
  1815. Client cli(HOST, PORT);
  1816. cli.set_connection_timeout(std::chrono::seconds(5));
  1817. auto res =
  1818. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1819. "application/json", [](uint64_t, uint64_t) { return false; });
  1820. ASSERT_TRUE(!res);
  1821. EXPECT_EQ(Error::Canceled, res.error());
  1822. }
  1823. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1824. Server svr;
  1825. svr.set_payload_max_length(200 * 1024 * 1024);
  1826. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1827. res.set_content(LARGE_DATA, "text/plain");
  1828. });
  1829. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1830. auto se = detail::scope_exit([&] {
  1831. svr.stop();
  1832. thread.join();
  1833. ASSERT_FALSE(svr.is_running());
  1834. });
  1835. svr.wait_until_ready();
  1836. Client cli(HOST, PORT);
  1837. cli.set_payload_max_length(200 * 1024 * 1024);
  1838. cli.set_connection_timeout(std::chrono::seconds(5));
  1839. auto res =
  1840. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1841. "application/json", [](uint64_t, uint64_t) { return false; });
  1842. ASSERT_TRUE(!res);
  1843. EXPECT_EQ(Error::Canceled, res.error());
  1844. }
  1845. TEST(CancelTest, NoCancelDelete) {
  1846. Server svr;
  1847. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1848. res.set_content("Hello World!", "text/plain");
  1849. });
  1850. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1851. auto se = detail::scope_exit([&] {
  1852. svr.stop();
  1853. thread.join();
  1854. ASSERT_FALSE(svr.is_running());
  1855. });
  1856. svr.wait_until_ready();
  1857. Client cli(HOST, PORT);
  1858. cli.set_connection_timeout(std::chrono::seconds(5));
  1859. auto res =
  1860. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1861. "application/json", [](uint64_t, uint64_t) { return true; });
  1862. ASSERT_TRUE(res);
  1863. EXPECT_EQ("Hello World!", res->body);
  1864. EXPECT_EQ(StatusCode::OK_200, res->status);
  1865. }
  1866. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1867. Server svr;
  1868. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1869. res.set_content("Hello World!", "text/plain");
  1870. });
  1871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1872. auto se = detail::scope_exit([&] {
  1873. svr.stop();
  1874. thread.join();
  1875. ASSERT_FALSE(svr.is_running());
  1876. });
  1877. svr.wait_until_ready();
  1878. Client cli(HOST, PORT);
  1879. cli.set_connection_timeout(std::chrono::seconds(5));
  1880. auto res =
  1881. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1882. "application/json", [](uint64_t, uint64_t) { return false; });
  1883. ASSERT_TRUE(!res);
  1884. EXPECT_EQ(Error::Canceled, res.error());
  1885. }
  1886. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1887. Server svr;
  1888. svr.set_payload_max_length(200 * 1024 * 1024);
  1889. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1890. res.set_content(LARGE_DATA, "text/plain");
  1891. });
  1892. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1893. auto se = detail::scope_exit([&] {
  1894. svr.stop();
  1895. thread.join();
  1896. ASSERT_FALSE(svr.is_running());
  1897. });
  1898. svr.wait_until_ready();
  1899. Client cli(HOST, PORT);
  1900. cli.set_payload_max_length(200 * 1024 * 1024);
  1901. cli.set_connection_timeout(std::chrono::seconds(5));
  1902. auto res =
  1903. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1904. "application/json", [](uint64_t, uint64_t) { return false; });
  1905. ASSERT_TRUE(!res);
  1906. EXPECT_EQ(Error::Canceled, res.error());
  1907. }
  1908. static std::string remove_whitespace(const std::string &input) {
  1909. std::string output;
  1910. output.reserve(input.size());
  1911. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1912. [](unsigned char c) { return !std::isspace(c); });
  1913. return output;
  1914. }
  1915. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1916. auto host = "httpbingo.org";
  1917. auto path = std::string{"/basic-auth/hello/world"};
  1918. #ifdef CPPHTTPLIB_SSL_ENABLED
  1919. auto port = 443;
  1920. SSLClient cli(host, port);
  1921. #else
  1922. auto port = 80;
  1923. Client cli(host, port);
  1924. #endif
  1925. {
  1926. auto res = cli.Get(path);
  1927. ASSERT_TRUE(res);
  1928. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1929. }
  1930. {
  1931. auto res =
  1932. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1933. ASSERT_TRUE(res);
  1934. auto body = remove_whitespace(res->body);
  1935. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1936. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1937. EXPECT_EQ(StatusCode::OK_200, res->status);
  1938. }
  1939. {
  1940. cli.set_basic_auth("hello", "world");
  1941. auto res = cli.Get(path);
  1942. ASSERT_TRUE(res);
  1943. auto body = remove_whitespace(res->body);
  1944. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1945. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1946. EXPECT_EQ(StatusCode::OK_200, res->status);
  1947. }
  1948. {
  1949. cli.set_basic_auth("hello", "bad");
  1950. auto res = cli.Get(path);
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1953. }
  1954. {
  1955. cli.set_basic_auth("bad", "world");
  1956. auto res = cli.Get(path);
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1959. }
  1960. }
  1961. #ifdef CPPHTTPLIB_SSL_ENABLED
  1962. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1963. auto host = "httpbingo.org";
  1964. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1965. auto paths = std::vector<std::string>{
  1966. "/digest-auth/auth/hello/world/MD5",
  1967. "/digest-auth/auth/hello/world/SHA-256",
  1968. };
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. {
  1972. auto res = cli.Get(unauth_path);
  1973. ASSERT_TRUE(res);
  1974. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1975. }
  1976. {
  1977. cli.set_digest_auth("hello", "world");
  1978. for (const auto &path : paths) {
  1979. auto res = cli.Get(path.c_str());
  1980. ASSERT_TRUE(res);
  1981. auto body = remove_whitespace(res->body);
  1982. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1983. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. }
  1986. cli.set_digest_auth("hello", "bad");
  1987. for (const auto &path : paths) {
  1988. auto res = cli.Get(path.c_str());
  1989. ASSERT_TRUE(res);
  1990. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1991. }
  1992. }
  1993. }
  1994. #endif
  1995. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1996. auto host = "google.com";
  1997. auto another_host = "example.com";
  1998. auto wrong_ip = "0.0.0.0";
  1999. #ifdef CPPHTTPLIB_SSL_ENABLED
  2000. SSLClient cli(host);
  2001. #else
  2002. Client cli(host);
  2003. #endif
  2004. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2005. auto res = cli.Get("/");
  2006. ASSERT_TRUE(res);
  2007. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2008. }
  2009. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2010. auto host = "google.com";
  2011. auto wrong_ip = "0.0.0.0";
  2012. #ifdef CPPHTTPLIB_SSL_ENABLED
  2013. SSLClient cli(host);
  2014. #else
  2015. Client cli(host);
  2016. #endif
  2017. cli.set_hostname_addr_map({{host, wrong_ip}});
  2018. auto res = cli.Get("/");
  2019. ASSERT_TRUE(!res);
  2020. EXPECT_EQ(Error::Connection, res.error());
  2021. }
  2022. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2023. auto host = "httpbingo.org";
  2024. auto path = std::string{"/absolute-redirect/3"};
  2025. #ifdef CPPHTTPLIB_SSL_ENABLED
  2026. SSLClient cli(host);
  2027. #else
  2028. Client cli(host);
  2029. #endif
  2030. cli.set_follow_location(true);
  2031. auto res = cli.Get(path);
  2032. ASSERT_TRUE(res);
  2033. EXPECT_EQ(StatusCode::OK_200, res->status);
  2034. }
  2035. TEST(RedirectTest, Redirect_Online) {
  2036. auto host = "httpbingo.org";
  2037. auto path = std::string{"/redirect/3"};
  2038. #ifdef CPPHTTPLIB_SSL_ENABLED
  2039. SSLClient cli(host);
  2040. #else
  2041. Client cli(host);
  2042. #endif
  2043. cli.set_follow_location(true);
  2044. auto res = cli.Get(path);
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(StatusCode::OK_200, res->status);
  2047. }
  2048. TEST(RelativeRedirectTest, Redirect_Online) {
  2049. auto host = "httpbingo.org";
  2050. auto path = std::string{"/relative-redirect/3"};
  2051. #ifdef CPPHTTPLIB_SSL_ENABLED
  2052. SSLClient cli(host);
  2053. #else
  2054. Client cli(host);
  2055. #endif
  2056. cli.set_follow_location(true);
  2057. auto res = cli.Get(path);
  2058. ASSERT_TRUE(res);
  2059. EXPECT_EQ(StatusCode::OK_200, res->status);
  2060. }
  2061. TEST(TooManyRedirectTest, Redirect_Online) {
  2062. auto host = "httpbingo.org";
  2063. auto path = std::string{"/redirect/21"};
  2064. #ifdef CPPHTTPLIB_SSL_ENABLED
  2065. SSLClient cli(host);
  2066. #else
  2067. Client cli(host);
  2068. #endif
  2069. cli.set_follow_location(true);
  2070. auto res = cli.Get(path);
  2071. ASSERT_TRUE(!res);
  2072. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2073. }
  2074. #ifdef CPPHTTPLIB_SSL_ENABLED
  2075. TEST(YahooRedirectTest, Redirect_Online) {
  2076. Client cli("yahoo.com");
  2077. auto res = cli.Get("/");
  2078. ASSERT_TRUE(res);
  2079. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2080. cli.set_follow_location(true);
  2081. res = cli.Get("/");
  2082. ASSERT_TRUE(res);
  2083. EXPECT_EQ(StatusCode::OK_200, res->status);
  2084. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2085. }
  2086. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2087. #define REDIR_HOST "httpbingo.org"
  2088. #define REDIR_PATH "/redirect-to"
  2089. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2090. SSLClient cli(REDIR_HOST);
  2091. cli.set_follow_location(true);
  2092. auto res =
  2093. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2094. ASSERT_TRUE(res);
  2095. EXPECT_EQ(StatusCode::OK_200, res->status);
  2096. }
  2097. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2098. SSLClient cli(REDIR_HOST);
  2099. cli.set_follow_location(true);
  2100. Params params;
  2101. params.emplace("url", "http://example.com");
  2102. params.emplace("status_code", "302");
  2103. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2104. ASSERT_TRUE(res);
  2105. EXPECT_EQ(StatusCode::OK_200, res->status);
  2106. }
  2107. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2108. SSLClient cli(REDIR_HOST);
  2109. cli.set_follow_location(true);
  2110. Params params;
  2111. params.emplace("url", "http://example.com");
  2112. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2113. ASSERT_TRUE(res);
  2114. EXPECT_EQ(StatusCode::OK_200, res->status);
  2115. }
  2116. TEST(UrlWithSpace, Redirect_Online) {
  2117. SSLClient cli("edge.forgecdn.net");
  2118. cli.set_follow_location(true);
  2119. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2120. ASSERT_TRUE(res);
  2121. EXPECT_EQ(StatusCode::OK_200, res->status);
  2122. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2123. }
  2124. #endif
  2125. #if !defined(_WIN32) && !defined(_WIN64)
  2126. TEST(ReceiveSignals, Signal) {
  2127. auto setupSignalHandlers = []() {
  2128. struct sigaction act;
  2129. sigemptyset(&act.sa_mask);
  2130. act.sa_flags = SA_SIGINFO;
  2131. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2132. switch (sig) {
  2133. case SIGINT:
  2134. default: break;
  2135. }
  2136. };
  2137. ::sigaction(SIGINT, &act, nullptr);
  2138. };
  2139. Server svr;
  2140. int port = 0;
  2141. auto thread = std::thread([&]() {
  2142. setupSignalHandlers();
  2143. port = svr.bind_to_any_port(HOST);
  2144. svr.listen_after_bind();
  2145. });
  2146. auto se = detail::scope_exit([&] {
  2147. svr.stop();
  2148. thread.join();
  2149. ASSERT_FALSE(svr.is_running());
  2150. });
  2151. svr.wait_until_ready();
  2152. ASSERT_TRUE(svr.is_running());
  2153. pthread_kill(thread.native_handle(), SIGINT);
  2154. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2155. ASSERT_TRUE(svr.is_running());
  2156. }
  2157. #endif
  2158. TEST(RedirectToDifferentPort, Redirect) {
  2159. Server svr1;
  2160. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2161. res.set_content("Hello World!", "text/plain");
  2162. });
  2163. int svr1_port = 0;
  2164. auto thread1 = std::thread([&]() {
  2165. svr1_port = svr1.bind_to_any_port(HOST);
  2166. svr1.listen_after_bind();
  2167. });
  2168. Server svr2;
  2169. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2170. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2171. });
  2172. int svr2_port = 0;
  2173. auto thread2 = std::thread([&]() {
  2174. svr2_port = svr2.bind_to_any_port(HOST);
  2175. svr2.listen_after_bind();
  2176. });
  2177. auto se = detail::scope_exit([&] {
  2178. svr2.stop();
  2179. thread2.join();
  2180. svr1.stop();
  2181. thread1.join();
  2182. ASSERT_FALSE(svr2.is_running());
  2183. ASSERT_FALSE(svr1.is_running());
  2184. });
  2185. svr1.wait_until_ready();
  2186. svr2.wait_until_ready();
  2187. Client cli("localhost", svr2_port);
  2188. cli.set_follow_location(true);
  2189. auto res = cli.Get("/2");
  2190. ASSERT_TRUE(res);
  2191. EXPECT_EQ(StatusCode::OK_200, res->status);
  2192. EXPECT_EQ("Hello World!", res->body);
  2193. }
  2194. static void
  2195. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2196. Server svr1;
  2197. std::string captured_authorization;
  2198. svr1.Get("/target", [&](const Request &req, Response &res) {
  2199. captured_authorization = req.get_header_value("Authorization");
  2200. res.set_content("OK", "text/plain");
  2201. });
  2202. int svr1_port = 0;
  2203. auto thread1 = std::thread([&]() {
  2204. svr1_port = svr1.bind_to_any_port(HOST);
  2205. svr1.listen_after_bind();
  2206. });
  2207. Server svr2;
  2208. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2209. res.set_redirect(
  2210. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2211. });
  2212. int svr2_port = 0;
  2213. auto thread2 = std::thread([&]() {
  2214. svr2_port = svr2.bind_to_any_port(HOST);
  2215. svr2.listen_after_bind();
  2216. });
  2217. auto se = detail::scope_exit([&] {
  2218. svr2.stop();
  2219. thread2.join();
  2220. svr1.stop();
  2221. thread1.join();
  2222. ASSERT_FALSE(svr2.is_running());
  2223. ASSERT_FALSE(svr1.is_running());
  2224. });
  2225. svr1.wait_until_ready();
  2226. svr2.wait_until_ready();
  2227. Client cli("localhost", svr2_port);
  2228. cli.set_follow_location(true);
  2229. set_auth(cli);
  2230. auto res = cli.Get("/redir");
  2231. ASSERT_TRUE(res);
  2232. EXPECT_EQ(StatusCode::OK_200, res->status);
  2233. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2234. EXPECT_TRUE(captured_authorization.empty());
  2235. }
  2236. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2237. TestDoNotForwardCredentialsOnRedirect(
  2238. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2239. }
  2240. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2241. TestDoNotForwardCredentialsOnRedirect(
  2242. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2243. }
  2244. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2245. Server svr;
  2246. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2247. // Port number that overflows int — should not crash
  2248. res.set_redirect("http://localhost:99999999999999999999/target");
  2249. });
  2250. auto port = svr.bind_to_any_port(HOST);
  2251. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2252. auto se = detail::scope_exit([&] {
  2253. svr.stop();
  2254. thread.join();
  2255. ASSERT_FALSE(svr.is_running());
  2256. });
  2257. svr.wait_until_ready();
  2258. Client cli(HOST, port);
  2259. cli.set_follow_location(true);
  2260. auto res = cli.Get("/redir");
  2261. // Should fail gracefully, not crash (no valid response due to bad port)
  2262. EXPECT_FALSE(res);
  2263. }
  2264. TEST(RedirectFromPageWithContent, Redirect) {
  2265. Server svr;
  2266. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2267. res.set_content("___", "text/plain");
  2268. res.set_redirect("/2");
  2269. });
  2270. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2271. res.set_content("Hello World!", "text/plain");
  2272. });
  2273. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2274. auto se = detail::scope_exit([&] {
  2275. svr.stop();
  2276. th.join();
  2277. ASSERT_FALSE(svr.is_running());
  2278. });
  2279. svr.wait_until_ready();
  2280. {
  2281. Client cli("localhost", PORT);
  2282. cli.set_follow_location(true);
  2283. std::string body;
  2284. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2285. body.append(data, data_length);
  2286. return true;
  2287. });
  2288. ASSERT_TRUE(res);
  2289. EXPECT_EQ(StatusCode::OK_200, res->status);
  2290. EXPECT_EQ("Hello World!", body);
  2291. }
  2292. {
  2293. Client cli("localhost", PORT);
  2294. std::string body;
  2295. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2296. body.append(data, data_length);
  2297. return true;
  2298. });
  2299. ASSERT_TRUE(res);
  2300. EXPECT_EQ(StatusCode::Found_302, res->status);
  2301. EXPECT_EQ("___", body);
  2302. }
  2303. }
  2304. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2305. Server svr;
  2306. auto port_str = std::to_string(PORT);
  2307. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2308. auto expected_host = "[::1]:" + port_str;
  2309. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2310. res.set_content("___", "text/plain");
  2311. // res.set_redirect("/2");
  2312. res.set_redirect(redirect_url);
  2313. });
  2314. svr.Get("/2", [&](const Request &req, Response &res) {
  2315. auto host_header = req.headers.find("Host");
  2316. ASSERT_TRUE(host_header != req.headers.end());
  2317. EXPECT_EQ(expected_host, host_header->second);
  2318. res.set_content("Hello World!", "text/plain");
  2319. });
  2320. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2321. auto se = detail::scope_exit([&] {
  2322. svr.stop();
  2323. th.join();
  2324. ASSERT_FALSE(svr.is_running());
  2325. });
  2326. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2327. // actually starts anything, so the condition !svr.is_running() will
  2328. // always remain true, and the loop never stops.
  2329. // This basically counts how many milliseconds have passed since the
  2330. // call to svr.listen(), and if after 5 seconds nothing started yet
  2331. // aborts the test.
  2332. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2333. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2334. ASSERT_LT(milliseconds, 5000U);
  2335. }
  2336. {
  2337. Client cli("::1", PORT);
  2338. cli.set_follow_location(true);
  2339. std::string body;
  2340. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2341. body.append(data, data_length);
  2342. return true;
  2343. });
  2344. ASSERT_TRUE(res);
  2345. EXPECT_EQ(StatusCode::OK_200, res->status);
  2346. EXPECT_EQ("Hello World!", body);
  2347. }
  2348. {
  2349. Client cli("::1", PORT);
  2350. std::string body;
  2351. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2352. body.append(data, data_length);
  2353. return true;
  2354. });
  2355. ASSERT_TRUE(res);
  2356. EXPECT_EQ(StatusCode::Found_302, res->status);
  2357. EXPECT_EQ("___", body);
  2358. }
  2359. }
  2360. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2361. Server svr;
  2362. svr.Get("/foo", [](const Request &req, Response &res) {
  2363. auto a = req.params.find("a");
  2364. if (a != req.params.end()) {
  2365. res.set_content((*a).second, "text/plain");
  2366. res.status = StatusCode::OK_200;
  2367. } else {
  2368. res.status = StatusCode::BadRequest_400;
  2369. }
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. {
  2379. Client cli(HOST, PORT);
  2380. cli.set_path_encode(false);
  2381. auto res = cli.Get("/foo?a=explicitly+encoded");
  2382. ASSERT_TRUE(res);
  2383. EXPECT_EQ(StatusCode::OK_200, res->status);
  2384. // This expects it back with a space, as the `+` won't have been
  2385. // url-encoded, and server-side the params get decoded turning `+`
  2386. // into spaces.
  2387. EXPECT_EQ("explicitly encoded", res->body);
  2388. }
  2389. }
  2390. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2391. Server svr;
  2392. svr.Get("/", [](const Request &req, Response &) {
  2393. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2394. });
  2395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2396. auto se = detail::scope_exit([&] {
  2397. svr.stop();
  2398. thread.join();
  2399. ASSERT_FALSE(svr.is_running());
  2400. });
  2401. svr.wait_until_ready();
  2402. {
  2403. Client cli(HOST, PORT);
  2404. cli.set_path_encode(false);
  2405. auto res = cli.Get("/?something=%0A");
  2406. ASSERT_TRUE(res);
  2407. EXPECT_EQ(StatusCode::OK_200, res->status);
  2408. }
  2409. }
  2410. TEST(BindServerTest, BindDualStack) {
  2411. Server svr;
  2412. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2413. res.set_content("Hello World!", "text/plain");
  2414. });
  2415. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2416. auto se = detail::scope_exit([&] {
  2417. svr.stop();
  2418. thread.join();
  2419. ASSERT_FALSE(svr.is_running());
  2420. });
  2421. svr.wait_until_ready();
  2422. {
  2423. Client cli("127.0.0.1", PORT);
  2424. auto res = cli.Get("/1");
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::OK_200, res->status);
  2427. EXPECT_EQ("Hello World!", res->body);
  2428. }
  2429. {
  2430. Client cli("::1", PORT);
  2431. auto res = cli.Get("/1");
  2432. ASSERT_TRUE(res);
  2433. EXPECT_EQ(StatusCode::OK_200, res->status);
  2434. EXPECT_EQ("Hello World!", res->body);
  2435. }
  2436. }
  2437. TEST(BindServerTest, BindAndListenSeparately) {
  2438. Server svr;
  2439. int port = svr.bind_to_any_port("0.0.0.0");
  2440. ASSERT_TRUE(svr.is_valid());
  2441. ASSERT_TRUE(port > 0);
  2442. svr.stop();
  2443. }
  2444. #ifdef CPPHTTPLIB_SSL_ENABLED
  2445. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2447. CLIENT_CA_CERT_DIR);
  2448. int port = svr.bind_to_any_port("0.0.0.0");
  2449. ASSERT_TRUE(svr.is_valid());
  2450. ASSERT_TRUE(port > 0);
  2451. svr.stop();
  2452. }
  2453. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2454. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2455. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2456. int port = svr.bind_to_any_port("0.0.0.0");
  2457. ASSERT_TRUE(svr.is_valid());
  2458. ASSERT_TRUE(port > 0);
  2459. svr.stop();
  2460. }
  2461. TEST(BindServerTest, UpdateCertsPem) {
  2462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2463. int port = svr.bind_to_any_port("0.0.0.0");
  2464. ASSERT_TRUE(svr.is_valid());
  2465. ASSERT_TRUE(port > 0);
  2466. // Read PEM files
  2467. std::string cert_pem, key_pem, ca_pem;
  2468. read_file(SERVER_CERT_FILE, cert_pem);
  2469. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2470. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2471. // Update server certificates using PEM API
  2472. ASSERT_TRUE(
  2473. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2474. ASSERT_TRUE(svr.is_valid());
  2475. svr.stop();
  2476. }
  2477. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2478. // Start server with client CA (enables client auth)
  2479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2480. ASSERT_TRUE(svr.is_valid());
  2481. bool handler_called = false;
  2482. svr.Get("/test", [&](const Request &req, Response &res) {
  2483. handler_called = true;
  2484. // Verify client certificate is present
  2485. auto cert = req.peer_cert();
  2486. EXPECT_TRUE(static_cast<bool>(cert));
  2487. res.set_content("ok", "text/plain");
  2488. });
  2489. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2490. auto se = detail::scope_exit([&] {
  2491. svr.stop();
  2492. t.join();
  2493. ASSERT_FALSE(svr.is_running());
  2494. });
  2495. svr.wait_until_ready();
  2496. // Read PEM files
  2497. std::string cert_pem, key_pem, ca_pem;
  2498. read_file(SERVER_CERT_FILE, cert_pem);
  2499. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2500. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2501. // Update server certificates and client CA using PEM API while server running
  2502. ASSERT_TRUE(
  2503. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2504. // Connect with client certificate
  2505. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2506. cli.enable_server_certificate_verification(false);
  2507. cli.set_connection_timeout(30);
  2508. auto res = cli.Get("/test");
  2509. ASSERT_TRUE(res);
  2510. ASSERT_EQ(StatusCode::OK_200, res->status);
  2511. ASSERT_TRUE(handler_called);
  2512. EXPECT_EQ("ok", res->body);
  2513. }
  2514. #endif
  2515. TEST(ErrorHandlerTest, ContentLength) {
  2516. Server svr;
  2517. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2518. res.status = StatusCode::OK_200;
  2519. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2520. "text/html"); // <= Content-Length still 13
  2521. });
  2522. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2523. res.set_content("Hello World!\n", "text/plain");
  2524. res.status = 524;
  2525. });
  2526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. {
  2534. Client cli(HOST, PORT);
  2535. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2536. ASSERT_TRUE(res);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2539. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2540. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2541. }
  2542. }
  2543. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2544. TEST(ExceptionTest, WithoutExceptionHandler) {
  2545. Server svr;
  2546. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2547. throw std::runtime_error("exception...");
  2548. });
  2549. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2550. throw std::runtime_error("exception\r\n...");
  2551. });
  2552. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. listen_thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli("localhost", PORT);
  2560. {
  2561. auto res = cli.Get("/exception");
  2562. ASSERT_TRUE(res);
  2563. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2564. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2565. }
  2566. {
  2567. auto res = cli.Get("/unknown");
  2568. ASSERT_TRUE(res);
  2569. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2570. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2571. }
  2572. }
  2573. TEST(ExceptionTest, WithExceptionHandler) {
  2574. Server svr;
  2575. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2576. std::exception_ptr ep) {
  2577. EXPECT_FALSE(ep == nullptr);
  2578. try {
  2579. std::rethrow_exception(ep);
  2580. } catch (std::exception &e) {
  2581. EXPECT_EQ("abc", std::string(e.what()));
  2582. } catch (...) {}
  2583. res.status = StatusCode::InternalServerError_500;
  2584. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2585. "text/html"); // <= Content-Length still 13 at this point
  2586. });
  2587. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2588. res.set_content("Hello World!\n", "text/plain");
  2589. throw std::runtime_error("abc");
  2590. });
  2591. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2592. auto se = detail::scope_exit([&] {
  2593. svr.stop();
  2594. thread.join();
  2595. ASSERT_FALSE(svr.is_running());
  2596. });
  2597. svr.wait_until_ready();
  2598. for (size_t i = 0; i < 10; i++) {
  2599. Client cli(HOST, PORT);
  2600. for (size_t j = 0; j < 100; j++) {
  2601. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2602. ASSERT_TRUE(res);
  2603. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2604. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2605. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2606. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2607. }
  2608. cli.set_keep_alive(true);
  2609. for (size_t j = 0; j < 100; j++) {
  2610. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2611. ASSERT_TRUE(res);
  2612. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2613. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2614. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2615. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2616. }
  2617. }
  2618. }
  2619. TEST(ExceptionTest, AndErrorHandler) {
  2620. Server svr;
  2621. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2622. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2623. });
  2624. svr.set_exception_handler(
  2625. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2626. EXPECT_FALSE(ep == nullptr);
  2627. try {
  2628. std::rethrow_exception(ep);
  2629. } catch (std::exception &e) {
  2630. res.set_content(e.what(), "text/html");
  2631. } catch (...) {}
  2632. res.status = StatusCode::InternalServerError_500;
  2633. });
  2634. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2635. throw std::runtime_error("EXCEPTION");
  2636. });
  2637. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2638. res.set_content("ERROR", "text/html");
  2639. res.status = StatusCode::InternalServerError_500;
  2640. });
  2641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2642. auto se = detail::scope_exit([&] {
  2643. svr.stop();
  2644. thread.join();
  2645. ASSERT_FALSE(svr.is_running());
  2646. });
  2647. svr.wait_until_ready();
  2648. Client cli(HOST, PORT);
  2649. {
  2650. auto res = cli.Get("/exception");
  2651. ASSERT_TRUE(res);
  2652. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2653. EXPECT_EQ("EXCEPTION", res->body);
  2654. }
  2655. {
  2656. auto res = cli.Get("/error");
  2657. ASSERT_TRUE(res);
  2658. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2659. EXPECT_EQ("ERROR", res->body);
  2660. }
  2661. {
  2662. auto res = cli.Get("/invalid");
  2663. ASSERT_TRUE(res);
  2664. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2665. EXPECT_EQ("NOT_FOUND", res->body);
  2666. }
  2667. }
  2668. #endif
  2669. TEST(NoContentTest, ContentLength) {
  2670. Server svr;
  2671. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2672. res.status = StatusCode::NoContent_204;
  2673. });
  2674. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2675. auto se = detail::scope_exit([&] {
  2676. svr.stop();
  2677. thread.join();
  2678. ASSERT_FALSE(svr.is_running());
  2679. });
  2680. svr.wait_until_ready();
  2681. {
  2682. Client cli(HOST, PORT);
  2683. auto res = cli.Get("/hi");
  2684. ASSERT_TRUE(res);
  2685. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2686. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2687. }
  2688. }
  2689. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2690. #ifdef CPPHTTPLIB_SSL_ENABLED
  2691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2692. ASSERT_TRUE(svr.is_valid());
  2693. #else
  2694. Server svr;
  2695. #endif
  2696. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2697. if (req.path == "/routing_handler") {
  2698. res.set_header("PRE_ROUTING", "on");
  2699. res.set_content("Routing Handler", "text/plain");
  2700. return httplib::Server::HandlerResponse::Handled;
  2701. }
  2702. return httplib::Server::HandlerResponse::Unhandled;
  2703. });
  2704. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2705. res.set_content("Error", "text/html");
  2706. });
  2707. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2708. if (req.path == "/routing_handler") {
  2709. res.set_header("POST_ROUTING", "on");
  2710. }
  2711. });
  2712. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2713. res.set_content("Hello World!\n", "text/plain");
  2714. });
  2715. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2716. auto se = detail::scope_exit([&] {
  2717. svr.stop();
  2718. thread.join();
  2719. ASSERT_FALSE(svr.is_running());
  2720. });
  2721. svr.wait_until_ready();
  2722. {
  2723. #ifdef CPPHTTPLIB_SSL_ENABLED
  2724. SSLClient cli(HOST, PORT);
  2725. cli.enable_server_certificate_verification(false);
  2726. #else
  2727. Client cli(HOST, PORT);
  2728. #endif
  2729. auto res = cli.Get("/routing_handler");
  2730. ASSERT_TRUE(res);
  2731. EXPECT_EQ(StatusCode::OK_200, res->status);
  2732. EXPECT_EQ("Routing Handler", res->body);
  2733. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2734. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2735. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2736. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2737. }
  2738. {
  2739. #ifdef CPPHTTPLIB_SSL_ENABLED
  2740. SSLClient cli(HOST, PORT);
  2741. cli.enable_server_certificate_verification(false);
  2742. #else
  2743. Client cli(HOST, PORT);
  2744. #endif
  2745. auto res = cli.Get("/hi");
  2746. ASSERT_TRUE(res);
  2747. EXPECT_EQ(StatusCode::OK_200, res->status);
  2748. EXPECT_EQ("Hello World!\n", res->body);
  2749. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2750. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2751. }
  2752. {
  2753. #ifdef CPPHTTPLIB_SSL_ENABLED
  2754. SSLClient cli(HOST, PORT);
  2755. cli.enable_server_certificate_verification(false);
  2756. #else
  2757. Client cli(HOST, PORT);
  2758. #endif
  2759. auto res = cli.Get("/aaa");
  2760. ASSERT_TRUE(res);
  2761. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2762. EXPECT_EQ("Error", res->body);
  2763. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2764. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2765. }
  2766. }
  2767. TEST(RequestHandlerTest, PreRequestHandler) {
  2768. auto route_path = "/user/:user";
  2769. Server svr;
  2770. svr.Get("/hi", [](const Request &, Response &res) {
  2771. res.set_content("hi", "text/plain");
  2772. });
  2773. svr.Get(route_path, [](const Request &req, Response &res) {
  2774. res.set_content(req.path_params.at("user"), "text/plain");
  2775. });
  2776. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2777. if (req.matched_route == route_path) {
  2778. auto user = req.path_params.at("user");
  2779. if (user != "john") {
  2780. res.status = StatusCode::Forbidden_403;
  2781. res.set_content("error", "text/html");
  2782. return Server::HandlerResponse::Handled;
  2783. }
  2784. }
  2785. return Server::HandlerResponse::Unhandled;
  2786. });
  2787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2788. auto se = detail::scope_exit([&] {
  2789. svr.stop();
  2790. thread.join();
  2791. ASSERT_FALSE(svr.is_running());
  2792. });
  2793. svr.wait_until_ready();
  2794. Client cli(HOST, PORT);
  2795. {
  2796. auto res = cli.Get("/hi");
  2797. ASSERT_TRUE(res);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. EXPECT_EQ("hi", res->body);
  2800. }
  2801. {
  2802. auto res = cli.Get("/user/john");
  2803. ASSERT_TRUE(res);
  2804. EXPECT_EQ(StatusCode::OK_200, res->status);
  2805. EXPECT_EQ("john", res->body);
  2806. }
  2807. {
  2808. auto res = cli.Get("/user/invalid-user");
  2809. ASSERT_TRUE(res);
  2810. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2811. EXPECT_EQ("error", res->body);
  2812. }
  2813. }
  2814. // The pre-request handler must run before the request body is read, so a
  2815. // rejected request never forces the server to buffer a (potentially large)
  2816. // body. Here the posted body is larger than the payload limit: if the body
  2817. // were read first the server would answer 413, but because the pre-request
  2818. // handler runs first it answers 403 and the body is never read.
  2819. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2820. Server svr;
  2821. svr.set_payload_max_length(8);
  2822. auto handler_ran = false;
  2823. svr.Post("/reject", [&](const Request &req, Response &res) {
  2824. handler_ran = true;
  2825. res.set_content(req.body, "text/plain");
  2826. });
  2827. svr.Post("/accept", [](const Request &req, Response &res) {
  2828. res.set_content(req.body, "text/plain");
  2829. });
  2830. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2831. if (req.matched_route == "/reject") {
  2832. res.status = StatusCode::Forbidden_403;
  2833. res.set_content("denied", "text/plain");
  2834. return Server::HandlerResponse::Handled;
  2835. }
  2836. return Server::HandlerResponse::Unhandled;
  2837. });
  2838. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2839. auto se = detail::scope_exit([&] {
  2840. svr.stop();
  2841. thread.join();
  2842. ASSERT_FALSE(svr.is_running());
  2843. });
  2844. svr.wait_until_ready();
  2845. Client cli(HOST, PORT);
  2846. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2847. // rejects with 403 before the body is read, so 413 is never reached.
  2848. {
  2849. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2850. ASSERT_TRUE(res);
  2851. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2852. EXPECT_EQ("denied", res->body);
  2853. EXPECT_FALSE(handler_ran);
  2854. }
  2855. // An approved route still reads the body and enforces the payload limit.
  2856. {
  2857. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2858. ASSERT_TRUE(res);
  2859. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2860. }
  2861. }
  2862. TEST(UserDataTest, BasicOperations) {
  2863. httplib::UserData ud;
  2864. // Initially empty
  2865. EXPECT_FALSE(ud.has("key"));
  2866. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2867. // set and get
  2868. ud.set("key", 42);
  2869. EXPECT_TRUE(ud.has("key"));
  2870. auto *p = ud.get<int>("key");
  2871. ASSERT_NE(nullptr, p);
  2872. EXPECT_EQ(42, *p);
  2873. // Type mismatch → nullptr
  2874. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2875. // Overwrite with different type
  2876. ud.set("key", std::string("hello"));
  2877. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2878. auto *s = ud.get<std::string>("key");
  2879. ASSERT_NE(nullptr, s);
  2880. EXPECT_EQ("hello", *s);
  2881. // erase
  2882. ud.erase("key");
  2883. EXPECT_FALSE(ud.has("key"));
  2884. // clear
  2885. ud.set("a", 1);
  2886. ud.set("b", 2);
  2887. ud.clear();
  2888. EXPECT_FALSE(ud.has("a"));
  2889. EXPECT_FALSE(ud.has("b"));
  2890. }
  2891. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2892. struct AuthCtx {
  2893. std::string user_id;
  2894. };
  2895. Server svr;
  2896. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2897. res.user_data.set("auth", AuthCtx{"alice"});
  2898. return Server::HandlerResponse::Unhandled;
  2899. });
  2900. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2901. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2902. ASSERT_NE(nullptr, ctx);
  2903. res.set_content("Hello " + ctx->user_id, "text/plain");
  2904. });
  2905. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2906. auto se = detail::scope_exit([&] {
  2907. svr.stop();
  2908. thread.join();
  2909. ASSERT_FALSE(svr.is_running());
  2910. });
  2911. svr.wait_until_ready();
  2912. Client cli(HOST, PORT);
  2913. auto res = cli.Get("/me");
  2914. ASSERT_TRUE(res);
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. EXPECT_EQ("Hello alice", res->body);
  2917. }
  2918. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2919. struct RoleCtx {
  2920. std::string role;
  2921. };
  2922. Server svr;
  2923. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2924. res.user_data.set("role", RoleCtx{"admin"});
  2925. return Server::HandlerResponse::Unhandled;
  2926. });
  2927. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2928. auto *ctx = res.user_data.get<RoleCtx>("role");
  2929. ASSERT_NE(nullptr, ctx);
  2930. res.set_content(ctx->role, "text/plain");
  2931. });
  2932. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2933. auto se = detail::scope_exit([&] {
  2934. svr.stop();
  2935. thread.join();
  2936. ASSERT_FALSE(svr.is_running());
  2937. });
  2938. svr.wait_until_ready();
  2939. Client cli(HOST, PORT);
  2940. auto res = cli.Get("/role");
  2941. ASSERT_TRUE(res);
  2942. EXPECT_EQ(StatusCode::OK_200, res->status);
  2943. EXPECT_EQ("admin", res->body);
  2944. }
  2945. TEST(InvalidFormatTest, StatusCode) {
  2946. Server svr;
  2947. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2948. res.set_content("Hello World!\n", "text/plain");
  2949. res.status = 9999; // Status should be a three-digit code...
  2950. });
  2951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2952. auto se = detail::scope_exit([&] {
  2953. svr.stop();
  2954. thread.join();
  2955. ASSERT_FALSE(svr.is_running());
  2956. });
  2957. svr.wait_until_ready();
  2958. {
  2959. Client cli(HOST, PORT);
  2960. auto res = cli.Get("/hi");
  2961. ASSERT_FALSE(res);
  2962. }
  2963. }
  2964. TEST(URLFragmentTest, WithFragment) {
  2965. Server svr;
  2966. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2967. EXPECT_TRUE(req.target == "/hi");
  2968. });
  2969. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2970. auto se = detail::scope_exit([&] {
  2971. svr.stop();
  2972. thread.join();
  2973. ASSERT_FALSE(svr.is_running());
  2974. });
  2975. svr.wait_until_ready();
  2976. {
  2977. Client cli(HOST, PORT);
  2978. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2979. EXPECT_TRUE(res);
  2980. EXPECT_EQ(StatusCode::OK_200, res->status);
  2981. res = cli.Get("/hi%23key1=val1=key2=val2");
  2982. EXPECT_TRUE(res);
  2983. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2984. }
  2985. }
  2986. TEST(HeaderWriter, SetHeaderWriter) {
  2987. Server svr;
  2988. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2989. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2990. return detail::write_headers(strm, hdrs);
  2991. });
  2992. svr.Get("/hi", [](const Request &req, Response &res) {
  2993. auto it = req.headers.find("CustomClientHeader");
  2994. EXPECT_TRUE(it != req.headers.end());
  2995. EXPECT_EQ(it->second, "CustomClientValue");
  2996. res.set_content("Hello World!\n", "text/plain");
  2997. });
  2998. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2999. auto se = detail::scope_exit([&] {
  3000. svr.stop();
  3001. thread.join();
  3002. ASSERT_FALSE(svr.is_running());
  3003. });
  3004. svr.wait_until_ready();
  3005. {
  3006. Client cli(HOST, PORT);
  3007. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3008. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3009. return detail::write_headers(strm, hdrs);
  3010. });
  3011. auto res = cli.Get("/hi");
  3012. EXPECT_TRUE(res);
  3013. EXPECT_EQ(StatusCode::OK_200, res->status);
  3014. auto it = res->headers.find("CustomServerHeader");
  3015. EXPECT_TRUE(it != res->headers.end());
  3016. EXPECT_EQ(it->second, "CustomServerValue");
  3017. }
  3018. }
  3019. class ServerTest : public ::testing::Test {
  3020. protected:
  3021. ServerTest()
  3022. : cli_(HOST, PORT)
  3023. #ifdef CPPHTTPLIB_SSL_ENABLED
  3024. ,
  3025. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3026. #endif
  3027. {
  3028. #ifdef CPPHTTPLIB_SSL_ENABLED
  3029. cli_.enable_server_certificate_verification(false);
  3030. #endif
  3031. // Allow LARGE_DATA (100MB) responses
  3032. cli_.set_payload_max_length(200 * 1024 * 1024);
  3033. }
  3034. virtual void SetUp() {
  3035. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3036. svr_.set_payload_max_length(200 * 1024 * 1024);
  3037. svr_.set_mount_point("/", "./www");
  3038. svr_.set_mount_point("/mount", "./www2");
  3039. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3040. svr_.Get("/hi",
  3041. [&](const Request & /*req*/, Response &res) {
  3042. res.set_content("Hello World!", "text/plain");
  3043. })
  3044. .Get("/file_content",
  3045. [&](const Request & /*req*/, Response &res) {
  3046. res.set_file_content("./www/dir/test.html");
  3047. })
  3048. .Get("/file_content_with_content_type",
  3049. [&](const Request & /*req*/, Response &res) {
  3050. res.set_file_content("./www/file", "text/plain");
  3051. })
  3052. .Get("/invalid_file_content",
  3053. [&](const Request & /*req*/, Response &res) {
  3054. res.set_file_content("./www/dir/invalid_file_path");
  3055. })
  3056. .Get("/http_response_splitting",
  3057. [&](const Request & /*req*/, Response &res) {
  3058. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3059. EXPECT_EQ(0U, res.headers.size());
  3060. EXPECT_FALSE(res.has_header("a"));
  3061. res.set_header("a", "1\nSet-Cookie: a=1");
  3062. EXPECT_EQ(0U, res.headers.size());
  3063. EXPECT_FALSE(res.has_header("a"));
  3064. res.set_header("a", "1\rSet-Cookie: a=1");
  3065. EXPECT_EQ(0U, res.headers.size());
  3066. EXPECT_FALSE(res.has_header("a"));
  3067. res.set_header("a\r\nb", "0");
  3068. EXPECT_EQ(0U, res.headers.size());
  3069. EXPECT_FALSE(res.has_header("a"));
  3070. res.set_header("a\rb", "0");
  3071. EXPECT_EQ(0U, res.headers.size());
  3072. EXPECT_FALSE(res.has_header("a"));
  3073. res.set_header("a\nb", "0");
  3074. EXPECT_EQ(0U, res.headers.size());
  3075. EXPECT_FALSE(res.has_header("a"));
  3076. res.set_redirect("1\r\nSet-Cookie: a=1");
  3077. EXPECT_EQ(0U, res.headers.size());
  3078. EXPECT_FALSE(res.has_header("Location"));
  3079. })
  3080. .Get("/slow",
  3081. [&](const Request & /*req*/, Response &res) {
  3082. std::this_thread::sleep_for(std::chrono::seconds(4));
  3083. res.set_content("slow", "text/plain");
  3084. })
  3085. #if 0
  3086. .Post("/slowpost",
  3087. [&](const Request & /*req*/, Response &res) {
  3088. std::this_thread::sleep_for(std::chrono::seconds(2));
  3089. res.set_content("slow", "text/plain");
  3090. })
  3091. #endif
  3092. .Get("/remote_addr",
  3093. [&](const Request &req, Response &res) {
  3094. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3095. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3096. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3097. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3098. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3099. #endif
  3100. res.set_content(req.remote_addr, "text/plain");
  3101. })
  3102. .Get("/local_addr",
  3103. [&](const Request &req, Response &res) {
  3104. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3105. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3106. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3107. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3108. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3109. #endif
  3110. auto local_addr = req.local_addr;
  3111. auto local_port = std::to_string(req.local_port);
  3112. res.set_content(local_addr.append(":").append(local_port),
  3113. "text/plain");
  3114. })
  3115. .Get("/endwith%",
  3116. [&](const Request & /*req*/, Response &res) {
  3117. res.set_content("Hello World!", "text/plain");
  3118. })
  3119. .Get("/a\\+\\+b",
  3120. [&](const Request &req, Response &res) {
  3121. ASSERT_TRUE(req.has_param("a +b"));
  3122. auto val = req.get_param_value("a +b");
  3123. res.set_content(val, "text/plain");
  3124. })
  3125. .Get("/", [&](const Request & /*req*/,
  3126. Response &res) { res.set_redirect("/hi"); })
  3127. .Post("/1",
  3128. [](const Request & /*req*/, Response &res) {
  3129. res.set_redirect("/2", StatusCode::SeeOther_303);
  3130. })
  3131. .Get("/2",
  3132. [](const Request & /*req*/, Response &res) {
  3133. res.set_content("redirected.", "text/plain");
  3134. res.status = StatusCode::OK_200;
  3135. })
  3136. .Post("/person",
  3137. [&](const Request &req, Response &res) {
  3138. if (req.has_param("name") && req.has_param("note")) {
  3139. persons_[req.get_param_value("name")] =
  3140. req.get_param_value("note");
  3141. } else {
  3142. res.status = StatusCode::BadRequest_400;
  3143. }
  3144. })
  3145. .Put("/person",
  3146. [&](const Request &req, Response &res) {
  3147. if (req.has_param("name") && req.has_param("note")) {
  3148. persons_[req.get_param_value("name")] =
  3149. req.get_param_value("note");
  3150. } else {
  3151. res.status = StatusCode::BadRequest_400;
  3152. }
  3153. })
  3154. .Get("/person/(.*)",
  3155. [&](const Request &req, Response &res) {
  3156. string name = req.matches[1];
  3157. if (persons_.find(name) != persons_.end()) {
  3158. auto note = persons_[name];
  3159. res.set_content(note, "text/plain");
  3160. } else {
  3161. res.status = StatusCode::NotFound_404;
  3162. }
  3163. })
  3164. .Delete("/person",
  3165. [&](const Request &req, Response &res) {
  3166. if (req.has_param("name")) {
  3167. string name = req.get_param_value("name");
  3168. if (persons_.find(name) != persons_.end()) {
  3169. persons_.erase(name);
  3170. res.set_content("DELETED", "text/plain");
  3171. } else {
  3172. res.status = StatusCode::NotFound_404;
  3173. }
  3174. } else {
  3175. res.status = StatusCode::BadRequest_400;
  3176. }
  3177. })
  3178. .Post("/x-www-form-urlencoded-json",
  3179. [&](const Request &req, Response &res) {
  3180. auto json = req.get_param_value("json");
  3181. ASSERT_EQ(JSON_DATA, json);
  3182. res.set_content(json, "appliation/json");
  3183. res.status = StatusCode::OK_200;
  3184. })
  3185. .Get("/streamed-chunked",
  3186. [&](const Request & /*req*/, Response &res) {
  3187. res.set_chunked_content_provider(
  3188. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3189. sink.os << "123";
  3190. sink.os << "456";
  3191. sink.os << "789";
  3192. sink.done();
  3193. return true;
  3194. });
  3195. })
  3196. .Get("/streamed-chunked-with-prohibited-trailer",
  3197. [&](const Request & /*req*/, Response &res) {
  3198. auto i = new int(0);
  3199. // Declare both a prohibited trailer (Content-Length) and an
  3200. // allowed one
  3201. res.set_header("Trailer", "Content-Length, X-Allowed");
  3202. res.set_chunked_content_provider(
  3203. "text/plain",
  3204. [i](size_t /*offset*/, DataSink &sink) {
  3205. switch (*i) {
  3206. case 0: sink.os << "123"; break;
  3207. case 1: sink.os << "456"; break;
  3208. case 2: sink.os << "789"; break;
  3209. case 3: {
  3210. sink.done_with_trailer(
  3211. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3212. } break;
  3213. }
  3214. (*i)++;
  3215. return true;
  3216. },
  3217. [i](bool success) {
  3218. EXPECT_TRUE(success);
  3219. delete i;
  3220. });
  3221. })
  3222. .Get("/streamed-chunked2",
  3223. [&](const Request & /*req*/, Response &res) {
  3224. auto i = new int(0);
  3225. res.set_chunked_content_provider(
  3226. "text/plain",
  3227. [i](size_t /*offset*/, DataSink &sink) {
  3228. switch (*i) {
  3229. case 0: sink.os << "123"; break;
  3230. case 1: sink.os << "456"; break;
  3231. case 2: sink.os << "789"; break;
  3232. case 3: sink.done(); break;
  3233. }
  3234. (*i)++;
  3235. return true;
  3236. },
  3237. [i](bool success) {
  3238. EXPECT_TRUE(success);
  3239. delete i;
  3240. });
  3241. })
  3242. .Get("/streamed-chunked-with-trailer",
  3243. [&](const Request & /*req*/, Response &res) {
  3244. auto i = new int(0);
  3245. res.set_header("Trailer", "Dummy1, Dummy2");
  3246. res.set_chunked_content_provider(
  3247. "text/plain",
  3248. [i](size_t /*offset*/, DataSink &sink) {
  3249. switch (*i) {
  3250. case 0: sink.os << "123"; break;
  3251. case 1: sink.os << "456"; break;
  3252. case 2: sink.os << "789"; break;
  3253. case 3: {
  3254. sink.done_with_trailer(
  3255. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3256. } break;
  3257. }
  3258. (*i)++;
  3259. return true;
  3260. },
  3261. [i](bool success) {
  3262. EXPECT_TRUE(success);
  3263. delete i;
  3264. });
  3265. })
  3266. .Get("/streamed",
  3267. [&](const Request & /*req*/, Response &res) {
  3268. res.set_content_provider(
  3269. 6, "text/plain",
  3270. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3271. sink.os << (offset < 3 ? "a" : "b");
  3272. return true;
  3273. });
  3274. })
  3275. .Get("/streamed-without-length",
  3276. [&](const Request & /*req*/, Response &res) {
  3277. auto data = new std::string("abcdefg");
  3278. res.set_content_provider(
  3279. "text/plain",
  3280. [data](size_t offset, DataSink &sink) {
  3281. if (offset < data->size()) {
  3282. sink.os << data->substr(offset);
  3283. }
  3284. sink.done();
  3285. return true;
  3286. },
  3287. [data](bool success) {
  3288. EXPECT_TRUE(success);
  3289. delete data;
  3290. });
  3291. })
  3292. .Get("/streamed-with-range",
  3293. [&](const Request &req, Response &res) {
  3294. auto data = new std::string("abcdefg");
  3295. res.set_content_provider(
  3296. data->size(), "text/plain",
  3297. [data](size_t offset, size_t length, DataSink &sink) {
  3298. size_t DATA_CHUNK_SIZE = 4;
  3299. const auto &d = *data;
  3300. auto out_len =
  3301. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3302. auto ret =
  3303. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3304. EXPECT_TRUE(ret);
  3305. return true;
  3306. },
  3307. [data, &req](bool success) {
  3308. EXPECT_EQ(success, !req.has_param("error"));
  3309. delete data;
  3310. });
  3311. })
  3312. .Get("/streamed-cancel",
  3313. [&](const Request & /*req*/, Response &res) {
  3314. res.set_content_provider(
  3315. size_t(-1), "text/plain",
  3316. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3317. sink.os << "data_chunk";
  3318. return true;
  3319. });
  3320. })
  3321. .Get("/regex-with-delimiter",
  3322. [&](const Request &req, Response & /*res*/) {
  3323. ASSERT_TRUE(req.has_param("key"));
  3324. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3325. })
  3326. .Get("/with-range",
  3327. [&](const Request & /*req*/, Response &res) {
  3328. res.set_content("abcdefg", "text/plain");
  3329. })
  3330. .Get("/test-start-time",
  3331. [&](const Request &req, Response & /*res*/) {
  3332. EXPECT_NE(req.start_time_,
  3333. std::chrono::steady_clock::time_point::min());
  3334. })
  3335. .Get("/with-range-customized-response",
  3336. [&](const Request & /*req*/, Response &res) {
  3337. res.status = StatusCode::BadRequest_400;
  3338. res.set_content(JSON_DATA, "application/json");
  3339. })
  3340. .Post("/chunked",
  3341. [&](const Request &req, Response & /*res*/) {
  3342. EXPECT_EQ(req.body, "dechunked post body");
  3343. })
  3344. .Post("/large-chunked",
  3345. [&](const Request &req, Response & /*res*/) {
  3346. std::string expected(6 * 30 * 1024u, 'a');
  3347. EXPECT_EQ(req.body, expected);
  3348. })
  3349. .Post("/multipart",
  3350. [&](const Request &req, Response & /*res*/) {
  3351. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3352. req.form.get_field_count("text2") +
  3353. req.form.get_field_count("file3") +
  3354. req.form.get_field_count("file4"));
  3355. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3356. req.form.get_file_count("file2"));
  3357. ASSERT_TRUE(!req.form.has_file("???"));
  3358. ASSERT_TRUE(!req.form.has_field("???"));
  3359. ASSERT_TRUE(req.body.empty());
  3360. {
  3361. const auto &text = req.form.get_field("text1");
  3362. EXPECT_EQ("text default", text);
  3363. }
  3364. {
  3365. const auto &text = req.form.get_field("text2");
  3366. EXPECT_EQ("aωb", text);
  3367. }
  3368. {
  3369. const auto &file = req.form.get_file("file1");
  3370. EXPECT_EQ("hello.txt", file.filename);
  3371. EXPECT_EQ("text/plain", file.content_type);
  3372. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3373. }
  3374. {
  3375. const auto &file = req.form.get_file("file2");
  3376. EXPECT_EQ("world.json", file.filename);
  3377. EXPECT_EQ("application/json", file.content_type);
  3378. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3379. }
  3380. {
  3381. const auto &text = req.form.get_field("file3");
  3382. EXPECT_EQ(0u, text.size());
  3383. }
  3384. {
  3385. const auto &text = req.form.get_field("file4");
  3386. EXPECT_EQ(0u, text.size());
  3387. }
  3388. })
  3389. .Post("/multipart/multi_file_values",
  3390. [&](const Request &req, Response & /*res*/) {
  3391. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3392. req.form.get_field_count("multi_text1"));
  3393. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3394. ASSERT_TRUE(!req.form.has_file("???"));
  3395. ASSERT_TRUE(!req.form.has_field("???"));
  3396. ASSERT_TRUE(req.body.empty());
  3397. {
  3398. const auto &text = req.form.get_field("text");
  3399. EXPECT_EQ("default text", text);
  3400. }
  3401. {
  3402. const auto &text1_values = req.form.get_fields("multi_text1");
  3403. EXPECT_EQ(2u, text1_values.size());
  3404. EXPECT_EQ("aaaaa", text1_values[0]);
  3405. EXPECT_EQ("bbbbb", text1_values[1]);
  3406. }
  3407. {
  3408. const auto &file1_values = req.form.get_files("multi_file1");
  3409. EXPECT_EQ(2u, file1_values.size());
  3410. auto file1 = file1_values[0];
  3411. EXPECT_EQ(file1.filename, "hello.txt");
  3412. EXPECT_EQ(file1.content_type, "text/plain");
  3413. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3414. auto file2 = file1_values[1];
  3415. EXPECT_EQ(file2.filename, "world.json");
  3416. EXPECT_EQ(file2.content_type, "application/json");
  3417. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3418. }
  3419. })
  3420. .Post("/empty",
  3421. [&](const Request &req, Response &res) {
  3422. EXPECT_EQ(req.body, "");
  3423. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3424. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3425. res.set_content("empty", "text/plain");
  3426. })
  3427. .Post("/empty-no-content-type",
  3428. [&](const Request &req, Response &res) {
  3429. EXPECT_EQ(req.body, "");
  3430. EXPECT_FALSE(req.has_header("Content-Type"));
  3431. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3432. res.set_content("empty-no-content-type", "text/plain");
  3433. })
  3434. .Post("/path-only",
  3435. [&](const Request &req, Response &res) {
  3436. EXPECT_EQ(req.body, "");
  3437. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3438. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3439. res.set_content("path-only", "text/plain");
  3440. })
  3441. .Post("/path-headers-only",
  3442. [&](const Request &req, Response &res) {
  3443. EXPECT_EQ(req.body, "");
  3444. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3445. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3446. EXPECT_EQ("world", req.get_header_value("hello"));
  3447. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3448. res.set_content("path-headers-only", "text/plain");
  3449. })
  3450. .Post("/post-large",
  3451. [&](const Request &req, Response &res) {
  3452. EXPECT_EQ(req.body, LARGE_DATA);
  3453. res.set_content(req.body, "text/plain");
  3454. })
  3455. .Post("/post-loopback",
  3456. [&](const Request &, Response &res,
  3457. ContentReader const &content_reader) {
  3458. std::string body;
  3459. content_reader([&](const char *data, size_t data_length) {
  3460. body.append(data, data_length);
  3461. return true;
  3462. });
  3463. res.set_content(body, "text/plain");
  3464. })
  3465. .Put("/put-loopback",
  3466. [&](const Request &, Response &res,
  3467. ContentReader const &content_reader) {
  3468. std::string body;
  3469. content_reader([&](const char *data, size_t data_length) {
  3470. body.append(data, data_length);
  3471. return true;
  3472. });
  3473. res.set_content(body, "text/plain");
  3474. })
  3475. .Patch("/patch-loopback",
  3476. [&](const Request &, Response &res,
  3477. ContentReader const &content_reader) {
  3478. std::string body;
  3479. content_reader([&](const char *data, size_t data_length) {
  3480. body.append(data, data_length);
  3481. return true;
  3482. });
  3483. res.set_content(body, "text/plain");
  3484. })
  3485. .Put("/empty-no-content-type",
  3486. [&](const Request &req, Response &res) {
  3487. EXPECT_EQ(req.body, "");
  3488. EXPECT_FALSE(req.has_header("Content-Type"));
  3489. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3490. res.set_content("empty-no-content-type", "text/plain");
  3491. })
  3492. .Put("/put",
  3493. [&](const Request &req, Response &res) {
  3494. EXPECT_EQ(req.body, "PUT");
  3495. res.set_content(req.body, "text/plain");
  3496. })
  3497. .Put("/put-large",
  3498. [&](const Request &req, Response &res) {
  3499. EXPECT_EQ(req.body, LARGE_DATA);
  3500. res.set_content(req.body, "text/plain");
  3501. })
  3502. .Patch("/patch",
  3503. [&](const Request &req, Response &res) {
  3504. EXPECT_EQ(req.body, "PATCH");
  3505. res.set_content(req.body, "text/plain");
  3506. })
  3507. .Delete("/delete",
  3508. [&](const Request & /*req*/, Response &res) {
  3509. res.set_content("DELETE", "text/plain");
  3510. })
  3511. .Delete("/delete-body",
  3512. [&](const Request &req, Response &res) {
  3513. EXPECT_EQ(req.body, "content");
  3514. res.set_content(req.body, "text/plain");
  3515. })
  3516. .Options(R"(\*)",
  3517. [&](const Request & /*req*/, Response &res) {
  3518. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3519. })
  3520. .Get("/request-target",
  3521. [&](const Request &req, Response & /*res*/) {
  3522. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3523. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3524. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3525. })
  3526. .Get("/long-query-value",
  3527. [&](const Request &req, Response & /*res*/) {
  3528. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3529. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3530. })
  3531. .Get("/too-long-query-value",
  3532. [&](const Request &req, Response & /*res*/) {
  3533. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3534. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3535. })
  3536. .Get("/array-param",
  3537. [&](const Request &req, Response & /*res*/) {
  3538. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3539. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3540. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3541. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3542. })
  3543. .Get("/array-param-values",
  3544. [&](const Request &req, Response & /*res*/) {
  3545. auto values = req.get_param_values("array");
  3546. EXPECT_EQ(3u, values.size());
  3547. EXPECT_EQ("value1", values[0]);
  3548. EXPECT_EQ("value2", values[1]);
  3549. EXPECT_EQ("value3", values[2]);
  3550. auto empty = req.get_param_values("nonexistent");
  3551. EXPECT_TRUE(empty.empty());
  3552. })
  3553. .Post("/validate-no-multiple-headers",
  3554. [&](const Request &req, Response & /*res*/) {
  3555. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3556. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3557. })
  3558. .Post("/content_receiver",
  3559. [&](const Request &req, Response &res,
  3560. const ContentReader &content_reader) {
  3561. if (req.is_multipart_form_data()) {
  3562. std::vector<FormData> items;
  3563. content_reader(
  3564. [&](const FormData &file) {
  3565. items.push_back(file);
  3566. return true;
  3567. },
  3568. [&](const char *data, size_t data_length) {
  3569. items.back().content.append(data, data_length);
  3570. return true;
  3571. });
  3572. EXPECT_EQ(5u, items.size());
  3573. {
  3574. const auto &file = get_file_value(items, "text1");
  3575. EXPECT_TRUE(file.filename.empty());
  3576. EXPECT_EQ("text default", file.content);
  3577. }
  3578. {
  3579. const auto &file = get_file_value(items, "text2");
  3580. EXPECT_TRUE(file.filename.empty());
  3581. EXPECT_EQ("aωb", file.content);
  3582. }
  3583. {
  3584. const auto &file = get_file_value(items, "file1");
  3585. EXPECT_EQ("hello.txt", file.filename);
  3586. EXPECT_EQ("text/plain", file.content_type);
  3587. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3588. }
  3589. {
  3590. const auto &file = get_file_value(items, "file2");
  3591. EXPECT_EQ("world.json", file.filename);
  3592. EXPECT_EQ("application/json", file.content_type);
  3593. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3594. }
  3595. {
  3596. const auto &file = get_file_value(items, "file3");
  3597. EXPECT_TRUE(file.filename.empty());
  3598. EXPECT_EQ("application/octet-stream", file.content_type);
  3599. EXPECT_EQ(0u, file.content.size());
  3600. }
  3601. } else {
  3602. std::string body;
  3603. content_reader([&](const char *data, size_t data_length) {
  3604. EXPECT_EQ(7U, data_length);
  3605. body.append(data, data_length);
  3606. return true;
  3607. });
  3608. EXPECT_EQ(body, "content");
  3609. res.set_content(body, "text/plain");
  3610. }
  3611. })
  3612. .Put("/content_receiver",
  3613. [&](const Request & /*req*/, Response &res,
  3614. const ContentReader &content_reader) {
  3615. std::string body;
  3616. content_reader([&](const char *data, size_t data_length) {
  3617. body.append(data, data_length);
  3618. return true;
  3619. });
  3620. EXPECT_EQ(body, "content");
  3621. res.set_content(body, "text/plain");
  3622. })
  3623. .Patch("/content_receiver",
  3624. [&](const Request & /*req*/, Response &res,
  3625. const ContentReader &content_reader) {
  3626. std::string body;
  3627. content_reader([&](const char *data, size_t data_length) {
  3628. body.append(data, data_length);
  3629. return true;
  3630. });
  3631. EXPECT_EQ(body, "content");
  3632. res.set_content(body, "text/plain");
  3633. })
  3634. .Post("/query-string-and-body",
  3635. [&](const Request &req, Response & /*res*/) {
  3636. ASSERT_TRUE(req.has_param("key"));
  3637. EXPECT_EQ(req.get_param_value("key"), "value");
  3638. EXPECT_EQ(req.body, "content");
  3639. })
  3640. .Get("/last-request",
  3641. [&](const Request &req, Response & /*res*/) {
  3642. EXPECT_EQ("close", req.get_header_value("Connection"));
  3643. })
  3644. .Get(R"(/redirect/(\d+))",
  3645. [&](const Request &req, Response &res) {
  3646. auto num = std::stoi(req.matches[1]) + 1;
  3647. std::string url = "/redirect/" + std::to_string(num);
  3648. res.set_redirect(url);
  3649. })
  3650. .Post("/binary",
  3651. [&](const Request &req, Response &res) {
  3652. EXPECT_EQ(4U, req.body.size());
  3653. EXPECT_EQ("application/octet-stream",
  3654. req.get_header_value("Content-Type"));
  3655. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3656. res.set_content(req.body, "application/octet-stream");
  3657. })
  3658. .Put("/binary",
  3659. [&](const Request &req, Response &res) {
  3660. EXPECT_EQ(4U, req.body.size());
  3661. EXPECT_EQ("application/octet-stream",
  3662. req.get_header_value("Content-Type"));
  3663. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3664. res.set_content(req.body, "application/octet-stream");
  3665. })
  3666. .Patch("/binary",
  3667. [&](const Request &req, Response &res) {
  3668. EXPECT_EQ(4U, req.body.size());
  3669. EXPECT_EQ("application/octet-stream",
  3670. req.get_header_value("Content-Type"));
  3671. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3672. res.set_content(req.body, "application/octet-stream");
  3673. })
  3674. .Delete("/binary",
  3675. [&](const Request &req, Response &res) {
  3676. EXPECT_EQ(4U, req.body.size());
  3677. EXPECT_EQ("application/octet-stream",
  3678. req.get_header_value("Content-Type"));
  3679. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3680. res.set_content(req.body, "application/octet-stream");
  3681. })
  3682. .Get("/issue1772",
  3683. [&](const Request & /*req*/, Response &res) {
  3684. res.status = 401;
  3685. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3686. })
  3687. .Delete("/issue609",
  3688. [](const httplib::Request &, httplib::Response &res,
  3689. const httplib::ContentReader &) {
  3690. res.set_content("ok", "text/plain");
  3691. })
  3692. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3693. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3694. .Get("/compress",
  3695. [&](const Request & /*req*/, Response &res) {
  3696. res.set_content(
  3697. "12345678901234567890123456789012345678901234567890123456789"
  3698. "01234567890123456789012345678901234567890",
  3699. "text/plain");
  3700. })
  3701. .Get("/compress-with-charset",
  3702. [&](const Request & /*req*/, Response &res) {
  3703. res.set_content(
  3704. "12345678901234567890123456789012345678901234567890123456789"
  3705. "01234567890123456789012345678901234567890",
  3706. "application/json; charset=utf-8");
  3707. })
  3708. .Get("/nocompress",
  3709. [&](const Request & /*req*/, Response &res) {
  3710. res.set_content(
  3711. "12345678901234567890123456789012345678901234567890123456789"
  3712. "01234567890123456789012345678901234567890",
  3713. "application/octet-stream");
  3714. })
  3715. .Post("/compress-multipart",
  3716. [&](const Request &req, Response & /*res*/) {
  3717. EXPECT_EQ(2u, req.form.fields.size());
  3718. ASSERT_TRUE(!req.form.has_field("???"));
  3719. {
  3720. const auto &text = req.form.get_field("key1");
  3721. EXPECT_EQ("test", text);
  3722. }
  3723. {
  3724. const auto &text = req.form.get_field("key2");
  3725. EXPECT_EQ("--abcdefg123", text);
  3726. }
  3727. })
  3728. #endif
  3729. ;
  3730. persons_["john"] = "programmer";
  3731. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3732. svr_.wait_until_ready();
  3733. }
  3734. virtual void TearDown() {
  3735. svr_.stop();
  3736. if (!request_threads_.empty()) {
  3737. std::this_thread::sleep_for(std::chrono::seconds(1));
  3738. for (auto &t : request_threads_) {
  3739. t.join();
  3740. }
  3741. }
  3742. t_.join();
  3743. }
  3744. map<string, string> persons_;
  3745. #ifdef CPPHTTPLIB_SSL_ENABLED
  3746. SSLClient cli_;
  3747. SSLServer svr_;
  3748. #else
  3749. Client cli_;
  3750. Server svr_;
  3751. #endif
  3752. thread t_;
  3753. std::vector<thread> request_threads_;
  3754. };
  3755. TEST_F(ServerTest, GetMethod200) {
  3756. auto res = cli_.Get("/hi");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ("HTTP/1.1", res->version);
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("OK", res->reason);
  3761. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3762. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3763. EXPECT_EQ("Hello World!", res->body);
  3764. }
  3765. TEST_F(ServerTest, GetEmptyFile) {
  3766. auto res = cli_.Get("/empty_file");
  3767. ASSERT_TRUE(res);
  3768. EXPECT_EQ(StatusCode::OK_200, res->status);
  3769. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3770. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3771. EXPECT_EQ("", res->body);
  3772. }
  3773. TEST_F(ServerTest, GetFileContent) {
  3774. auto res = cli_.Get("/file_content");
  3775. ASSERT_TRUE(res);
  3776. EXPECT_EQ(StatusCode::OK_200, res->status);
  3777. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3778. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3779. EXPECT_EQ("test.html", res->body);
  3780. }
  3781. TEST_F(ServerTest, GetFileContentWithRange) {
  3782. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3785. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3786. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3787. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3788. EXPECT_EQ("est", res->body);
  3789. }
  3790. TEST_F(ServerTest, GetFileContentWithContentType) {
  3791. auto res = cli_.Get("/file_content_with_content_type");
  3792. ASSERT_TRUE(res);
  3793. EXPECT_EQ(StatusCode::OK_200, res->status);
  3794. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3795. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3796. EXPECT_EQ("file\n", res->body);
  3797. }
  3798. TEST_F(ServerTest, GetInvalidFileContent) {
  3799. auto res = cli_.Get("/invalid_file_content");
  3800. ASSERT_TRUE(res);
  3801. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3802. }
  3803. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3804. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3805. ASSERT_TRUE(res);
  3806. EXPECT_EQ("HTTP/1.1", res->version);
  3807. EXPECT_EQ(StatusCode::OK_200, res->status);
  3808. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3809. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3810. EXPECT_EQ("Hello World!", res->body);
  3811. }
  3812. TEST_F(ServerTest, GetMethod302) {
  3813. auto res = cli_.Get("/");
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::Found_302, res->status);
  3816. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3817. }
  3818. TEST_F(ServerTest, GetMethod302Redirect) {
  3819. cli_.set_follow_location(true);
  3820. auto res = cli_.Get("/");
  3821. ASSERT_TRUE(res);
  3822. EXPECT_EQ(StatusCode::OK_200, res->status);
  3823. EXPECT_EQ("Hello World!", res->body);
  3824. EXPECT_EQ("/hi", res->location);
  3825. }
  3826. TEST_F(ServerTest, GetMethod404) {
  3827. auto res = cli_.Get("/invalid");
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3830. }
  3831. TEST_F(ServerTest, HeadMethod200) {
  3832. auto res = cli_.Head("/hi");
  3833. ASSERT_TRUE(res);
  3834. EXPECT_EQ(StatusCode::OK_200, res->status);
  3835. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3836. EXPECT_TRUE(res->body.empty());
  3837. }
  3838. TEST_F(ServerTest, HeadMethod200Static) {
  3839. auto res = cli_.Head("/mount/dir/index.html");
  3840. ASSERT_TRUE(res);
  3841. EXPECT_EQ(StatusCode::OK_200, res->status);
  3842. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3843. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3844. EXPECT_TRUE(res->body.empty());
  3845. }
  3846. TEST_F(ServerTest, HeadMethod404) {
  3847. auto res = cli_.Head("/invalid");
  3848. ASSERT_TRUE(res);
  3849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3850. EXPECT_TRUE(res->body.empty());
  3851. }
  3852. TEST_F(ServerTest, GetMethodPersonJohn) {
  3853. auto res = cli_.Get("/person/john");
  3854. ASSERT_TRUE(res);
  3855. EXPECT_EQ(StatusCode::OK_200, res->status);
  3856. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3857. EXPECT_EQ("programmer", res->body);
  3858. }
  3859. TEST_F(ServerTest, PostMethod1) {
  3860. auto res = cli_.Get("/person/john1");
  3861. ASSERT_TRUE(res);
  3862. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3863. res = cli_.Post("/person", "name=john1&note=coder",
  3864. "application/x-www-form-urlencoded");
  3865. ASSERT_TRUE(res);
  3866. ASSERT_EQ(StatusCode::OK_200, res->status);
  3867. res = cli_.Get("/person/john1");
  3868. ASSERT_TRUE(res);
  3869. ASSERT_EQ(StatusCode::OK_200, res->status);
  3870. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3871. ASSERT_EQ("coder", res->body);
  3872. }
  3873. TEST_F(ServerTest, PostMethod2) {
  3874. auto res = cli_.Get("/person/john2");
  3875. ASSERT_TRUE(res);
  3876. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3877. Params params;
  3878. params.emplace("name", "john2");
  3879. params.emplace("note", "coder");
  3880. res = cli_.Post("/person", params);
  3881. ASSERT_TRUE(res);
  3882. ASSERT_EQ(StatusCode::OK_200, res->status);
  3883. res = cli_.Get("/person/john2");
  3884. ASSERT_TRUE(res);
  3885. ASSERT_EQ(StatusCode::OK_200, res->status);
  3886. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3887. ASSERT_EQ("coder", res->body);
  3888. }
  3889. TEST_F(ServerTest, PutMethod3) {
  3890. auto res = cli_.Get("/person/john3");
  3891. ASSERT_TRUE(res);
  3892. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3893. Params params;
  3894. params.emplace("name", "john3");
  3895. params.emplace("note", "coder");
  3896. res = cli_.Put("/person", params);
  3897. ASSERT_TRUE(res);
  3898. ASSERT_EQ(StatusCode::OK_200, res->status);
  3899. res = cli_.Get("/person/john3");
  3900. ASSERT_TRUE(res);
  3901. ASSERT_EQ(StatusCode::OK_200, res->status);
  3902. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3903. ASSERT_EQ("coder", res->body);
  3904. }
  3905. TEST_F(ServerTest, DeleteMethod1) {
  3906. auto res = cli_.Get("/person/john4");
  3907. ASSERT_TRUE(res);
  3908. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3909. Params params;
  3910. params.emplace("name", "john4");
  3911. params.emplace("note", "coder");
  3912. res = cli_.Post("/person", params);
  3913. ASSERT_TRUE(res);
  3914. ASSERT_EQ(StatusCode::OK_200, res->status);
  3915. res = cli_.Get("/person/john4");
  3916. ASSERT_TRUE(res);
  3917. ASSERT_EQ(StatusCode::OK_200, res->status);
  3918. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3919. ASSERT_EQ("coder", res->body);
  3920. Params delete_params;
  3921. delete_params.emplace("name", "john4");
  3922. res = cli_.Delete("/person", delete_params);
  3923. ASSERT_TRUE(res);
  3924. ASSERT_EQ(StatusCode::OK_200, res->status);
  3925. ASSERT_EQ("DELETED", res->body);
  3926. res = cli_.Get("/person/john4");
  3927. ASSERT_TRUE(res);
  3928. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3929. }
  3930. TEST_F(ServerTest, DeleteMethod2) {
  3931. auto res = cli_.Get("/person/john5");
  3932. ASSERT_TRUE(res);
  3933. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3934. Params params;
  3935. params.emplace("name", "john5");
  3936. params.emplace("note", "developer");
  3937. res = cli_.Post("/person", params);
  3938. ASSERT_TRUE(res);
  3939. ASSERT_EQ(StatusCode::OK_200, res->status);
  3940. res = cli_.Get("/person/john5");
  3941. ASSERT_TRUE(res);
  3942. ASSERT_EQ(StatusCode::OK_200, res->status);
  3943. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3944. ASSERT_EQ("developer", res->body);
  3945. Params delete_params;
  3946. delete_params.emplace("name", "john5");
  3947. Headers headers;
  3948. headers.emplace("Custom-Header", "test-value");
  3949. res = cli_.Delete("/person", headers, delete_params);
  3950. ASSERT_TRUE(res);
  3951. ASSERT_EQ(StatusCode::OK_200, res->status);
  3952. ASSERT_EQ("DELETED", res->body);
  3953. res = cli_.Get("/person/john5");
  3954. ASSERT_TRUE(res);
  3955. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3956. }
  3957. TEST_F(ServerTest, DeleteMethod3) {
  3958. auto res = cli_.Get("/person/john6");
  3959. ASSERT_TRUE(res);
  3960. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3961. Params params;
  3962. params.emplace("name", "john6");
  3963. params.emplace("note", "tester");
  3964. res = cli_.Post("/person", params);
  3965. ASSERT_TRUE(res);
  3966. ASSERT_EQ(StatusCode::OK_200, res->status);
  3967. res = cli_.Get("/person/john6");
  3968. ASSERT_TRUE(res);
  3969. ASSERT_EQ(StatusCode::OK_200, res->status);
  3970. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3971. ASSERT_EQ("tester", res->body);
  3972. Params delete_params;
  3973. delete_params.emplace("name", "john6");
  3974. Headers headers;
  3975. headers.emplace("Custom-Header", "test-value");
  3976. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3977. ASSERT_TRUE(res);
  3978. ASSERT_EQ(StatusCode::OK_200, res->status);
  3979. ASSERT_EQ("DELETED", res->body);
  3980. res = cli_.Get("/person/john6");
  3981. ASSERT_TRUE(res);
  3982. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3983. }
  3984. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3985. Params params;
  3986. params.emplace("json", JSON_DATA);
  3987. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3988. ASSERT_TRUE(res);
  3989. ASSERT_EQ(StatusCode::OK_200, res->status);
  3990. ASSERT_EQ(JSON_DATA, res->body);
  3991. }
  3992. TEST_F(ServerTest, PostEmptyContent) {
  3993. auto res = cli_.Post("/empty", "", "text/plain");
  3994. ASSERT_TRUE(res);
  3995. ASSERT_EQ(StatusCode::OK_200, res->status);
  3996. ASSERT_EQ("empty", res->body);
  3997. }
  3998. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3999. auto res = cli_.Post("/empty-no-content-type");
  4000. ASSERT_TRUE(res);
  4001. ASSERT_EQ(StatusCode::OK_200, res->status);
  4002. ASSERT_EQ("empty-no-content-type", res->body);
  4003. }
  4004. TEST_F(ServerTest, PostPathOnly) {
  4005. auto res = cli_.Post("/path-only");
  4006. ASSERT_TRUE(res);
  4007. ASSERT_EQ(StatusCode::OK_200, res->status);
  4008. ASSERT_EQ("path-only", res->body);
  4009. }
  4010. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4011. auto res = cli_.Post("/path-headers-only",
  4012. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4013. ASSERT_TRUE(res);
  4014. ASSERT_EQ(StatusCode::OK_200, res->status);
  4015. ASSERT_EQ("path-headers-only", res->body);
  4016. }
  4017. TEST_F(ServerTest, PostLarge) {
  4018. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4019. ASSERT_TRUE(res);
  4020. ASSERT_EQ(StatusCode::OK_200, res->status);
  4021. EXPECT_EQ(LARGE_DATA, res->body);
  4022. }
  4023. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4024. auto res = cli_.Put("/empty-no-content-type");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::OK_200, res->status);
  4027. ASSERT_EQ("empty-no-content-type", res->body);
  4028. }
  4029. TEST_F(ServerTest, GetMethodDir) {
  4030. auto res = cli_.Get("/dir/");
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::OK_200, res->status);
  4033. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4034. auto body = R"(<html>
  4035. <head>
  4036. </head>
  4037. <body>
  4038. <a href="/dir/test.html">Test</a>
  4039. <a href="/hi">hi</a>
  4040. </body>
  4041. </html>
  4042. )";
  4043. EXPECT_EQ(body, res->body);
  4044. }
  4045. TEST_F(ServerTest, GetMethodDirTest) {
  4046. auto res = cli_.Get("/dir/test.html");
  4047. ASSERT_TRUE(res);
  4048. EXPECT_EQ(StatusCode::OK_200, res->status);
  4049. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4050. EXPECT_EQ("test.html", res->body);
  4051. }
  4052. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4053. auto res = cli_.Get("/dir/../dir/test.html");
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::OK_200, res->status);
  4056. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4057. EXPECT_EQ("test.html", res->body);
  4058. }
  4059. TEST_F(ServerTest, GetMethodInvalidPath) {
  4060. auto res = cli_.Get("/dir/../test.html");
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4063. }
  4064. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4065. auto res = cli_.Get("/../www/dir/test.html");
  4066. ASSERT_TRUE(res);
  4067. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4068. }
  4069. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4070. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4071. ASSERT_TRUE(res);
  4072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4073. }
  4074. TEST_F(ServerTest, GetMethodDirMountTest) {
  4075. auto res = cli_.Get("/mount/dir/test.html");
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::OK_200, res->status);
  4078. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4079. EXPECT_EQ("test.html", res->body);
  4080. }
  4081. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4082. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4083. ASSERT_TRUE(res);
  4084. EXPECT_EQ(StatusCode::OK_200, res->status);
  4085. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4086. EXPECT_EQ("test.html", res->body);
  4087. }
  4088. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4089. auto res = cli_.Get("/mount/dir/../test.html");
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4092. }
  4093. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4094. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4097. }
  4098. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4099. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4102. }
  4103. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4104. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4107. }
  4108. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4109. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4110. ASSERT_TRUE(res);
  4111. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4112. }
  4113. TEST_F(ServerTest, PostMethod303) {
  4114. auto res = cli_.Post("/1", "body", "text/plain");
  4115. ASSERT_TRUE(res);
  4116. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4117. EXPECT_EQ("/2", res->get_header_value("Location"));
  4118. }
  4119. TEST_F(ServerTest, PostMethod303Redirect) {
  4120. cli_.set_follow_location(true);
  4121. auto res = cli_.Post("/1", "body", "text/plain");
  4122. ASSERT_TRUE(res);
  4123. EXPECT_EQ(StatusCode::OK_200, res->status);
  4124. EXPECT_EQ("redirected.", res->body);
  4125. EXPECT_EQ("/2", res->location);
  4126. }
  4127. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4128. auto res = cli_.Get("/dir/test.abcde");
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::OK_200, res->status);
  4131. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4132. EXPECT_EQ("abcde", res->body);
  4133. }
  4134. TEST_F(ServerTest, StaticFileRange) {
  4135. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4136. ASSERT_TRUE(res);
  4137. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4138. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4139. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ(true, res->has_header("Content-Range"));
  4141. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4142. EXPECT_EQ(std::string("cd"), res->body);
  4143. }
  4144. TEST_F(ServerTest, StaticFileRanges) {
  4145. auto res =
  4146. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4149. EXPECT_TRUE(
  4150. res->get_header_value("Content-Type")
  4151. .find(
  4152. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4153. 0);
  4154. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4155. }
  4156. TEST_F(ServerTest, StaticFileRangeHead) {
  4157. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4158. ASSERT_TRUE(res);
  4159. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4160. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4161. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4162. EXPECT_EQ(true, res->has_header("Content-Range"));
  4163. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4164. }
  4165. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4166. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4167. ASSERT_TRUE(res);
  4168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4169. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4170. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4171. EXPECT_EQ(true, res->has_header("Content-Range"));
  4172. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4173. res->get_header_value("Content-Range"));
  4174. EXPECT_EQ("LAST\n", res->body);
  4175. }
  4176. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4177. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4178. ASSERT_TRUE(res);
  4179. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4180. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4181. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4182. EXPECT_EQ(true, res->has_header("Content-Range"));
  4183. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4184. }
  4185. TEST_F(ServerTest, StaticFileBigFile) {
  4186. auto res = cli_.Get("/dir/1MB.txt");
  4187. ASSERT_TRUE(res);
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4190. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4191. }
  4192. TEST_F(ServerTest, InvalidBaseDirMount) {
  4193. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4194. }
  4195. TEST_F(ServerTest, Binary) {
  4196. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4197. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4198. "application/octet-stream");
  4199. ASSERT_TRUE(res);
  4200. ASSERT_EQ(StatusCode::OK_200, res->status);
  4201. ASSERT_EQ(4U, res->body.size());
  4202. res = cli_.Put("/binary", binary.data(), binary.size(),
  4203. "application/octet-stream");
  4204. ASSERT_TRUE(res);
  4205. ASSERT_EQ(StatusCode::OK_200, res->status);
  4206. ASSERT_EQ(4U, res->body.size());
  4207. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4208. "application/octet-stream");
  4209. ASSERT_TRUE(res);
  4210. ASSERT_EQ(StatusCode::OK_200, res->status);
  4211. ASSERT_EQ(4U, res->body.size());
  4212. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4213. "application/octet-stream");
  4214. ASSERT_TRUE(res);
  4215. ASSERT_EQ(StatusCode::OK_200, res->status);
  4216. ASSERT_EQ(4U, res->body.size());
  4217. }
  4218. TEST_F(ServerTest, BinaryString) {
  4219. auto binary = std::string("\x00\x01\x02\x03", 4);
  4220. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4221. ASSERT_TRUE(res);
  4222. ASSERT_EQ(StatusCode::OK_200, res->status);
  4223. ASSERT_EQ(4U, res->body.size());
  4224. res = cli_.Put("/binary", binary, "application/octet-stream");
  4225. ASSERT_TRUE(res);
  4226. ASSERT_EQ(StatusCode::OK_200, res->status);
  4227. ASSERT_EQ(4U, res->body.size());
  4228. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4229. ASSERT_TRUE(res);
  4230. ASSERT_EQ(StatusCode::OK_200, res->status);
  4231. ASSERT_EQ(4U, res->body.size());
  4232. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4233. ASSERT_TRUE(res);
  4234. ASSERT_EQ(StatusCode::OK_200, res->status);
  4235. ASSERT_EQ(4U, res->body.size());
  4236. }
  4237. TEST_F(ServerTest, EmptyRequest) {
  4238. auto res = cli_.Get("");
  4239. ASSERT_TRUE(!res);
  4240. EXPECT_EQ(Error::Connection, res.error());
  4241. }
  4242. TEST_F(ServerTest, LongRequest) {
  4243. std::string request;
  4244. for (size_t i = 0; i < 545; i++) {
  4245. request += "/TooLongRequest";
  4246. }
  4247. request += "OK";
  4248. auto res = cli_.Get(request.c_str());
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4251. }
  4252. TEST_F(ServerTest, TooLongRequest) {
  4253. std::string request;
  4254. for (size_t i = 0; i < 546; i++) {
  4255. request += "/TooLongRequest";
  4256. }
  4257. request += "_NG";
  4258. auto start = std::chrono::high_resolution_clock::now();
  4259. cli_.set_keep_alive(true);
  4260. auto res = cli_.Get(request.c_str());
  4261. auto end = std::chrono::high_resolution_clock::now();
  4262. auto elapsed =
  4263. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4264. .count();
  4265. ASSERT_TRUE(res);
  4266. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4267. EXPECT_LE(elapsed, 1000);
  4268. EXPECT_EQ("close", res->get_header_value("Connection"));
  4269. EXPECT_FALSE(cli_.is_socket_open());
  4270. }
  4271. TEST_F(ServerTest, AlmostTooLongRequest) {
  4272. // test for #2046 - URI length check shouldn't include other content on req
  4273. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4274. // leading /, space, HTTP/1.1)
  4275. std::string request =
  4276. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4277. auto res = cli_.Get(request.c_str());
  4278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4279. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4280. }
  4281. TEST_F(ServerTest, LongHeader) {
  4282. Request req;
  4283. req.method = "GET";
  4284. req.path = "/hi";
  4285. std::string host_and_port;
  4286. host_and_port += HOST;
  4287. host_and_port += ":";
  4288. host_and_port += std::to_string(PORT);
  4289. req.headers.emplace("Host", host_and_port.c_str());
  4290. req.headers.emplace("Accept", "*/*");
  4291. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4292. req.headers.emplace(
  4293. "Header-Name",
  4294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4307. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4308. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4309. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4322. "@@@@@@@@@@@@@@@@");
  4323. auto res = std::make_shared<Response>();
  4324. auto error = Error::Success;
  4325. auto ret = cli_.send(req, *res, error);
  4326. ASSERT_TRUE(ret);
  4327. EXPECT_EQ(StatusCode::OK_200, res->status);
  4328. }
  4329. TEST_F(ServerTest, LongQueryValue) {
  4330. auto start = std::chrono::high_resolution_clock::now();
  4331. cli_.set_keep_alive(true);
  4332. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4333. auto end = std::chrono::high_resolution_clock::now();
  4334. auto elapsed =
  4335. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4336. .count();
  4337. ASSERT_TRUE(res);
  4338. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4339. EXPECT_LE(elapsed, 1000);
  4340. EXPECT_EQ("close", res->get_header_value("Connection"));
  4341. EXPECT_FALSE(cli_.is_socket_open());
  4342. }
  4343. TEST_F(ServerTest, TooLongQueryValue) {
  4344. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4345. ASSERT_FALSE(res);
  4346. EXPECT_EQ(Error::Read, res.error());
  4347. }
  4348. TEST_F(ServerTest, TooLongHeader) {
  4349. Request req;
  4350. req.method = "GET";
  4351. req.path = "/hi";
  4352. std::string host_and_port;
  4353. host_and_port += HOST;
  4354. host_and_port += ":";
  4355. host_and_port += std::to_string(PORT);
  4356. req.headers.emplace("Host", host_and_port.c_str());
  4357. req.headers.emplace("Accept", "*/*");
  4358. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4359. req.headers.emplace(
  4360. "Header-Name",
  4361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4374. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4382. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4383. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4385. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4386. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4387. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4388. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4389. "@@@@@@@@@@@@@@@@@");
  4390. auto res = std::make_shared<Response>();
  4391. auto error = Error::Success;
  4392. auto ret = cli_.send(req, *res, error);
  4393. ASSERT_TRUE(ret);
  4394. EXPECT_EQ(StatusCode::OK_200, res->status);
  4395. }
  4396. TEST_F(ServerTest, HeaderCountAtLimit) {
  4397. // Test with headers just under the 100 limit
  4398. httplib::Headers headers;
  4399. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4400. // This should keep us just under the 100 header limit
  4401. for (int i = 0; i < 95; i++) {
  4402. std::string name = "X-Test-Header-" + std::to_string(i);
  4403. std::string value = "value" + std::to_string(i);
  4404. headers.emplace(name, value);
  4405. }
  4406. // This should work fine as we're under the limit
  4407. auto res = cli_.Get("/hi", headers);
  4408. EXPECT_TRUE(res);
  4409. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4410. }
  4411. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4412. // Test with many headers to exceed the 100 limit
  4413. httplib::Headers headers;
  4414. // Add 150 headers to definitely exceed the 100 limit
  4415. for (int i = 0; i < 150; i++) {
  4416. std::string name = "X-Test-Header-" + std::to_string(i);
  4417. std::string value = "value" + std::to_string(i);
  4418. headers.emplace(name, value);
  4419. }
  4420. // This should fail due to exceeding header count limit
  4421. cli_.set_keep_alive(true);
  4422. auto res = cli_.Get("/hi", headers);
  4423. // The server should respond with 400 Bad Request
  4424. ASSERT_TRUE(res);
  4425. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4426. EXPECT_EQ("close", res->get_header_value("Connection"));
  4427. EXPECT_FALSE(cli_.is_socket_open());
  4428. }
  4429. TEST_F(ServerTest, PercentEncoding) {
  4430. auto res = cli_.Get("/e%6edwith%");
  4431. ASSERT_TRUE(res);
  4432. EXPECT_EQ(StatusCode::OK_200, res->status);
  4433. }
  4434. TEST_F(ServerTest, PercentEncodingUnicode) {
  4435. auto res = cli_.Get("/e%u006edwith%");
  4436. ASSERT_TRUE(res);
  4437. EXPECT_EQ(StatusCode::OK_200, res->status);
  4438. }
  4439. TEST_F(ServerTest, InvalidPercentEncoding) {
  4440. auto res = cli_.Get("/%endwith%");
  4441. ASSERT_TRUE(res);
  4442. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4443. }
  4444. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4445. auto res = cli_.Get("/%uendwith%");
  4446. ASSERT_TRUE(res);
  4447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4448. }
  4449. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4450. auto res = cli_.Get("/hello?aaa=bbb%");
  4451. ASSERT_TRUE(res);
  4452. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4453. }
  4454. TEST_F(ServerTest, PlusSignEncoding) {
  4455. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4456. ASSERT_TRUE(res);
  4457. EXPECT_EQ(StatusCode::OK_200, res->status);
  4458. EXPECT_EQ("a +b", res->body);
  4459. }
  4460. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4461. // This test simulates a potential DoS attack using many headers
  4462. // to verify our security fix prevents memory exhaustion
  4463. httplib::Headers attack_headers;
  4464. // Attempt to add many headers like an attacker would (200 headers to far
  4465. // exceed limit)
  4466. for (int i = 0; i < 200; i++) {
  4467. std::string name = "X-Attack-Header-" + std::to_string(i);
  4468. std::string value = "attack_payload_" + std::to_string(i);
  4469. attack_headers.emplace(name, value);
  4470. }
  4471. // Try to POST with excessive headers
  4472. cli_.set_keep_alive(true);
  4473. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4474. // Should either fail or return 400 Bad Request due to security limit
  4475. if (res) {
  4476. // If we get a response, it should be 400 Bad Request
  4477. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4478. EXPECT_EQ("close", res->get_header_value("Connection"));
  4479. }
  4480. EXPECT_FALSE(cli_.is_socket_open());
  4481. }
  4482. TEST_F(ServerTest, MultipartFormData) {
  4483. UploadFormDataItems items = {
  4484. {"text1", "text default", "", ""},
  4485. {"text2", "aωb", "", ""},
  4486. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4487. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4488. {"file3", "", "", "application/octet-stream"},
  4489. {"file4", "", "", " application/json tmp-string "}};
  4490. auto res = cli_.Post("/multipart", items);
  4491. ASSERT_TRUE(res);
  4492. EXPECT_EQ(StatusCode::OK_200, res->status);
  4493. }
  4494. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4495. UploadFormDataItems items = {
  4496. {"text", "default text", "", ""},
  4497. {"multi_text1", "aaaaa", "", ""},
  4498. {"multi_text1", "bbbbb", "", ""},
  4499. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4500. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4501. "application/json"},
  4502. };
  4503. auto res = cli_.Post("/multipart/multi_file_values", items);
  4504. ASSERT_TRUE(res);
  4505. EXPECT_EQ(StatusCode::OK_200, res->status);
  4506. }
  4507. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4508. auto res = cli_.Get("/hi");
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4512. EXPECT_EQ("Hello World!", res->body);
  4513. }
  4514. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4515. Request req;
  4516. req.method = "POST";
  4517. req.path = "/chunked";
  4518. std::string host_and_port;
  4519. host_and_port += HOST;
  4520. host_and_port += ":";
  4521. host_and_port += std::to_string(PORT);
  4522. req.headers.emplace("Host", host_and_port.c_str());
  4523. req.headers.emplace("Accept", "*/*");
  4524. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4525. req.headers.emplace("Content-Type", "text/plain");
  4526. req.headers.emplace("Content-Length", "0");
  4527. req.headers.emplace(
  4528. "Transfer-Encoding",
  4529. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4530. // Client does not chunk, so make a chunked body manually.
  4531. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4532. auto res = std::make_shared<Response>();
  4533. auto error = Error::Success;
  4534. auto ret = cli_.send(req, *res, error);
  4535. ASSERT_TRUE(ret);
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. }
  4538. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4539. // rather than treat them as valid lengths.
  4540. template <typename ClientT>
  4541. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4542. Request req;
  4543. req.method = "POST";
  4544. req.path = "/chunked";
  4545. std::string host_and_port;
  4546. host_and_port += HOST;
  4547. host_and_port += ":";
  4548. host_and_port += std::to_string(PORT);
  4549. req.headers.emplace("Host", host_and_port.c_str());
  4550. req.headers.emplace("Content-Length", "0");
  4551. req.headers.emplace("Transfer-Encoding", "chunked");
  4552. req.body = body;
  4553. auto res = std::make_shared<Response>();
  4554. auto error = Error::Success;
  4555. ASSERT_TRUE(cli.send(req, *res, error));
  4556. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4557. }
  4558. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4559. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4560. }
  4561. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4562. expect_chunked_body_rejected(
  4563. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4564. }
  4565. TEST_F(ServerTest, GetStreamed2) {
  4566. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4567. ASSERT_TRUE(res);
  4568. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4569. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4570. EXPECT_EQ(true, res->has_header("Content-Range"));
  4571. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4572. EXPECT_EQ(std::string("ab"), res->body);
  4573. }
  4574. TEST_F(ServerTest, GetStreamed) {
  4575. auto res = cli_.Get("/streamed");
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4579. EXPECT_EQ(std::string("aaabbb"), res->body);
  4580. }
  4581. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4582. auto res =
  4583. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. EXPECT_EQ(false, res->has_header("Content-Length"));
  4587. EXPECT_EQ(false, res->has_header("Content-Range"));
  4588. EXPECT_EQ(std::string("abcdefg"), res->body);
  4589. }
  4590. TEST_F(ServerTest, GetStreamedWithRange1) {
  4591. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4592. ASSERT_TRUE(res);
  4593. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4594. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4595. EXPECT_EQ(true, res->has_header("Content-Range"));
  4596. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4597. EXPECT_EQ(std::string("def"), res->body);
  4598. }
  4599. TEST_F(ServerTest, GetStreamedWithRange2) {
  4600. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4601. ASSERT_TRUE(res);
  4602. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4603. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4604. EXPECT_EQ(true, res->has_header("Content-Range"));
  4605. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4606. EXPECT_EQ(std::string("bcdefg"), res->body);
  4607. }
  4608. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4609. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4610. ASSERT_TRUE(res);
  4611. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4612. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4613. EXPECT_EQ(true, res->has_header("Content-Range"));
  4614. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4615. EXPECT_EQ(std::string("efg"), res->body);
  4616. }
  4617. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4618. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4619. ASSERT_TRUE(res);
  4620. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4621. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4622. EXPECT_EQ(false, res->has_header("Content-Range"));
  4623. EXPECT_EQ(0U, res->body.size());
  4624. }
  4625. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4626. auto res = cli_.Get("/streamed-with-range",
  4627. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4628. "92233720368547758079223372036854775807"}});
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4631. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4632. EXPECT_EQ(false, res->has_header("Content-Range"));
  4633. EXPECT_EQ(0U, res->body.size());
  4634. }
  4635. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4636. auto res = cli_.Get(
  4637. "/with-range",
  4638. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4639. {"Accept-Encoding", ""}});
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4642. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4643. EXPECT_EQ(true, res->has_header("Content-Range"));
  4644. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4645. EXPECT_EQ(std::string("abcdefg"), res->body);
  4646. }
  4647. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4648. auto res = cli_.Get("/with-range", {
  4649. {"Range", "bytes=0-"},
  4650. {"Accept-Encoding", ""},
  4651. });
  4652. ASSERT_TRUE(res);
  4653. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4654. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4655. EXPECT_EQ(true, res->has_header("Content-Range"));
  4656. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4657. EXPECT_EQ(std::string("abcdefg"), res->body);
  4658. }
  4659. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4660. auto res =
  4661. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4662. ASSERT_TRUE(res);
  4663. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4664. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4665. EXPECT_EQ(false, res->has_header("Content-Range"));
  4666. EXPECT_EQ(267U, res->body.size());
  4667. // Check that both range contents are present
  4668. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4669. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4670. // Check that Content-Range headers are present for both ranges
  4671. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4672. std::string::npos);
  4673. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4674. std::string::npos);
  4675. }
  4676. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4677. Ranges ranges;
  4678. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4679. ranges.emplace_back(0, -1);
  4680. }
  4681. auto res =
  4682. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4683. ASSERT_TRUE(res);
  4684. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4685. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4686. EXPECT_EQ(false, res->has_header("Content-Range"));
  4687. EXPECT_EQ(0U, res->body.size());
  4688. }
  4689. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4690. auto res =
  4691. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4692. ASSERT_TRUE(res);
  4693. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4694. EXPECT_EQ(5U, res->body.size());
  4695. // Check that overlapping ranges are coalesced into a single range
  4696. EXPECT_EQ("bcdef", res->body);
  4697. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4698. // Should be single range, not multipart
  4699. EXPECT_TRUE(res->has_header("Content-Range"));
  4700. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4701. }
  4702. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4703. auto res =
  4704. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4705. ASSERT_TRUE(res);
  4706. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4707. EXPECT_EQ(268U, res->body.size());
  4708. // Check that both range contents are present
  4709. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4710. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4711. // Check that Content-Range headers are present for both ranges
  4712. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4713. std::string::npos);
  4714. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4715. std::string::npos);
  4716. }
  4717. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4718. auto res =
  4719. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4720. ASSERT_TRUE(res);
  4721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4722. EXPECT_EQ(269U, res->body.size());
  4723. // Check that both duplicate range contents are present
  4724. size_t first_abc = res->body.find("abc\r\n");
  4725. EXPECT_TRUE(first_abc != std::string::npos);
  4726. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4727. EXPECT_TRUE(second_abc != std::string::npos);
  4728. // Check that Content-Range headers are present for both ranges
  4729. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4730. EXPECT_TRUE(first_range != std::string::npos);
  4731. size_t second_range =
  4732. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4733. EXPECT_TRUE(second_range != std::string::npos);
  4734. }
  4735. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4736. auto res = cli_.Get("/streamed-with-range?error",
  4737. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4738. ASSERT_TRUE(res);
  4739. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4740. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4741. EXPECT_EQ(false, res->has_header("Content-Range"));
  4742. EXPECT_EQ(0U, res->body.size());
  4743. }
  4744. TEST_F(ServerTest, GetStreamedEndless) {
  4745. uint64_t offset = 0;
  4746. auto res = cli_.Get("/streamed-cancel",
  4747. [&](const char * /*data*/, uint64_t data_length) {
  4748. if (offset < 100) {
  4749. offset += data_length;
  4750. return true;
  4751. }
  4752. return false;
  4753. });
  4754. ASSERT_TRUE(!res);
  4755. EXPECT_EQ(Error::Canceled, res.error());
  4756. }
  4757. TEST_F(ServerTest, ClientStop) {
  4758. std::atomic_size_t count{4};
  4759. std::vector<std::thread> threads;
  4760. for (auto i = count.load(); i != 0; --i) {
  4761. threads.emplace_back([&]() {
  4762. auto res = cli_.Get("/streamed-cancel",
  4763. [&](const char *, uint64_t) { return true; });
  4764. --count;
  4765. ASSERT_TRUE(!res);
  4766. EXPECT_TRUE(res.error() == Error::Canceled ||
  4767. res.error() == Error::Read || res.error() == Error::Write);
  4768. });
  4769. }
  4770. std::this_thread::sleep_for(std::chrono::seconds(2));
  4771. while (count != 0) {
  4772. cli_.stop();
  4773. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4774. }
  4775. for (auto &t : threads) {
  4776. t.join();
  4777. }
  4778. }
  4779. TEST_F(ServerTest, GetWithRange1) {
  4780. auto res = cli_.Get("/with-range", {
  4781. make_range_header({{3, 5}}),
  4782. {"Accept-Encoding", ""},
  4783. });
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4786. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4787. EXPECT_EQ(true, res->has_header("Content-Range"));
  4788. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4789. EXPECT_EQ(std::string("def"), res->body);
  4790. }
  4791. TEST_F(ServerTest, GetWithRange2) {
  4792. auto res = cli_.Get("/with-range", {
  4793. make_range_header({{1, -1}}),
  4794. {"Accept-Encoding", ""},
  4795. });
  4796. ASSERT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4798. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4799. EXPECT_EQ(true, res->has_header("Content-Range"));
  4800. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4801. EXPECT_EQ(std::string("bcdefg"), res->body);
  4802. }
  4803. TEST_F(ServerTest, GetWithRange3) {
  4804. auto res = cli_.Get("/with-range", {
  4805. make_range_header({{0, 0}}),
  4806. {"Accept-Encoding", ""},
  4807. });
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4810. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4811. EXPECT_EQ(true, res->has_header("Content-Range"));
  4812. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4813. EXPECT_EQ(std::string("a"), res->body);
  4814. }
  4815. TEST_F(ServerTest, GetWithRange4) {
  4816. auto res = cli_.Get("/with-range", {
  4817. make_range_header({{-1, 2}}),
  4818. {"Accept-Encoding", ""},
  4819. });
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4822. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4823. EXPECT_EQ(true, res->has_header("Content-Range"));
  4824. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4825. EXPECT_EQ(std::string("fg"), res->body);
  4826. }
  4827. TEST_F(ServerTest, GetWithRange5) {
  4828. auto res = cli_.Get("/with-range", {
  4829. make_range_header({{0, 5}}),
  4830. {"Accept-Encoding", ""},
  4831. });
  4832. ASSERT_TRUE(res);
  4833. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4834. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4835. EXPECT_EQ(true, res->has_header("Content-Range"));
  4836. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4837. EXPECT_EQ(std::string("abcdef"), res->body);
  4838. }
  4839. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4840. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4841. ASSERT_TRUE(res);
  4842. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4843. }
  4844. TEST_F(ServerTest, GetWithRangeMultipart) {
  4845. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4846. ASSERT_TRUE(res);
  4847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4848. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4849. EXPECT_EQ(false, res->has_header("Content-Range"));
  4850. EXPECT_EQ(267U, res->body.size());
  4851. }
  4852. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4853. auto res =
  4854. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4857. }
  4858. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4859. auto res = cli_.Get("/with-range-customized-response",
  4860. {{make_range_header({{1, 2}})}});
  4861. ASSERT_TRUE(res);
  4862. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4863. EXPECT_EQ(true, res->has_header("Content-Length"));
  4864. EXPECT_EQ(false, res->has_header("Content-Range"));
  4865. EXPECT_EQ(JSON_DATA, res->body);
  4866. }
  4867. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4868. auto res = cli_.Get("/with-range-customized-response",
  4869. {{make_range_header({{1, 2}, {4, 5}})}});
  4870. ASSERT_TRUE(res);
  4871. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4872. EXPECT_EQ(true, res->has_header("Content-Length"));
  4873. EXPECT_EQ(false, res->has_header("Content-Range"));
  4874. EXPECT_EQ(JSON_DATA, res->body);
  4875. }
  4876. TEST_F(ServerTest, Issue1772) {
  4877. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4880. }
  4881. TEST_F(ServerTest, Issue609) {
  4882. auto res = cli_.Delete("/issue609");
  4883. ASSERT_TRUE(res);
  4884. EXPECT_EQ(StatusCode::OK_200, res->status);
  4885. EXPECT_EQ(std::string("ok"), res->body);
  4886. }
  4887. TEST_F(ServerTest, GetStreamedChunked) {
  4888. auto res = cli_.Get("/streamed-chunked");
  4889. ASSERT_TRUE(res);
  4890. EXPECT_EQ(StatusCode::OK_200, res->status);
  4891. EXPECT_EQ(std::string("123456789"), res->body);
  4892. }
  4893. TEST_F(ServerTest, GetStreamedChunked2) {
  4894. auto res = cli_.Get("/streamed-chunked2");
  4895. ASSERT_TRUE(res);
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ(std::string("123456789"), res->body);
  4898. }
  4899. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4900. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4901. ASSERT_TRUE(res);
  4902. EXPECT_EQ(StatusCode::OK_200, res->status);
  4903. EXPECT_EQ(std::string("123456789"), res->body);
  4904. EXPECT_TRUE(res->has_header("Trailer"));
  4905. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4906. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4907. // Trailers are now stored separately from headers (security fix)
  4908. EXPECT_EQ(2U, res->trailers.size());
  4909. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4910. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4911. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4912. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4913. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4914. // Verify trailers are NOT in headers (security verification)
  4915. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4916. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4917. }
  4918. TEST_F(ServerTest, LargeChunkedPost) {
  4919. Request req;
  4920. req.method = "POST";
  4921. req.path = "/large-chunked";
  4922. std::string host_and_port;
  4923. host_and_port += HOST;
  4924. host_and_port += ":";
  4925. host_and_port += std::to_string(PORT);
  4926. req.headers.emplace("Host", host_and_port.c_str());
  4927. req.headers.emplace("Accept", "*/*");
  4928. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4929. req.headers.emplace("Content-Type", "text/plain");
  4930. req.headers.emplace("Content-Length", "0");
  4931. req.headers.emplace("Transfer-Encoding", "chunked");
  4932. std::string long_string(30 * 1024u, 'a');
  4933. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4934. // Attempt to make a large enough post to exceed OS buffers, to test that
  4935. // the server handles short reads if the full chunk data isn't available.
  4936. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4937. auto res = std::make_shared<Response>();
  4938. auto error = Error::Success;
  4939. auto ret = cli_.send(req, *res, error);
  4940. ASSERT_TRUE(ret);
  4941. EXPECT_EQ(StatusCode::OK_200, res->status);
  4942. }
  4943. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4944. auto res = cli_.Get("/remote_addr");
  4945. ASSERT_TRUE(res);
  4946. EXPECT_EQ(StatusCode::OK_200, res->status);
  4947. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4948. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4949. }
  4950. TEST_F(ServerTest, GetMethodLocalAddr) {
  4951. auto res = cli_.Get("/local_addr");
  4952. ASSERT_TRUE(res);
  4953. EXPECT_EQ(StatusCode::OK_200, res->status);
  4954. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4955. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4956. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4957. }
  4958. TEST_F(ServerTest, HTTPResponseSplitting) {
  4959. auto res = cli_.Get("/http_response_splitting");
  4960. ASSERT_TRUE(res);
  4961. EXPECT_EQ(StatusCode::OK_200, res->status);
  4962. }
  4963. TEST_F(ServerTest, SlowRequest) {
  4964. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4965. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4966. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4967. }
  4968. #if 0
  4969. TEST_F(ServerTest, SlowPost) {
  4970. char buffer[64 * 1024];
  4971. memset(buffer, 0x42, sizeof(buffer));
  4972. auto res = cli_.Post(
  4973. "/slowpost", 64 * 1024 * 1024,
  4974. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4975. auto ret = sink.write(buffer, sizeof(buffer));
  4976. EXPECT_TRUE(ret);
  4977. return true;
  4978. },
  4979. "text/plain");
  4980. ASSERT_TRUE(res);
  4981. EXPECT_EQ(StatusCode::OK_200, res->status);
  4982. }
  4983. TEST_F(ServerTest, SlowPostFail) {
  4984. char buffer[64 * 1024];
  4985. memset(buffer, 0x42, sizeof(buffer));
  4986. cli_.set_write_timeout(std::chrono::seconds(0));
  4987. auto res = cli_.Post(
  4988. "/slowpost", 64 * 1024 * 1024,
  4989. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4990. sink.write(buffer, sizeof(buffer));
  4991. return true;
  4992. },
  4993. "text/plain");
  4994. ASSERT_TRUE(!res);
  4995. EXPECT_EQ(Error::Write, res.error());
  4996. }
  4997. #endif
  4998. TEST_F(ServerTest, Put) {
  4999. auto res = cli_.Put("/put", "PUT", "text/plain");
  5000. ASSERT_TRUE(res);
  5001. EXPECT_EQ(StatusCode::OK_200, res->status);
  5002. EXPECT_EQ("PUT", res->body);
  5003. }
  5004. TEST_F(ServerTest, PutWithContentProvider) {
  5005. auto res = cli_.Put(
  5006. "/put", 3,
  5007. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5008. sink.os << "PUT";
  5009. return true;
  5010. },
  5011. "text/plain");
  5012. ASSERT_TRUE(res);
  5013. EXPECT_EQ(StatusCode::OK_200, res->status);
  5014. EXPECT_EQ("PUT", res->body);
  5015. }
  5016. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5017. auto res = cli_.Post(
  5018. "/post", 42,
  5019. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5020. return false;
  5021. },
  5022. "text/plain");
  5023. ASSERT_TRUE(!res);
  5024. EXPECT_EQ(Error::Canceled, res.error());
  5025. }
  5026. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5027. auto res = cli_.Put(
  5028. "/put",
  5029. [](size_t /*offset*/, DataSink &sink) {
  5030. sink.os << "PUT";
  5031. sink.done();
  5032. return true;
  5033. },
  5034. "text/plain");
  5035. ASSERT_TRUE(res);
  5036. EXPECT_EQ(StatusCode::OK_200, res->status);
  5037. EXPECT_EQ("PUT", res->body);
  5038. }
  5039. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5040. auto res = cli_.Post(
  5041. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5042. "text/plain");
  5043. ASSERT_TRUE(!res);
  5044. EXPECT_EQ(Error::Canceled, res.error());
  5045. }
  5046. TEST_F(ServerTest, PostLoopBack) {
  5047. std::string body;
  5048. auto res = cli_.Post(
  5049. "/post-loopback", 9,
  5050. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5051. EXPECT_EQ(9u, length);
  5052. sink.write("123", 3);
  5053. sink.write("456", 3);
  5054. sink.write("789", 3);
  5055. return true;
  5056. },
  5057. "text/plain",
  5058. [&body](const char *data, size_t data_length) {
  5059. body.append(data, data_length);
  5060. return true;
  5061. });
  5062. ASSERT_TRUE(res);
  5063. EXPECT_EQ(StatusCode::OK_200, res->status);
  5064. EXPECT_EQ("123456789", body);
  5065. }
  5066. TEST_F(ServerTest, PutLoopBack) {
  5067. std::string body;
  5068. auto res = cli_.Put(
  5069. "/put-loopback", 9,
  5070. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5071. EXPECT_EQ(9u, length);
  5072. sink.write("123", 3);
  5073. sink.write("456", 3);
  5074. sink.write("789", 3);
  5075. return true;
  5076. },
  5077. "text/plain",
  5078. [&body](const char *data, size_t data_length) {
  5079. body.append(data, data_length);
  5080. return true;
  5081. });
  5082. ASSERT_TRUE(res);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. EXPECT_EQ("123456789", body);
  5085. }
  5086. TEST_F(ServerTest, PatchLoopBack) {
  5087. std::string body;
  5088. auto res = cli_.Patch(
  5089. "/patch-loopback", 9,
  5090. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5091. EXPECT_EQ(9u, length);
  5092. sink.write("123", 3);
  5093. sink.write("456", 3);
  5094. sink.write("789", 3);
  5095. return true;
  5096. },
  5097. "text/plain",
  5098. [&body](const char *data, size_t data_length) {
  5099. body.append(data, data_length);
  5100. return true;
  5101. });
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ("123456789", body);
  5105. }
  5106. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5107. std::string body;
  5108. auto res = cli_.Post(
  5109. "/post-loopback",
  5110. [](size_t /*offset*/, DataSink &sink) {
  5111. sink.write("123", 3);
  5112. sink.write("456", 3);
  5113. sink.write("789", 3);
  5114. sink.done();
  5115. return true;
  5116. },
  5117. "text/plain",
  5118. [&body](const char *data, size_t data_length) {
  5119. body.append(data, data_length);
  5120. return true;
  5121. });
  5122. ASSERT_TRUE(res);
  5123. EXPECT_EQ(StatusCode::OK_200, res->status);
  5124. EXPECT_EQ("123456789", body);
  5125. }
  5126. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5127. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5128. cli_.set_compress(true);
  5129. auto res = cli_.Put(
  5130. "/put", 3,
  5131. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5132. sink.os << "PUT";
  5133. return true;
  5134. },
  5135. "text/plain");
  5136. ASSERT_TRUE(res);
  5137. EXPECT_EQ(StatusCode::OK_200, res->status);
  5138. EXPECT_EQ("PUT", res->body);
  5139. }
  5140. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5141. cli_.set_compress(true);
  5142. auto res = cli_.Post(
  5143. "/post", 42,
  5144. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5145. return false;
  5146. },
  5147. "text/plain");
  5148. ASSERT_TRUE(!res);
  5149. EXPECT_EQ(Error::Canceled, res.error());
  5150. }
  5151. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5152. cli_.set_compress(true);
  5153. auto res = cli_.Put(
  5154. "/put",
  5155. [](size_t /*offset*/, DataSink &sink) {
  5156. sink.os << "PUT";
  5157. sink.done();
  5158. return true;
  5159. },
  5160. "text/plain");
  5161. ASSERT_TRUE(res);
  5162. EXPECT_EQ(StatusCode::OK_200, res->status);
  5163. EXPECT_EQ("PUT", res->body);
  5164. }
  5165. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5166. cli_.set_compress(true);
  5167. auto res = cli_.Post(
  5168. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5169. "text/plain");
  5170. ASSERT_TRUE(!res);
  5171. EXPECT_EQ(Error::Canceled, res.error());
  5172. }
  5173. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5174. cli_.set_compress(true);
  5175. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5176. ASSERT_TRUE(res);
  5177. EXPECT_EQ(StatusCode::OK_200, res->status);
  5178. EXPECT_EQ(LARGE_DATA, res->body);
  5179. }
  5180. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5181. #ifdef CPPHTTPLIB_SSL_ENABLED
  5182. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5183. Client cli(s.c_str());
  5184. cli.enable_server_certificate_verification(false);
  5185. #else
  5186. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5187. Client cli(s.c_str());
  5188. #endif
  5189. cli.set_compress(true);
  5190. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5191. ASSERT_TRUE(res);
  5192. EXPECT_EQ(StatusCode::OK_200, res->status);
  5193. EXPECT_EQ(LARGE_DATA, res->body);
  5194. // The compressed size should be less than a 10th of the original. May vary
  5195. // depending on the zlib library.
  5196. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5197. static_cast<uint64_t>(10 * 1024 * 1024));
  5198. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5199. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5200. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5201. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5202. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5203. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5204. #endif
  5205. }
  5206. TEST_F(ServerTest, PutContentWithDeflate) {
  5207. cli_.set_compress(false);
  5208. Headers headers;
  5209. headers.emplace("Content-Encoding", "deflate");
  5210. // PUT in deflate format:
  5211. auto res = cli_.Put("/put", headers,
  5212. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5213. ASSERT_TRUE(res);
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. EXPECT_EQ("PUT", res->body);
  5216. }
  5217. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5218. Headers headers;
  5219. headers.emplace("Accept-Encoding", "gzip, deflate");
  5220. auto res = cli_.Get("/streamed-chunked", headers);
  5221. ASSERT_TRUE(res);
  5222. EXPECT_EQ(StatusCode::OK_200, res->status);
  5223. EXPECT_EQ(std::string("123456789"), res->body);
  5224. }
  5225. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5226. Headers headers;
  5227. headers.emplace("Accept-Encoding", "gzip, deflate");
  5228. auto res = cli_.Get("/streamed-chunked2", headers);
  5229. ASSERT_TRUE(res);
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. EXPECT_EQ(std::string("123456789"), res->body);
  5232. }
  5233. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5234. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(StatusCode::OK_200, res->status);
  5237. }
  5238. TEST(GzipDecompressor, ChunkedDecompression) {
  5239. std::string data;
  5240. for (size_t i = 0; i < 32 * 1024; ++i) {
  5241. data.push_back(static_cast<char>('a' + i % 26));
  5242. }
  5243. std::string compressed_data;
  5244. {
  5245. httplib::detail::gzip_compressor compressor;
  5246. bool result = compressor.compress(
  5247. data.data(), data.size(),
  5248. /*last=*/true,
  5249. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5250. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5251. compressed_data_size);
  5252. return true;
  5253. });
  5254. ASSERT_TRUE(result);
  5255. }
  5256. std::string decompressed_data;
  5257. {
  5258. httplib::detail::gzip_decompressor decompressor;
  5259. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5260. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5261. size_t chunk_size = 130;
  5262. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5263. chunk_begin += chunk_size) {
  5264. size_t current_chunk_size =
  5265. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5266. bool result = decompressor.decompress(
  5267. compressed_data.data() + chunk_begin, current_chunk_size,
  5268. [&](const char *decompressed_data_chunk,
  5269. size_t decompressed_data_chunk_size) {
  5270. decompressed_data.insert(decompressed_data.size(),
  5271. decompressed_data_chunk,
  5272. decompressed_data_chunk_size);
  5273. return true;
  5274. });
  5275. ASSERT_TRUE(result);
  5276. }
  5277. }
  5278. ASSERT_EQ(data, decompressed_data);
  5279. }
  5280. TEST(GzipDecompressor, DeflateDecompression) {
  5281. std::string original_text = "Raw deflate without gzip";
  5282. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5283. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5284. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5285. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5286. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5287. std::string decompressed_data;
  5288. {
  5289. httplib::detail::gzip_decompressor decompressor;
  5290. bool result = decompressor.decompress(
  5291. compressed_data.data(), compressed_data.size(),
  5292. [&](const char *decompressed_data_chunk,
  5293. size_t decompressed_data_chunk_size) {
  5294. decompressed_data.insert(decompressed_data.size(),
  5295. decompressed_data_chunk,
  5296. decompressed_data_chunk_size);
  5297. return true;
  5298. });
  5299. ASSERT_TRUE(result);
  5300. }
  5301. ASSERT_EQ(original_text, decompressed_data);
  5302. }
  5303. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5304. std::string original_text = "Raw deflate without gzip";
  5305. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5306. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5307. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5308. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5309. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5310. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5311. std::string decompressed_data;
  5312. {
  5313. httplib::detail::gzip_decompressor decompressor;
  5314. bool result = decompressor.decompress(
  5315. compressed_data.data(), compressed_data.size(),
  5316. [&](const char *decompressed_data_chunk,
  5317. size_t decompressed_data_chunk_size) {
  5318. decompressed_data.insert(decompressed_data.size(),
  5319. decompressed_data_chunk,
  5320. decompressed_data_chunk_size);
  5321. return true;
  5322. });
  5323. ASSERT_TRUE(result);
  5324. }
  5325. ASSERT_EQ(original_text, decompressed_data);
  5326. }
  5327. #endif
  5328. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5329. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5330. Headers headers;
  5331. headers.emplace("Accept-Encoding", "br");
  5332. auto res = cli_.Get("/streamed-chunked", headers);
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. EXPECT_EQ(std::string("123456789"), res->body);
  5336. }
  5337. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5338. Headers headers;
  5339. headers.emplace("Accept-Encoding", "br");
  5340. auto res = cli_.Get("/streamed-chunked2", headers);
  5341. ASSERT_TRUE(res);
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. EXPECT_EQ(std::string("123456789"), res->body);
  5344. }
  5345. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5346. cli_.set_compress(true);
  5347. auto res = cli_.Put(
  5348. "/put", 3,
  5349. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5350. sink.os << "PUT";
  5351. return true;
  5352. },
  5353. "text/plain");
  5354. ASSERT_TRUE(res);
  5355. EXPECT_EQ(StatusCode::OK_200, res->status);
  5356. EXPECT_EQ("PUT", res->body);
  5357. }
  5358. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5359. cli_.set_compress(true);
  5360. auto res = cli_.Put(
  5361. "/put",
  5362. [](size_t /*offset*/, DataSink &sink) {
  5363. sink.os << "PUT";
  5364. sink.done();
  5365. return true;
  5366. },
  5367. "text/plain");
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. EXPECT_EQ("PUT", res->body);
  5371. }
  5372. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5373. cli_.set_compress(true);
  5374. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5375. ASSERT_TRUE(res);
  5376. EXPECT_EQ(StatusCode::OK_200, res->status);
  5377. EXPECT_EQ(LARGE_DATA, res->body);
  5378. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5379. }
  5380. #endif
  5381. TEST_F(ServerTest, Patch) {
  5382. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5383. ASSERT_TRUE(res);
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. EXPECT_EQ("PATCH", res->body);
  5386. }
  5387. TEST_F(ServerTest, Delete) {
  5388. auto res = cli_.Delete("/delete");
  5389. ASSERT_TRUE(res);
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ("DELETE", res->body);
  5392. }
  5393. TEST_F(ServerTest, DeleteContentReceiver) {
  5394. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ(StatusCode::OK_200, res->status);
  5397. EXPECT_EQ("content", res->body);
  5398. }
  5399. TEST_F(ServerTest, Options) {
  5400. auto res = cli_.Options("*");
  5401. ASSERT_TRUE(res);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5404. EXPECT_TRUE(res->body.empty());
  5405. }
  5406. TEST_F(ServerTest, URL) {
  5407. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5408. ASSERT_TRUE(res);
  5409. EXPECT_EQ(StatusCode::OK_200, res->status);
  5410. }
  5411. TEST_F(ServerTest, ArrayParam) {
  5412. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5413. ASSERT_TRUE(res);
  5414. EXPECT_EQ(StatusCode::OK_200, res->status);
  5415. }
  5416. TEST_F(ServerTest, ArrayParamValues) {
  5417. auto res =
  5418. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5419. ASSERT_TRUE(res);
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. }
  5422. TEST_F(ServerTest, NoMultipleHeaders) {
  5423. Headers headers = {{"Content-Length", "5"}};
  5424. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5425. "text/plain");
  5426. ASSERT_TRUE(res);
  5427. EXPECT_EQ(StatusCode::OK_200, res->status);
  5428. }
  5429. TEST_F(ServerTest, PostContentReceiver) {
  5430. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5431. ASSERT_TRUE(res);
  5432. ASSERT_EQ(StatusCode::OK_200, res->status);
  5433. ASSERT_EQ("content", res->body);
  5434. }
  5435. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5436. UploadFormDataItems items = {
  5437. {"text1", "text default", "", ""},
  5438. {"text2", "aωb", "", ""},
  5439. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5440. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5441. {"file3", "", "", "application/octet-stream"},
  5442. };
  5443. auto res = cli_.Post("/content_receiver", items);
  5444. ASSERT_TRUE(res);
  5445. EXPECT_EQ(StatusCode::OK_200, res->status);
  5446. }
  5447. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5448. UploadFormDataItems items = {
  5449. {"text1", "text default", "", ""},
  5450. {"text2", "aωb", "", ""},
  5451. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5452. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5453. {"file3", "", "", "application/octet-stream"},
  5454. };
  5455. auto boundary = std::string("+++++");
  5456. std::string body;
  5457. for (const auto &item : items) {
  5458. body += "--" + boundary + "\r\n";
  5459. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5460. if (!item.filename.empty()) {
  5461. body += "; filename=\"" + item.filename + "\"";
  5462. }
  5463. body += "\r\n";
  5464. if (!item.content_type.empty()) {
  5465. body += "Content-Type: " + item.content_type + "\r\n";
  5466. }
  5467. body += "\r\n";
  5468. body += item.content + "\r\n";
  5469. }
  5470. body += "--" + boundary + "--\r\n";
  5471. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5472. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5473. ASSERT_TRUE(res);
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. }
  5476. TEST_F(ServerTest, PostContentReceiverGzip) {
  5477. cli_.set_compress(true);
  5478. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5479. ASSERT_TRUE(res);
  5480. ASSERT_EQ(StatusCode::OK_200, res->status);
  5481. ASSERT_EQ("content", res->body);
  5482. }
  5483. TEST_F(ServerTest, PutContentReceiver) {
  5484. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5485. ASSERT_TRUE(res);
  5486. ASSERT_EQ(StatusCode::OK_200, res->status);
  5487. ASSERT_EQ("content", res->body);
  5488. }
  5489. TEST_F(ServerTest, PatchContentReceiver) {
  5490. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5491. ASSERT_TRUE(res);
  5492. ASSERT_EQ(StatusCode::OK_200, res->status);
  5493. ASSERT_EQ("content", res->body);
  5494. }
  5495. template <typename ClientType>
  5496. void TestWithHeadersAndContentReceiver(
  5497. ClientType &cli,
  5498. std::function<Result(ClientType &, const std::string &, const Headers &,
  5499. const std::string &, const std::string &,
  5500. ContentReceiver, DownloadProgress)>
  5501. request_func) {
  5502. Headers headers;
  5503. headers.emplace("X-Custom-Header", "test-value");
  5504. std::string received_body;
  5505. auto res = request_func(
  5506. cli, "/content_receiver", headers, "content", "application/json",
  5507. [&](const char *data, size_t data_length) {
  5508. received_body.append(data, data_length);
  5509. return true;
  5510. },
  5511. nullptr);
  5512. ASSERT_TRUE(res);
  5513. EXPECT_EQ(StatusCode::OK_200, res->status);
  5514. EXPECT_EQ("content", received_body);
  5515. }
  5516. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5517. #ifdef CPPHTTPLIB_SSL_ENABLED
  5518. using ClientT = SSLClient;
  5519. #else
  5520. using ClientT = Client;
  5521. #endif
  5522. TestWithHeadersAndContentReceiver<ClientT>(
  5523. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5524. const std::string &body, const std::string &content_type,
  5525. ContentReceiver receiver, DownloadProgress progress) {
  5526. return cli.Post(path, headers, body, content_type, receiver, progress);
  5527. });
  5528. }
  5529. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5530. #ifdef CPPHTTPLIB_SSL_ENABLED
  5531. using ClientT = SSLClient;
  5532. #else
  5533. using ClientT = Client;
  5534. #endif
  5535. TestWithHeadersAndContentReceiver<ClientT>(
  5536. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5537. const std::string &body, const std::string &content_type,
  5538. ContentReceiver receiver, DownloadProgress progress) {
  5539. return cli.Put(path, headers, body, content_type, receiver, progress);
  5540. });
  5541. }
  5542. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5543. #ifdef CPPHTTPLIB_SSL_ENABLED
  5544. using ClientT = SSLClient;
  5545. #else
  5546. using ClientT = Client;
  5547. #endif
  5548. TestWithHeadersAndContentReceiver<ClientT>(
  5549. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5550. const std::string &body, const std::string &content_type,
  5551. ContentReceiver receiver, DownloadProgress progress) {
  5552. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5553. });
  5554. }
  5555. template <typename ClientType>
  5556. void TestWithHeadersAndContentReceiverWithProgress(
  5557. ClientType &cli,
  5558. std::function<Result(ClientType &, const std::string &, const Headers &,
  5559. const std::string &, const std::string &,
  5560. ContentReceiver, DownloadProgress)>
  5561. request_func) {
  5562. Headers headers;
  5563. headers.emplace("X-Test-Header", "progress-test");
  5564. std::string received_body;
  5565. auto progress_called = false;
  5566. auto res = request_func(
  5567. cli, "/content_receiver", headers, "content", "text/plain",
  5568. [&](const char *data, size_t data_length) {
  5569. received_body.append(data, data_length);
  5570. return true;
  5571. },
  5572. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5573. progress_called = true;
  5574. return true;
  5575. });
  5576. ASSERT_TRUE(res);
  5577. EXPECT_EQ(StatusCode::OK_200, res->status);
  5578. EXPECT_EQ("content", received_body);
  5579. EXPECT_TRUE(progress_called);
  5580. }
  5581. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5582. #ifdef CPPHTTPLIB_SSL_ENABLED
  5583. using ClientT = SSLClient;
  5584. #else
  5585. using ClientT = Client;
  5586. #endif
  5587. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5588. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5589. const std::string &body, const std::string &content_type,
  5590. ContentReceiver receiver, DownloadProgress progress) {
  5591. return cli.Post(path, headers, body, content_type, receiver, progress);
  5592. });
  5593. }
  5594. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5595. #ifdef CPPHTTPLIB_SSL_ENABLED
  5596. using ClientT = SSLClient;
  5597. #else
  5598. using ClientT = Client;
  5599. #endif
  5600. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5601. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5602. const std::string &body, const std::string &content_type,
  5603. ContentReceiver receiver, DownloadProgress progress) {
  5604. return cli.Put(path, headers, body, content_type, receiver, progress);
  5605. });
  5606. }
  5607. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5608. #ifdef CPPHTTPLIB_SSL_ENABLED
  5609. using ClientT = SSLClient;
  5610. #else
  5611. using ClientT = Client;
  5612. #endif
  5613. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5614. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5615. const std::string &body, const std::string &content_type,
  5616. ContentReceiver receiver, DownloadProgress progress) {
  5617. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5618. });
  5619. }
  5620. template <typename ClientType>
  5621. void TestWithHeadersAndContentReceiverError(
  5622. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5623. const Headers &, const std::string &,
  5624. const std::string &, ContentReceiver)>
  5625. request_func) {
  5626. Headers headers;
  5627. headers.emplace("X-Error-Test", "true");
  5628. std::string received_body;
  5629. auto receiver_failed = false;
  5630. auto res =
  5631. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5632. [&](const char *data, size_t data_length) {
  5633. received_body.append(data, data_length);
  5634. receiver_failed = true;
  5635. return false;
  5636. });
  5637. ASSERT_FALSE(res);
  5638. EXPECT_TRUE(receiver_failed);
  5639. }
  5640. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5641. #ifdef CPPHTTPLIB_SSL_ENABLED
  5642. using ClientT = SSLClient;
  5643. #else
  5644. using ClientT = Client;
  5645. #endif
  5646. TestWithHeadersAndContentReceiverError<ClientT>(
  5647. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5648. const std::string &body, const std::string &content_type,
  5649. ContentReceiver receiver) {
  5650. return cli.Post(path, headers, body, content_type, receiver);
  5651. });
  5652. }
  5653. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5654. #ifdef CPPHTTPLIB_SSL_ENABLED
  5655. using ClientT = SSLClient;
  5656. #else
  5657. using ClientT = Client;
  5658. #endif
  5659. TestWithHeadersAndContentReceiverError<ClientT>(
  5660. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5661. const std::string &body, const std::string &content_type,
  5662. ContentReceiver receiver) {
  5663. return cli.Put(path, headers, body, content_type, receiver);
  5664. });
  5665. }
  5666. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5667. #ifdef CPPHTTPLIB_SSL_ENABLED
  5668. using ClientT = SSLClient;
  5669. #else
  5670. using ClientT = Client;
  5671. #endif
  5672. TestWithHeadersAndContentReceiverError<ClientT>(
  5673. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5674. const std::string &body, const std::string &content_type,
  5675. ContentReceiver receiver) {
  5676. return cli.Patch(path, headers, body, content_type, receiver);
  5677. });
  5678. }
  5679. TEST_F(ServerTest, PostQueryStringAndBody) {
  5680. auto res =
  5681. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5682. ASSERT_TRUE(res);
  5683. ASSERT_EQ(StatusCode::OK_200, res->status);
  5684. }
  5685. TEST_F(ServerTest, HTTP2Magic) {
  5686. Request req;
  5687. req.method = "PRI";
  5688. req.path = "*";
  5689. req.body = "SM";
  5690. auto res = std::make_shared<Response>();
  5691. auto error = Error::Success;
  5692. auto ret = cli_.send(req, *res, error);
  5693. ASSERT_TRUE(ret);
  5694. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5695. }
  5696. TEST_F(ServerTest, KeepAlive) {
  5697. auto res = cli_.Get("/hi");
  5698. ASSERT_TRUE(res);
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5701. EXPECT_EQ("Hello World!", res->body);
  5702. res = cli_.Get("/hi");
  5703. ASSERT_TRUE(res);
  5704. EXPECT_EQ(StatusCode::OK_200, res->status);
  5705. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5706. EXPECT_EQ("Hello World!", res->body);
  5707. res = cli_.Get("/hi");
  5708. ASSERT_TRUE(res);
  5709. EXPECT_EQ(StatusCode::OK_200, res->status);
  5710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5711. EXPECT_EQ("Hello World!", res->body);
  5712. res = cli_.Get("/not-exist");
  5713. ASSERT_TRUE(res);
  5714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5715. res = cli_.Post("/empty", "", "text/plain");
  5716. ASSERT_TRUE(res);
  5717. EXPECT_EQ(StatusCode::OK_200, res->status);
  5718. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5719. EXPECT_EQ("empty", res->body);
  5720. EXPECT_EQ("close", res->get_header_value("Connection"));
  5721. res = cli_.Post(
  5722. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5723. "text/plain");
  5724. ASSERT_TRUE(res);
  5725. EXPECT_EQ(StatusCode::OK_200, res->status);
  5726. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5727. EXPECT_EQ("empty", res->body);
  5728. cli_.set_keep_alive(false);
  5729. res = cli_.Get("/last-request");
  5730. ASSERT_TRUE(res);
  5731. EXPECT_EQ(StatusCode::OK_200, res->status);
  5732. EXPECT_EQ("close", res->get_header_value("Connection"));
  5733. }
  5734. TEST_F(ServerTest, TooManyRedirect) {
  5735. cli_.set_follow_location(true);
  5736. auto res = cli_.Get("/redirect/0");
  5737. ASSERT_TRUE(!res);
  5738. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5739. }
  5740. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5741. Request req;
  5742. req.method = "FOOBAR";
  5743. req.path = "/hi";
  5744. cli_.set_keep_alive(true);
  5745. auto res = cli_.send(req);
  5746. ASSERT_TRUE(res);
  5747. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5748. EXPECT_EQ("close", res->get_header_value("Connection"));
  5749. EXPECT_FALSE(cli_.is_socket_open());
  5750. }
  5751. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5752. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5753. TEST_F(ServerTest, Gzip) {
  5754. Headers headers;
  5755. headers.emplace("Accept-Encoding", "gzip, deflate");
  5756. auto res = cli_.Get("/compress", headers);
  5757. ASSERT_TRUE(res);
  5758. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5760. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5761. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5762. "7890123456789012345678901234567890",
  5763. res->body);
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. }
  5766. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5767. Headers headers;
  5768. headers.emplace("Accept-Encoding", "gzip, deflate");
  5769. auto res = cli_.Get("/compress-with-charset", headers);
  5770. ASSERT_TRUE(res);
  5771. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5772. EXPECT_EQ("application/json; charset=utf-8",
  5773. res->get_header_value("Content-Type"));
  5774. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5775. "7890123456789012345678901234567890",
  5776. res->body);
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. }
  5779. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5780. Headers headers;
  5781. headers.emplace("Accept-Encoding", "");
  5782. auto res = cli_.Get("/compress", headers);
  5783. ASSERT_TRUE(res);
  5784. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5785. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5786. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5787. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5788. "7890123456789012345678901234567890",
  5789. res->body);
  5790. EXPECT_EQ(StatusCode::OK_200, res->status);
  5791. }
  5792. TEST_F(ServerTest, GzipWithContentReceiver) {
  5793. Headers headers;
  5794. headers.emplace("Accept-Encoding", "gzip, deflate");
  5795. std::string body;
  5796. auto res = cli_.Get("/compress", headers,
  5797. [&](const char *data, uint64_t data_length) {
  5798. EXPECT_EQ(100U, data_length);
  5799. body.append(data, data_length);
  5800. return true;
  5801. });
  5802. ASSERT_TRUE(res);
  5803. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5804. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5805. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5806. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5807. "7890123456789012345678901234567890",
  5808. body);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. }
  5811. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5812. Headers headers;
  5813. headers.emplace("Accept-Encoding", "gzip, deflate");
  5814. cli_.set_decompress(false);
  5815. auto res = cli_.Get("/compress", headers);
  5816. ASSERT_TRUE(res);
  5817. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5818. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5819. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5820. EXPECT_EQ(33U, res->body.size());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. }
  5823. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5824. Headers headers;
  5825. headers.emplace("Accept-Encoding", "");
  5826. std::string body;
  5827. auto res = cli_.Get("/compress", headers,
  5828. [&](const char *data, uint64_t data_length) {
  5829. EXPECT_EQ(100U, data_length);
  5830. body.append(data, data_length);
  5831. return true;
  5832. });
  5833. ASSERT_TRUE(res);
  5834. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5835. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5836. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5837. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5838. "7890123456789012345678901234567890",
  5839. body);
  5840. EXPECT_EQ(StatusCode::OK_200, res->status);
  5841. }
  5842. TEST_F(ServerTest, NoGzip) {
  5843. Headers headers;
  5844. headers.emplace("Accept-Encoding", "gzip, deflate");
  5845. auto res = cli_.Get("/nocompress", headers);
  5846. ASSERT_TRUE(res);
  5847. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5848. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5849. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5850. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5851. "7890123456789012345678901234567890",
  5852. res->body);
  5853. EXPECT_EQ(StatusCode::OK_200, res->status);
  5854. }
  5855. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5856. Headers headers;
  5857. headers.emplace("Accept-Encoding", "gzip, deflate");
  5858. std::string body;
  5859. auto res = cli_.Get("/nocompress", headers,
  5860. [&](const char *data, uint64_t data_length) {
  5861. EXPECT_EQ(100U, data_length);
  5862. body.append(data, data_length);
  5863. return true;
  5864. });
  5865. ASSERT_TRUE(res);
  5866. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5867. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5868. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5869. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5870. "7890123456789012345678901234567890",
  5871. body);
  5872. EXPECT_EQ(StatusCode::OK_200, res->status);
  5873. }
  5874. TEST_F(ServerTest, MultipartFormDataGzip) {
  5875. UploadFormDataItems items = {
  5876. {"key1", "test", "", ""},
  5877. {"key2", "--abcdefg123", "", ""},
  5878. };
  5879. cli_.set_compress(true);
  5880. auto res = cli_.Post("/compress-multipart", items);
  5881. ASSERT_TRUE(res);
  5882. EXPECT_EQ(StatusCode::OK_200, res->status);
  5883. }
  5884. #endif
  5885. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5886. TEST_F(ServerTest, Brotli) {
  5887. Headers headers;
  5888. headers.emplace("Accept-Encoding", "br");
  5889. auto res = cli_.Get("/compress", headers);
  5890. ASSERT_TRUE(res);
  5891. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5892. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5893. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5894. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5895. "7890123456789012345678901234567890",
  5896. res->body);
  5897. EXPECT_EQ(StatusCode::OK_200, res->status);
  5898. }
  5899. #endif
  5900. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5901. TEST_F(ServerTest, Zstd) {
  5902. Headers headers;
  5903. headers.emplace("Accept-Encoding", "zstd");
  5904. auto res = cli_.Get("/compress", headers);
  5905. ASSERT_TRUE(res);
  5906. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5907. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5908. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5909. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5910. "7890123456789012345678901234567890",
  5911. res->body);
  5912. EXPECT_EQ(StatusCode::OK_200, res->status);
  5913. }
  5914. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5915. Headers headers;
  5916. headers.emplace("Accept-Encoding", "");
  5917. auto res = cli_.Get("/compress", headers);
  5918. ASSERT_TRUE(res);
  5919. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5921. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5922. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5923. "7890123456789012345678901234567890",
  5924. res->body);
  5925. EXPECT_EQ(StatusCode::OK_200, res->status);
  5926. }
  5927. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5928. Headers headers;
  5929. headers.emplace("Accept-Encoding", "zstd");
  5930. std::string body;
  5931. auto res = cli_.Get("/compress", headers,
  5932. [&](const char *data, uint64_t data_length) {
  5933. EXPECT_EQ(100U, data_length);
  5934. body.append(data, data_length);
  5935. return true;
  5936. });
  5937. ASSERT_TRUE(res);
  5938. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5939. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5940. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5941. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5942. "7890123456789012345678901234567890",
  5943. body);
  5944. EXPECT_EQ(StatusCode::OK_200, res->status);
  5945. }
  5946. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5947. Headers headers;
  5948. headers.emplace("Accept-Encoding", "zstd");
  5949. cli_.set_decompress(false);
  5950. auto res = cli_.Get("/compress", headers);
  5951. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5952. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5953. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5954. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5955. ASSERT_TRUE(res);
  5956. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5957. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5958. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5959. EXPECT_EQ(StatusCode::OK_200, res->status);
  5960. ASSERT_EQ(26U, res->body.size());
  5961. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5962. 0);
  5963. }
  5964. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5965. Headers headers;
  5966. headers.emplace("Accept-Encoding", "");
  5967. std::string body;
  5968. auto res = cli_.Get("/compress", headers,
  5969. [&](const char *data, uint64_t data_length) {
  5970. EXPECT_EQ(100U, data_length);
  5971. body.append(data, data_length);
  5972. return true;
  5973. });
  5974. ASSERT_TRUE(res);
  5975. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5977. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5978. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5979. "7890123456789012345678901234567890",
  5980. body);
  5981. EXPECT_EQ(StatusCode::OK_200, res->status);
  5982. }
  5983. TEST_F(ServerTest, NoZstd) {
  5984. Headers headers;
  5985. headers.emplace("Accept-Encoding", "zstd");
  5986. auto res = cli_.Get("/nocompress", headers);
  5987. ASSERT_TRUE(res);
  5988. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5989. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5990. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5991. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5992. "7890123456789012345678901234567890",
  5993. res->body);
  5994. EXPECT_EQ(StatusCode::OK_200, res->status);
  5995. }
  5996. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5997. Headers headers;
  5998. headers.emplace("Accept-Encoding", "zstd");
  5999. std::string body;
  6000. auto res = cli_.Get("/nocompress", headers,
  6001. [&](const char *data, uint64_t data_length) {
  6002. EXPECT_EQ(100U, data_length);
  6003. body.append(data, data_length);
  6004. return true;
  6005. });
  6006. ASSERT_TRUE(res);
  6007. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6008. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6009. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6011. "7890123456789012345678901234567890",
  6012. body);
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. }
  6015. // TODO: How to enable zstd ??
  6016. TEST_F(ServerTest, MultipartFormDataZstd) {
  6017. UploadFormDataItems items = {
  6018. {"key1", "test", "", ""},
  6019. {"key2", "--abcdefg123", "", ""},
  6020. };
  6021. Headers headers;
  6022. headers.emplace("Accept-Encoding", "zstd");
  6023. cli_.set_compress(true);
  6024. auto res = cli_.Post("/compress-multipart", headers, items);
  6025. ASSERT_TRUE(res);
  6026. EXPECT_EQ(StatusCode::OK_200, res->status);
  6027. }
  6028. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6029. Headers headers;
  6030. headers.emplace("Accept-Encoding", "zstd");
  6031. cli_.set_compress(true);
  6032. auto res = cli_.Put(
  6033. "/put", headers, 3,
  6034. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6035. sink.os << "PUT";
  6036. return true;
  6037. },
  6038. "text/plain");
  6039. ASSERT_TRUE(res);
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. EXPECT_EQ("PUT", res->body);
  6042. }
  6043. // Pre-compression logging tests
  6044. TEST_F(ServerTest, PreCompressionLogging) {
  6045. // Test data for compression (matches the actual /compress endpoint content)
  6046. const std::string test_content =
  6047. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6048. "3456789012345678901234567890";
  6049. // Variables to capture logging data
  6050. std::string pre_compression_body;
  6051. std::string pre_compression_content_type;
  6052. std::string pre_compression_content_encoding;
  6053. std::string post_compression_body;
  6054. std::string post_compression_content_type;
  6055. std::string post_compression_content_encoding;
  6056. // Set up pre-compression logger
  6057. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6058. const Response &res) {
  6059. pre_compression_body = res.body;
  6060. pre_compression_content_type = res.get_header_value("Content-Type");
  6061. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6062. });
  6063. // Set up post-compression logger
  6064. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6065. post_compression_body = res.body;
  6066. post_compression_content_type = res.get_header_value("Content-Type");
  6067. post_compression_content_encoding =
  6068. res.get_header_value("Content-Encoding");
  6069. });
  6070. // Test with gzip compression
  6071. Headers headers;
  6072. headers.emplace("Accept-Encoding", "gzip");
  6073. auto res = cli_.Get("/compress", headers);
  6074. // Verify response was compressed
  6075. ASSERT_TRUE(res);
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6078. // Verify pre-compression logger captured uncompressed content
  6079. EXPECT_EQ(test_content, pre_compression_body);
  6080. EXPECT_EQ("text/plain", pre_compression_content_type);
  6081. EXPECT_TRUE(pre_compression_content_encoding
  6082. .empty()); // No encoding header before compression
  6083. // Verify post-compression logger captured compressed content
  6084. EXPECT_NE(test_content,
  6085. post_compression_body); // Should be different after compression
  6086. EXPECT_EQ("text/plain", post_compression_content_type);
  6087. EXPECT_EQ("gzip", post_compression_content_encoding);
  6088. // Verify compressed content is smaller
  6089. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6090. }
  6091. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6092. const std::string test_content =
  6093. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6094. "3456789012345678901234567890";
  6095. std::string pre_compression_body;
  6096. std::string post_compression_body;
  6097. svr_.set_pre_compression_logger(
  6098. [&](const Request & /*req*/, const Response &res) {
  6099. pre_compression_body = res.body;
  6100. });
  6101. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6102. post_compression_body = res.body;
  6103. });
  6104. Headers headers;
  6105. headers.emplace("Accept-Encoding", "br");
  6106. auto res = cli_.Get("/compress", headers);
  6107. ASSERT_TRUE(res);
  6108. EXPECT_EQ(StatusCode::OK_200, res->status);
  6109. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6110. // Verify pre-compression content is uncompressed
  6111. EXPECT_EQ(test_content, pre_compression_body);
  6112. // Verify post-compression content is compressed
  6113. EXPECT_NE(test_content, post_compression_body);
  6114. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6115. }
  6116. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6117. const std::string test_content =
  6118. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6119. "3456789012345678901234567890";
  6120. std::string pre_compression_body;
  6121. std::string post_compression_body;
  6122. svr_.set_pre_compression_logger(
  6123. [&](const Request & /*req*/, const Response &res) {
  6124. pre_compression_body = res.body;
  6125. });
  6126. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6127. post_compression_body = res.body;
  6128. });
  6129. // Request without compression (use /nocompress endpoint)
  6130. Headers headers;
  6131. auto res = cli_.Get("/nocompress", headers);
  6132. ASSERT_TRUE(res);
  6133. EXPECT_EQ(StatusCode::OK_200, res->status);
  6134. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6135. // Pre-compression logger should not be called when no compression is applied
  6136. EXPECT_TRUE(
  6137. pre_compression_body.empty()); // Pre-compression logger not called
  6138. EXPECT_EQ(
  6139. test_content,
  6140. post_compression_body); // Post-compression logger captures final content
  6141. }
  6142. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6143. const std::string test_content =
  6144. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6145. "3456789012345678901234567890";
  6146. std::string pre_compression_body;
  6147. bool pre_logger_called = false;
  6148. // Set only pre-compression logger
  6149. svr_.set_pre_compression_logger(
  6150. [&](const Request & /*req*/, const Response &res) {
  6151. pre_compression_body = res.body;
  6152. pre_logger_called = true;
  6153. });
  6154. Headers headers;
  6155. headers.emplace("Accept-Encoding", "gzip");
  6156. auto res = cli_.Get("/compress", headers);
  6157. ASSERT_TRUE(res);
  6158. EXPECT_EQ(StatusCode::OK_200, res->status);
  6159. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6160. // Verify pre-compression logger was called
  6161. EXPECT_TRUE(pre_logger_called);
  6162. EXPECT_EQ(test_content, pre_compression_body);
  6163. }
  6164. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6165. {
  6166. // Test with Expect: 100-continue header - success case
  6167. // Server returns 100 Continue, client sends body, server returns 200 OK
  6168. Request req;
  6169. req.method = "POST";
  6170. req.path = "/post-large";
  6171. req.set_header("Expect", "100-continue");
  6172. req.body = LARGE_DATA;
  6173. Response res;
  6174. auto error = Error::Success;
  6175. cli_.set_keep_alive(true);
  6176. auto ret = cli_.send(req, res, error);
  6177. EXPECT_TRUE(ret);
  6178. EXPECT_EQ(StatusCode::OK_200, res.status);
  6179. EXPECT_EQ(LARGE_DATA, res.body);
  6180. }
  6181. {
  6182. // Test with Expect: 100-continue header - error case
  6183. // Client should not send the body when server returns an error
  6184. Request req;
  6185. req.method = "POST";
  6186. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6187. req.set_header("Expect", "100-continue");
  6188. req.body = LARGE_DATA;
  6189. Response res;
  6190. auto error = Error::Success;
  6191. auto start = std::chrono::high_resolution_clock::now();
  6192. cli_.set_keep_alive(true);
  6193. auto ret = cli_.send(req, res, error);
  6194. auto end = std::chrono::high_resolution_clock::now();
  6195. auto elapsed =
  6196. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6197. .count();
  6198. // With Expect: 100-continue, request completes successfully but with error
  6199. EXPECT_TRUE(ret);
  6200. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6201. EXPECT_EQ("close", res.get_header_value("Connection"));
  6202. EXPECT_FALSE(cli_.is_socket_open());
  6203. EXPECT_LE(elapsed, 2000);
  6204. }
  6205. {
  6206. // Send an extra GET request to ensure error recovery without hanging
  6207. Request req;
  6208. req.method = "GET";
  6209. req.path = "/hi";
  6210. auto start = std::chrono::high_resolution_clock::now();
  6211. auto res = cli_.send(req);
  6212. auto end = std::chrono::high_resolution_clock::now();
  6213. auto elapsed =
  6214. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6215. .count();
  6216. ASSERT_TRUE(res);
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. EXPECT_EQ("Hello World!", res->body);
  6219. EXPECT_LE(elapsed, 500);
  6220. }
  6221. }
  6222. TEST(ZstdDecompressor, ChunkedDecompression) {
  6223. std::string data;
  6224. for (size_t i = 0; i < 32 * 1024; ++i) {
  6225. data.push_back(static_cast<char>('a' + i % 26));
  6226. }
  6227. std::string compressed_data;
  6228. {
  6229. httplib::detail::zstd_compressor compressor;
  6230. bool result = compressor.compress(
  6231. data.data(), data.size(),
  6232. /*last=*/true,
  6233. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6234. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6235. compressed_data_size);
  6236. return true;
  6237. });
  6238. ASSERT_TRUE(result);
  6239. }
  6240. std::string decompressed_data;
  6241. {
  6242. httplib::detail::zstd_decompressor decompressor;
  6243. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6244. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6245. size_t chunk_size = 130;
  6246. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6247. chunk_begin += chunk_size) {
  6248. size_t current_chunk_size =
  6249. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6250. bool result = decompressor.decompress(
  6251. compressed_data.data() + chunk_begin, current_chunk_size,
  6252. [&](const char *decompressed_data_chunk,
  6253. size_t decompressed_data_chunk_size) {
  6254. decompressed_data.insert(decompressed_data.size(),
  6255. decompressed_data_chunk,
  6256. decompressed_data_chunk_size);
  6257. return true;
  6258. });
  6259. ASSERT_TRUE(result);
  6260. }
  6261. }
  6262. ASSERT_EQ(data, decompressed_data);
  6263. }
  6264. TEST(ZstdDecompressor, Decompress) {
  6265. std::string original_text = "Compressed with ZSTD";
  6266. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6267. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6268. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6269. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6270. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6271. std::string decompressed_data;
  6272. {
  6273. httplib::detail::zstd_decompressor decompressor;
  6274. bool result = decompressor.decompress(
  6275. compressed_data.data(), compressed_data.size(),
  6276. [&](const char *decompressed_data_chunk,
  6277. size_t decompressed_data_chunk_size) {
  6278. decompressed_data.insert(decompressed_data.size(),
  6279. decompressed_data_chunk,
  6280. decompressed_data_chunk_size);
  6281. return true;
  6282. });
  6283. ASSERT_TRUE(result);
  6284. }
  6285. ASSERT_EQ(original_text, decompressed_data);
  6286. }
  6287. #endif
  6288. // Sends a raw request to a server listening at HOST:PORT.
  6289. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6290. std::string *resp = nullptr) {
  6291. auto error = Error::Success;
  6292. auto client_sock = detail::create_client_socket(
  6293. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6294. /*connection_timeout_sec=*/5, 0,
  6295. /*read_timeout_sec=*/5, 0,
  6296. /*write_timeout_sec=*/5, 0, std::string(), error);
  6297. if (client_sock == INVALID_SOCKET) { return false; }
  6298. auto ret = detail::process_client_socket(
  6299. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6300. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6301. if (req.size() !=
  6302. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6303. return false;
  6304. }
  6305. char buf[512];
  6306. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6307. while (line_reader.getline()) {
  6308. if (resp) { *resp += line_reader.ptr(); }
  6309. }
  6310. return true;
  6311. });
  6312. detail::close_socket(client_sock);
  6313. return ret;
  6314. }
  6315. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6316. Server svr;
  6317. std::string header_value;
  6318. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6319. header_value = req.get_header_value("foo");
  6320. res.set_content("ok", "text/plain");
  6321. });
  6322. thread t = thread([&] { svr.listen(HOST, PORT); });
  6323. auto se = detail::scope_exit([&] {
  6324. svr.stop();
  6325. t.join();
  6326. ASSERT_FALSE(svr.is_running());
  6327. });
  6328. svr.wait_until_ready();
  6329. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6330. // like characters are not treated the same - use vertical tab and escape.
  6331. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6332. "foo: \t \v bar \x1B\t \r\n"
  6333. "Connection: close\r\n"
  6334. "\r\n";
  6335. std::string res;
  6336. ASSERT_TRUE(send_request(5, req, &res));
  6337. EXPECT_EQ(header_value, "");
  6338. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6339. }
  6340. // Sends a raw request and verifies that there isn't a crash or exception.
  6341. static void test_raw_request(const std::string &req,
  6342. std::string *out = nullptr) {
  6343. Server svr;
  6344. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6345. res.set_content("ok", "text/plain");
  6346. });
  6347. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6348. res.set_content("ok", "text/plain");
  6349. });
  6350. svr.Get("/header_field_value_check",
  6351. [&](const Request & /*req*/, Response &res) {
  6352. res.set_content("ok", "text/plain");
  6353. });
  6354. // Server read timeout must be longer than the client read timeout for the
  6355. // bug to reproduce, probably to force the server to process a request
  6356. // without a trailing blank line.
  6357. const time_t client_read_timeout_sec = 1;
  6358. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6359. bool listen_thread_ok = false;
  6360. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6361. auto se = detail::scope_exit([&] {
  6362. svr.stop();
  6363. t.join();
  6364. ASSERT_FALSE(svr.is_running());
  6365. EXPECT_TRUE(listen_thread_ok);
  6366. });
  6367. svr.wait_until_ready();
  6368. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6369. }
  6370. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6371. // A certain header line causes an exception if the header property is parsed
  6372. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6373. test_raw_request(
  6374. "GET /hi HTTP/1.1\r\n"
  6375. " : "
  6376. " "
  6377. " ");
  6378. }
  6379. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6380. // A certain header line causes an exception if the header property *name* is
  6381. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6382. // greedy matcher and requires backtracking when there are a lot of ":"
  6383. // characters.
  6384. // This occurs with libc++ but not libstdc++.
  6385. test_raw_request(
  6386. "GET /hi HTTP/1.1\r\n"
  6387. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6388. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6389. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6390. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6391. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6392. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6393. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6394. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6395. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6396. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6397. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6398. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6399. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6400. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6401. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6402. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6403. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6404. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6405. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6406. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6407. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6408. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6409. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6410. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6411. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6412. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6413. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6414. "&&&%%%");
  6415. }
  6416. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6417. // Make sure this doesn't crash the server.
  6418. // In a previous version of the header line regex, the "\r" rendered the line
  6419. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6420. // a new position where the leading white space ended and the field value
  6421. // began.
  6422. // The crash occurs with libc++ but not libstdc++.
  6423. test_raw_request("GET /hi HTTP/1.1\r\n"
  6424. "a:" +
  6425. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6426. "\r\n"
  6427. "\r\n");
  6428. }
  6429. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6430. std::string out;
  6431. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6432. "Content-Type: text/plain\r\n"
  6433. "Transfer-Encoding: chunked\r\n"
  6434. "\r\n"
  6435. "nothex\r\n",
  6436. &out);
  6437. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6438. }
  6439. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6440. std::string out;
  6441. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6442. "Content-Type: text/plain\r\n"
  6443. "Transfer-Encoding: chunked\r\n"
  6444. "\r\n"
  6445. "3\r\n"
  6446. "xyz\r\n"
  6447. "NaN\r\n",
  6448. &out);
  6449. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6450. }
  6451. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6452. std::string out;
  6453. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6454. "Content-Type: text/plain\r\n"
  6455. "Transfer-Encoding: chunked\r\n"
  6456. "\r\n"
  6457. // Length is too large for 64 bits.
  6458. "1ffffffffffffffff\r\n"
  6459. "xyz\r\n",
  6460. &out);
  6461. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6462. }
  6463. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6464. test_raw_request("GET /hi HTTP/1.1\r\n"
  6465. "Content-Type: text/plain\r\n\r");
  6466. }
  6467. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6468. std::string out;
  6469. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6470. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6471. }
  6472. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6473. Server svr;
  6474. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6475. EXPECT_TRUE(!req.remote_addr.empty());
  6476. });
  6477. thread t = thread([&] { svr.listen(HOST, PORT); });
  6478. auto se = detail::scope_exit([&] {
  6479. svr.stop();
  6480. t.join();
  6481. ASSERT_FALSE(svr.is_running());
  6482. });
  6483. svr.wait_until_ready();
  6484. // Send an invalid request line to trigger Bad Request
  6485. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6486. std::string out;
  6487. ASSERT_TRUE(send_request(5, bad_req, &out));
  6488. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6489. }
  6490. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6491. std::string out;
  6492. std::string request(
  6493. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6494. test_raw_request(request, &out);
  6495. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6496. }
  6497. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6498. std::string out;
  6499. std::string request(
  6500. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6501. test_raw_request(request, &out);
  6502. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6503. }
  6504. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6505. std::string out;
  6506. std::string request(
  6507. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6508. test_raw_request(request, &out);
  6509. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6510. }
  6511. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6512. std::string out;
  6513. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6514. "Test: \r\n\r\n",
  6515. &out);
  6516. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6517. }
  6518. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6519. Server svr;
  6520. std::string x_custom;
  6521. std::string cookie;
  6522. std::string xff;
  6523. std::string x_unicode;
  6524. std::string x_iis;
  6525. svr.Get("/check", [&](const Request &req, Response &res) {
  6526. x_custom = req.get_header_value("X-Custom");
  6527. cookie = req.get_header_value("Cookie");
  6528. xff = req.get_header_value("X-Forwarded-For");
  6529. x_unicode = req.get_header_value("X-Unicode");
  6530. x_iis = req.get_header_value("X-IIS");
  6531. res.set_content("ok", "text/plain");
  6532. });
  6533. thread t = thread([&] { svr.listen(HOST, PORT); });
  6534. auto se = detail::scope_exit([&] {
  6535. svr.stop();
  6536. t.join();
  6537. ASSERT_FALSE(svr.is_running());
  6538. });
  6539. svr.wait_until_ready();
  6540. const std::string req = "GET /check HTTP/1.1\r\n"
  6541. "Host: localhost\r\n"
  6542. "X-Custom: a%0D%0AInjected: b\r\n"
  6543. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6544. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6545. "X-Unicode: %E3%81%82\r\n"
  6546. "X-IIS: %u00E9\r\n"
  6547. "Connection: close\r\n"
  6548. "\r\n";
  6549. std::string res;
  6550. ASSERT_TRUE(send_request(5, req, &res));
  6551. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6552. // Every value must be returned verbatim (wire form), with no decoding.
  6553. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6554. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6555. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6556. EXPECT_EQ("%E3%81%82", x_unicode);
  6557. EXPECT_EQ("%u00E9", x_iis);
  6558. }
  6559. // Applications that previously relied on automatic percent-decoding can
  6560. // reproduce the old behavior by explicitly calling decode_path_component()
  6561. // or, for RFC 3986 conformance, decode_uri_component().
  6562. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6563. Server svr;
  6564. std::string decoded;
  6565. svr.Get("/check", [&](const Request &req, Response &res) {
  6566. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6567. res.set_content("ok", "text/plain");
  6568. });
  6569. thread t = thread([&] { svr.listen(HOST, PORT); });
  6570. auto se = detail::scope_exit([&] {
  6571. svr.stop();
  6572. t.join();
  6573. ASSERT_FALSE(svr.is_running());
  6574. });
  6575. svr.wait_until_ready();
  6576. const std::string req = "GET /check HTTP/1.1\r\n"
  6577. "Host: localhost\r\n"
  6578. "X-Custom: hello%20world\r\n"
  6579. "Connection: close\r\n"
  6580. "\r\n";
  6581. std::string res;
  6582. ASSERT_TRUE(send_request(5, req, &res));
  6583. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6584. EXPECT_EQ("hello world", decoded);
  6585. }
  6586. // Regression test for #2033. Browsers send Referer values that include
  6587. // percent-encoded characters such as %0A inside the URL. Decoding the
  6588. // header value would either trip the post-decode CR/LF/NUL guard (the
  6589. // original bug, returning 400) or, after that guard was relaxed, silently
  6590. // store a literal LF — both unacceptable. The wire form must round-trip.
  6591. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6592. Server svr;
  6593. std::string referer;
  6594. svr.Get("/check", [&](const Request &req, Response &res) {
  6595. referer = req.get_header_value("Referer");
  6596. res.set_content("ok", "text/plain");
  6597. });
  6598. thread t = thread([&] { svr.listen(HOST, PORT); });
  6599. auto se = detail::scope_exit([&] {
  6600. svr.stop();
  6601. t.join();
  6602. ASSERT_FALSE(svr.is_running());
  6603. });
  6604. svr.wait_until_ready();
  6605. const std::string req = "GET /check HTTP/1.1\r\n"
  6606. "Host: localhost\r\n"
  6607. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6608. "Connection: close\r\n"
  6609. "\r\n";
  6610. std::string res;
  6611. ASSERT_TRUE(send_request(5, req, &res));
  6612. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6613. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6614. }
  6615. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6616. Server svr;
  6617. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6618. res.set_header("Cache-Control", "no-cache");
  6619. res.set_chunked_content_provider(
  6620. "text/event-stream", [](size_t offset, DataSink &sink) {
  6621. std::string s = "data:";
  6622. s += std::to_string(offset);
  6623. s += "\n\n";
  6624. auto ret = sink.write(s.data(), s.size());
  6625. EXPECT_TRUE(ret);
  6626. std::this_thread::sleep_for(std::chrono::seconds(1));
  6627. return true;
  6628. });
  6629. });
  6630. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6631. svr.wait_until_ready();
  6632. Client client(HOST, PORT);
  6633. const Headers headers = {{"Accept", "text/event-stream"}};
  6634. auto get_thread = std::thread([&client, &headers]() {
  6635. auto res = client.Get(
  6636. "/events", headers,
  6637. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6638. });
  6639. auto se = detail::scope_exit([&] {
  6640. svr.stop();
  6641. get_thread.join();
  6642. listen_thread.join();
  6643. ASSERT_FALSE(svr.is_running());
  6644. });
  6645. // Give GET time to get a few messages.
  6646. std::this_thread::sleep_for(std::chrono::seconds(2));
  6647. }
  6648. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6649. httplib::Server svr;
  6650. svr.Post("/hi",
  6651. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6652. res.status = StatusCode::OK_200;
  6653. });
  6654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6655. svr.wait_until_ready();
  6656. Client cli(HOST, PORT);
  6657. auto res = cli.Post("/hi", "data", "text/plain");
  6658. ASSERT_TRUE(res);
  6659. EXPECT_EQ(StatusCode::OK_200, res->status);
  6660. svr.stop();
  6661. thread.join();
  6662. ASSERT_FALSE(svr.is_running());
  6663. res = cli.Post("/hi", "data", "text/plain");
  6664. ASSERT_FALSE(res);
  6665. }
  6666. TEST(ServerStopTest, ListenFailure) {
  6667. Server svr;
  6668. auto t = thread([&]() {
  6669. auto ret = svr.listen("????", PORT);
  6670. EXPECT_FALSE(ret);
  6671. });
  6672. svr.wait_until_ready();
  6673. svr.stop();
  6674. t.join();
  6675. }
  6676. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6677. TEST(ServerStopTest, Decommision) {
  6678. Server svr;
  6679. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6680. for (int i = 0; i < 4; i++) {
  6681. auto is_even = !(i % 2);
  6682. std::thread t{[&] {
  6683. try {
  6684. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6685. if (is_even) {
  6686. throw std::runtime_error("Some thing that happens to go wrong.");
  6687. }
  6688. svr.listen(HOST, PORT);
  6689. } catch (...) { svr.decommission(); }
  6690. }};
  6691. svr.wait_until_ready();
  6692. // Server is up
  6693. {
  6694. Client cli(HOST, PORT);
  6695. auto res = cli.Get("/hi");
  6696. if (is_even) {
  6697. EXPECT_FALSE(res);
  6698. } else {
  6699. EXPECT_TRUE(res);
  6700. EXPECT_EQ("hi...", res->body);
  6701. }
  6702. }
  6703. svr.stop();
  6704. t.join();
  6705. // Server is down...
  6706. {
  6707. Client cli(HOST, PORT);
  6708. auto res = cli.Get("/hi");
  6709. EXPECT_FALSE(res);
  6710. }
  6711. }
  6712. }
  6713. #endif
  6714. // Helper function for string body upload progress tests
  6715. template <typename SetupHandler, typename ClientCall>
  6716. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6717. ClientCall &&client_call,
  6718. const string &body) {
  6719. Server svr;
  6720. setup_handler(svr);
  6721. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6722. auto se = detail::scope_exit([&] {
  6723. svr.stop();
  6724. t.join();
  6725. });
  6726. svr.wait_until_ready();
  6727. Client cli(HOST, PORT);
  6728. vector<uint64_t> progress_values;
  6729. bool progress_called = false;
  6730. auto res =
  6731. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6732. progress_values.push_back(current);
  6733. progress_called = true;
  6734. return true;
  6735. });
  6736. ASSERT_TRUE(res);
  6737. EXPECT_EQ(200, res->status);
  6738. EXPECT_TRUE(progress_called);
  6739. }
  6740. TEST(UploadProgressTest, PostStringBodyBasic) {
  6741. TestStringBodyUploadProgress(
  6742. [](Server &svr) {
  6743. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6744. res.set_content("received", "text/plain");
  6745. });
  6746. },
  6747. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6748. return cli.Post("/test", body, "text/plain", progress_callback);
  6749. },
  6750. "test data for upload progress");
  6751. }
  6752. TEST(UploadProgressTest, PutStringBodyBasic) {
  6753. TestStringBodyUploadProgress(
  6754. [](Server &svr) {
  6755. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6756. res.set_content("put received", "text/plain");
  6757. });
  6758. },
  6759. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6760. return cli.Put("/test", body, "text/plain", progress_callback);
  6761. },
  6762. "put test data for upload progress");
  6763. }
  6764. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6765. TestStringBodyUploadProgress(
  6766. [](Server &svr) {
  6767. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6768. res.set_content("patch received", "text/plain");
  6769. });
  6770. },
  6771. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6772. return cli.Patch("/test", body, "text/plain", progress_callback);
  6773. },
  6774. "patch test data for upload progress");
  6775. }
  6776. // Helper function for content provider upload progress tests
  6777. template <typename SetupHandler, typename ClientCall>
  6778. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6779. ClientCall &&client_call) {
  6780. Server svr;
  6781. setup_handler(svr);
  6782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6783. auto se = detail::scope_exit([&] {
  6784. svr.stop();
  6785. t.join();
  6786. });
  6787. svr.wait_until_ready();
  6788. Client cli(HOST, PORT);
  6789. vector<uint64_t> progress_values;
  6790. auto res =
  6791. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6792. progress_values.push_back(current);
  6793. return true;
  6794. });
  6795. ASSERT_TRUE(res);
  6796. EXPECT_EQ(200, res->status);
  6797. EXPECT_FALSE(progress_values.empty());
  6798. }
  6799. TEST(UploadProgressTest, PostContentProviderProgress) {
  6800. TestContentProviderUploadProgress(
  6801. [](Server &svr) {
  6802. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6803. res.set_content("provider received", "text/plain");
  6804. });
  6805. },
  6806. [](Client &cli, UploadProgress progress_callback) {
  6807. return cli.Post(
  6808. "/test", 10,
  6809. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6810. sink.os << "test data";
  6811. return true;
  6812. },
  6813. "text/plain", progress_callback);
  6814. });
  6815. }
  6816. // Helper function for multipart upload progress tests
  6817. template <typename SetupHandler, typename ClientCall>
  6818. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6819. ClientCall &&client_call,
  6820. const string &endpoint) {
  6821. Server svr;
  6822. setup_handler(svr);
  6823. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6824. auto se = detail::scope_exit([&] {
  6825. svr.stop();
  6826. t.join();
  6827. });
  6828. svr.wait_until_ready();
  6829. Client cli(HOST, PORT);
  6830. vector<uint64_t> progress_values;
  6831. UploadFormDataItems items = {
  6832. {"field1", "value1", "", ""},
  6833. {"field2", "longer value for progress tracking test", "", ""},
  6834. {"file1", "file content data for upload progress", "test.txt",
  6835. "text/plain"}};
  6836. auto res = client_call(cli, endpoint, items,
  6837. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6838. progress_values.push_back(current);
  6839. return true;
  6840. });
  6841. ASSERT_TRUE(res);
  6842. EXPECT_EQ(200, res->status);
  6843. EXPECT_FALSE(progress_values.empty());
  6844. }
  6845. TEST(UploadProgressTest, PostMultipartProgress) {
  6846. TestMultipartUploadProgress(
  6847. [](Server &svr) {
  6848. svr.Post("/multipart", [](const Request &req, Response &res) {
  6849. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6850. res.set_content("multipart received", "text/plain");
  6851. });
  6852. },
  6853. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6854. UploadProgress progress_callback) {
  6855. return cli.Post(endpoint, items, progress_callback);
  6856. },
  6857. "/multipart");
  6858. }
  6859. // Helper function for basic download progress tests
  6860. template <typename SetupHandler, typename ClientCall>
  6861. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6862. ClientCall &&client_call, const string &endpoint,
  6863. size_t expected_content_size) {
  6864. Server svr;
  6865. setup_handler(svr);
  6866. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6867. auto se = detail::scope_exit([&] {
  6868. svr.stop();
  6869. t.join();
  6870. });
  6871. svr.wait_until_ready();
  6872. Client cli(HOST, PORT);
  6873. vector<uint64_t> progress_values;
  6874. auto res = client_call(cli, endpoint,
  6875. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6876. progress_values.push_back(current);
  6877. return true;
  6878. });
  6879. ASSERT_TRUE(res);
  6880. EXPECT_EQ(200, res->status);
  6881. EXPECT_FALSE(progress_values.empty());
  6882. EXPECT_EQ(expected_content_size, res->body.size());
  6883. }
  6884. TEST(DownloadProgressTest, GetBasic) {
  6885. TestBasicDownloadProgress(
  6886. [](Server &svr) {
  6887. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6888. string content(1000, 'D');
  6889. res.set_content(content, "text/plain");
  6890. });
  6891. },
  6892. [](Client &cli, const string &endpoint,
  6893. DownloadProgress progress_callback) {
  6894. return cli.Get(endpoint, progress_callback);
  6895. },
  6896. "/download", 1000u);
  6897. }
  6898. // Helper function for content receiver download progress tests
  6899. template <typename SetupHandler, typename ClientCall>
  6900. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6901. ClientCall &&client_call,
  6902. const string &endpoint,
  6903. size_t expected_content_size) {
  6904. Server svr;
  6905. setup_handler(svr);
  6906. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6907. auto se = detail::scope_exit([&] {
  6908. svr.stop();
  6909. t.join();
  6910. });
  6911. svr.wait_until_ready();
  6912. Client cli(HOST, PORT);
  6913. vector<uint64_t> progress_values;
  6914. string received_body;
  6915. auto res = client_call(
  6916. cli, endpoint,
  6917. [&](const char *data, size_t data_length) -> bool {
  6918. received_body.append(data, data_length);
  6919. return true;
  6920. },
  6921. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6922. progress_values.push_back(current);
  6923. return true;
  6924. });
  6925. ASSERT_TRUE(res);
  6926. EXPECT_EQ(200, res->status);
  6927. EXPECT_FALSE(progress_values.empty());
  6928. EXPECT_EQ(expected_content_size, received_body.size());
  6929. EXPECT_TRUE(res->body.empty());
  6930. }
  6931. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6932. TestContentReceiverDownloadProgress(
  6933. [](Server &svr) {
  6934. svr.Get("/download-receiver",
  6935. [](const Request & /*req*/, Response &res) {
  6936. string content(2000, 'R');
  6937. res.set_content(content, "text/plain");
  6938. });
  6939. },
  6940. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6941. DownloadProgress progress_callback) {
  6942. return cli.Get(endpoint, content_receiver, progress_callback);
  6943. },
  6944. "/download-receiver", 2000u);
  6945. }
  6946. TEST(StreamingTest, NoContentLengthStreaming) {
  6947. Server svr;
  6948. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6949. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6950. if (offset < 6) {
  6951. sink.os << (offset < 3 ? "a" : "b");
  6952. } else {
  6953. sink.done();
  6954. }
  6955. return true;
  6956. });
  6957. });
  6958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6959. auto listen_se = detail::scope_exit([&] {
  6960. svr.stop();
  6961. listen_thread.join();
  6962. ASSERT_FALSE(svr.is_running());
  6963. });
  6964. svr.wait_until_ready();
  6965. Client client(HOST, PORT);
  6966. auto get_thread = std::thread([&client]() {
  6967. std::string s;
  6968. auto res =
  6969. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6970. s += std::string(data, len);
  6971. return true;
  6972. });
  6973. ASSERT_TRUE(res);
  6974. EXPECT_EQ(StatusCode::OK_200, res->status);
  6975. EXPECT_EQ("aaabbb", s);
  6976. });
  6977. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6978. // Give GET time to get a few messages.
  6979. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6980. }
  6981. TEST(MountTest, Unmount) {
  6982. Server svr;
  6983. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6984. auto se = detail::scope_exit([&] {
  6985. svr.stop();
  6986. listen_thread.join();
  6987. ASSERT_FALSE(svr.is_running());
  6988. });
  6989. svr.wait_until_ready();
  6990. Client cli("localhost", PORT);
  6991. svr.set_mount_point("/mount2", "./www2");
  6992. auto res = cli.Get("/");
  6993. ASSERT_TRUE(res);
  6994. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6995. res = cli.Get("/mount2/dir/test.html");
  6996. ASSERT_TRUE(res);
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. svr.set_mount_point("/", "./www");
  6999. res = cli.Get("/dir/");
  7000. ASSERT_TRUE(res);
  7001. EXPECT_EQ(StatusCode::OK_200, res->status);
  7002. svr.remove_mount_point("/");
  7003. res = cli.Get("/dir/");
  7004. ASSERT_TRUE(res);
  7005. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7006. svr.remove_mount_point("/mount2");
  7007. res = cli.Get("/mount2/dir/test.html");
  7008. ASSERT_TRUE(res);
  7009. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7010. }
  7011. TEST(MountTest, Redicect) {
  7012. Server svr;
  7013. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7014. auto se = detail::scope_exit([&] {
  7015. svr.stop();
  7016. listen_thread.join();
  7017. ASSERT_FALSE(svr.is_running());
  7018. });
  7019. svr.set_mount_point("/", "./www");
  7020. svr.wait_until_ready();
  7021. Client cli("localhost", PORT);
  7022. auto res = cli.Get("/dir/");
  7023. ASSERT_TRUE(res);
  7024. EXPECT_EQ(StatusCode::OK_200, res->status);
  7025. res = cli.Get("/dir");
  7026. ASSERT_TRUE(res);
  7027. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7028. res = cli.Get("/file");
  7029. ASSERT_TRUE(res);
  7030. EXPECT_EQ(StatusCode::OK_200, res->status);
  7031. res = cli.Get("/file/");
  7032. ASSERT_TRUE(res);
  7033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7034. cli.set_follow_location(true);
  7035. res = cli.Get("/dir");
  7036. ASSERT_TRUE(res);
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. }
  7039. TEST(MountTest, MultibytesPathName) {
  7040. Server svr;
  7041. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7042. auto se = detail::scope_exit([&] {
  7043. svr.stop();
  7044. listen_thread.join();
  7045. ASSERT_FALSE(svr.is_running());
  7046. });
  7047. svr.set_mount_point("/", "./www");
  7048. svr.wait_until_ready();
  7049. Client cli("localhost", PORT);
  7050. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7051. ASSERT_TRUE(res);
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7054. }
  7055. #ifdef _WIN32
  7056. // Issue #2435: mmap::open() must succeed even when another handle holds
  7057. // the file open for writing (e.g. an active log file).
  7058. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7059. const char *path = "mmap_concurrent_writer_test.txt";
  7060. const char *content = "hello";
  7061. {
  7062. std::ofstream f(path, std::ios::binary);
  7063. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7064. }
  7065. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7066. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7067. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7068. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7069. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7070. detail::mmap m(path);
  7071. ASSERT_TRUE(m.is_open());
  7072. EXPECT_EQ(strlen(content), m.size());
  7073. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7074. }
  7075. #endif
  7076. TEST(KeepAliveTest, ReadTimeout) {
  7077. Server svr;
  7078. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7079. std::this_thread::sleep_for(std::chrono::seconds(2));
  7080. res.set_content("a", "text/plain");
  7081. });
  7082. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7083. res.set_content("b", "text/plain");
  7084. });
  7085. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7086. auto se = detail::scope_exit([&] {
  7087. svr.stop();
  7088. listen_thread.join();
  7089. ASSERT_FALSE(svr.is_running());
  7090. });
  7091. svr.wait_until_ready();
  7092. Client cli("localhost", PORT);
  7093. cli.set_keep_alive(true);
  7094. cli.set_read_timeout(std::chrono::seconds(1));
  7095. auto resa = cli.Get("/a");
  7096. ASSERT_FALSE(resa);
  7097. EXPECT_EQ(Error::Read, resa.error());
  7098. auto resb = cli.Get("/b");
  7099. ASSERT_TRUE(resb);
  7100. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7101. EXPECT_EQ("b", resb->body);
  7102. }
  7103. TEST(KeepAliveTest, MaxCount) {
  7104. size_t keep_alive_max_count = 3;
  7105. Server svr;
  7106. svr.set_keep_alive_max_count(keep_alive_max_count);
  7107. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7108. res.set_content("Hello World!", "text/plain");
  7109. });
  7110. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7111. auto se = detail::scope_exit([&] {
  7112. svr.stop();
  7113. listen_thread.join();
  7114. ASSERT_FALSE(svr.is_running());
  7115. });
  7116. svr.wait_until_ready();
  7117. Client cli(HOST, PORT);
  7118. cli.set_keep_alive(true);
  7119. for (size_t i = 0; i < 5; i++) {
  7120. auto result = cli.Get("/hi");
  7121. ASSERT_TRUE(result);
  7122. EXPECT_EQ(StatusCode::OK_200, result->status);
  7123. if (i == keep_alive_max_count - 1) {
  7124. EXPECT_EQ("close", result->get_header_value("Connection"));
  7125. } else {
  7126. EXPECT_FALSE(result->has_header("Connection"));
  7127. }
  7128. }
  7129. }
  7130. TEST(KeepAliveTest, Issue1041) {
  7131. Server svr;
  7132. svr.set_keep_alive_timeout(3);
  7133. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7134. res.set_content("Hello World!", "text/plain");
  7135. });
  7136. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7137. auto se = detail::scope_exit([&] {
  7138. svr.stop();
  7139. listen_thread.join();
  7140. ASSERT_FALSE(svr.is_running());
  7141. });
  7142. svr.wait_until_ready();
  7143. Client cli(HOST, PORT);
  7144. cli.set_keep_alive(true);
  7145. auto result = cli.Get("/hi");
  7146. ASSERT_TRUE(result);
  7147. EXPECT_EQ(StatusCode::OK_200, result->status);
  7148. std::this_thread::sleep_for(std::chrono::seconds(5));
  7149. result = cli.Get("/hi");
  7150. ASSERT_TRUE(result);
  7151. EXPECT_EQ(StatusCode::OK_200, result->status);
  7152. }
  7153. TEST(KeepAliveTest, Issue1959) {
  7154. Server svr;
  7155. svr.set_keep_alive_timeout(5);
  7156. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7157. res.set_content("a", "text/plain");
  7158. });
  7159. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7160. auto se = detail::scope_exit([&] {
  7161. if (!svr.is_running()) return;
  7162. svr.stop();
  7163. listen_thread.join();
  7164. ASSERT_FALSE(svr.is_running());
  7165. });
  7166. svr.wait_until_ready();
  7167. Client cli("localhost", PORT);
  7168. cli.set_keep_alive(true);
  7169. using namespace std::chrono;
  7170. auto start = steady_clock::now();
  7171. cli.Get("/a");
  7172. svr.stop();
  7173. listen_thread.join();
  7174. auto end = steady_clock::now();
  7175. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7176. EXPECT_LT(elapsed, 5000);
  7177. }
  7178. #ifdef CPPHTTPLIB_SSL_ENABLED
  7179. TEST(KeepAliveTest, SSLClientReconnection) {
  7180. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7181. ASSERT_TRUE(svr.is_valid());
  7182. svr.set_keep_alive_timeout(1);
  7183. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7184. res.set_content("Hello World!", "text/plain");
  7185. });
  7186. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7187. auto se = detail::scope_exit([&] {
  7188. svr.stop();
  7189. listen_thread.join();
  7190. ASSERT_FALSE(svr.is_running());
  7191. });
  7192. svr.wait_until_ready();
  7193. SSLClient cli(HOST, PORT);
  7194. cli.enable_server_certificate_verification(false);
  7195. cli.set_keep_alive(true);
  7196. auto result = cli.Get("/hi");
  7197. ASSERT_TRUE(result);
  7198. EXPECT_EQ(StatusCode::OK_200, result->status);
  7199. result = cli.Get("/hi");
  7200. ASSERT_TRUE(result);
  7201. EXPECT_EQ(StatusCode::OK_200, result->status);
  7202. std::this_thread::sleep_for(std::chrono::seconds(2));
  7203. // Recoonect
  7204. result = cli.Get("/hi");
  7205. ASSERT_TRUE(result);
  7206. EXPECT_EQ(StatusCode::OK_200, result->status);
  7207. result = cli.Get("/hi");
  7208. ASSERT_TRUE(result);
  7209. EXPECT_EQ(StatusCode::OK_200, result->status);
  7210. }
  7211. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7213. ASSERT_TRUE(svr.is_valid());
  7214. svr.set_keep_alive_timeout(1);
  7215. std::string content = "reconnect";
  7216. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7217. res.set_content("Hello World!", "text/plain");
  7218. });
  7219. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7220. auto se = detail::scope_exit([&] {
  7221. svr.stop();
  7222. listen_thread.join();
  7223. ASSERT_FALSE(svr.is_running());
  7224. });
  7225. svr.wait_until_ready();
  7226. SSLClient cli(HOST, PORT);
  7227. cli.enable_server_certificate_verification(false);
  7228. cli.set_keep_alive(true);
  7229. auto result = cli.Post(
  7230. "/hi", content.size(),
  7231. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7232. sink.write(content.c_str(), content.size());
  7233. return true;
  7234. },
  7235. "text/plain");
  7236. ASSERT_TRUE(result);
  7237. EXPECT_EQ(200, result->status);
  7238. std::this_thread::sleep_for(std::chrono::seconds(2));
  7239. // Recoonect
  7240. result = cli.Post(
  7241. "/hi", content.size(),
  7242. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7243. sink.write(content.c_str(), content.size());
  7244. return true;
  7245. },
  7246. "text/plain");
  7247. ASSERT_TRUE(result);
  7248. EXPECT_EQ(200, result->status);
  7249. result = cli.Post(
  7250. "/hi", content.size(),
  7251. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7252. sink.write(content.c_str(), content.size());
  7253. return true;
  7254. },
  7255. "text/plain");
  7256. ASSERT_TRUE(result);
  7257. EXPECT_EQ(200, result->status);
  7258. }
  7259. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7260. using namespace httplib::tls;
  7261. {
  7262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7263. ASSERT_TRUE(svr.is_valid());
  7264. svr.Get("/sni", [&](const Request &req, Response &res) {
  7265. std::string expected = req.sni();
  7266. EXPECT_EQ(expected, req.get_param_value("expected"));
  7267. res.set_content("ok", "text/plain");
  7268. });
  7269. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7270. auto se = detail::scope_exit([&] {
  7271. svr.stop();
  7272. listen_thread.join();
  7273. ASSERT_FALSE(svr.is_running());
  7274. });
  7275. svr.wait_until_ready();
  7276. {
  7277. SSLClient cli("localhost", PORT);
  7278. cli.enable_server_certificate_verification(false);
  7279. auto res = cli.Get("/sni?expected=localhost");
  7280. ASSERT_TRUE(res);
  7281. }
  7282. {
  7283. SSLClient cli("::1", PORT);
  7284. cli.enable_server_certificate_verification(false);
  7285. auto res = cli.Get("/sni?expected=");
  7286. // NOTE: This may fail if the server is listening on IPv4 only
  7287. // (e.g., when localhost resolves to 127.0.0.1 only)
  7288. if (res) {
  7289. EXPECT_EQ(StatusCode::OK_200, res->status);
  7290. } else {
  7291. EXPECT_EQ(Error::Connection, res.error());
  7292. }
  7293. }
  7294. }
  7295. }
  7296. #endif
  7297. TEST(ClientProblemDetectionTest, ContentProvider) {
  7298. Server svr;
  7299. size_t content_length = 1024 * 1024;
  7300. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7301. res.set_content_provider(
  7302. content_length, "text/plain",
  7303. [&](size_t offset, size_t length, DataSink &sink) {
  7304. auto out_len = std::min(length, static_cast<size_t>(1024));
  7305. std::string out(out_len, '@');
  7306. sink.write(out.data(), out_len);
  7307. return offset < 4096;
  7308. },
  7309. [](bool success) { ASSERT_FALSE(success); });
  7310. });
  7311. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7312. res.set_content_provider(
  7313. 0, "text/plain",
  7314. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7315. EXPECT_TRUE(false);
  7316. return true;
  7317. },
  7318. [](bool success) { ASSERT_FALSE(success); });
  7319. });
  7320. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7321. auto se = detail::scope_exit([&] {
  7322. svr.stop();
  7323. listen_thread.join();
  7324. ASSERT_FALSE(svr.is_running());
  7325. });
  7326. svr.wait_until_ready();
  7327. Client cli("localhost", PORT);
  7328. {
  7329. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7330. size_t /*data_length*/) { return false; });
  7331. ASSERT_FALSE(res);
  7332. }
  7333. {
  7334. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7335. size_t /*data_length*/) { return false; });
  7336. ASSERT_TRUE(res);
  7337. }
  7338. }
  7339. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7340. Server svr;
  7341. svr.set_error_handler([](Request const &, Response &res) -> void {
  7342. res.set_chunked_content_provider(
  7343. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7344. sink.os << "hello";
  7345. sink.os << "world";
  7346. sink.done();
  7347. return true;
  7348. });
  7349. });
  7350. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7351. auto se = detail::scope_exit([&] {
  7352. svr.stop();
  7353. listen_thread.join();
  7354. ASSERT_FALSE(svr.is_running());
  7355. });
  7356. svr.wait_until_ready();
  7357. Client cli("localhost", PORT);
  7358. auto res = cli.Get("/");
  7359. ASSERT_TRUE(res);
  7360. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7361. EXPECT_EQ("helloworld", res->body);
  7362. }
  7363. TEST(LongPollingTest, ClientCloseDetection) {
  7364. Server svr;
  7365. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7366. res.set_chunked_content_provider(
  7367. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7368. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7369. sink.os << "hello";
  7370. auto count = 10;
  7371. while (count > 0 && sink.is_writable()) {
  7372. this_thread::sleep_for(chrono::milliseconds(10));
  7373. count--;
  7374. }
  7375. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7376. return true;
  7377. });
  7378. });
  7379. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7380. auto se = detail::scope_exit([&] {
  7381. svr.stop();
  7382. listen_thread.join();
  7383. ASSERT_FALSE(svr.is_running());
  7384. });
  7385. svr.wait_until_ready();
  7386. Client cli("localhost", PORT);
  7387. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7388. EXPECT_EQ("hello", string(data, data_length));
  7389. return false; // close the socket immediately.
  7390. });
  7391. ASSERT_FALSE(res);
  7392. }
  7393. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7394. Server svr;
  7395. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7396. res.set_chunked_content_provider(
  7397. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7398. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7399. sink.os << "hello";
  7400. EXPECT_TRUE(sink.os.good());
  7401. // Wait for the client to close the connection
  7402. auto count = 10;
  7403. while (count > 0 && sink.is_writable()) {
  7404. this_thread::sleep_for(chrono::milliseconds(10));
  7405. count--;
  7406. }
  7407. // After client disconnect, write repeatedly until the socket
  7408. // write actually fails (small writes may be absorbed by the
  7409. // kernel buffer)
  7410. std::string chunk(1024, 'x');
  7411. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7412. sink.os << chunk;
  7413. }
  7414. EXPECT_TRUE(sink.os.fail());
  7415. return true;
  7416. });
  7417. });
  7418. auto port = svr.bind_to_any_port("localhost");
  7419. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7420. auto se = detail::scope_exit([&] {
  7421. svr.stop();
  7422. listen_thread.join();
  7423. ASSERT_FALSE(svr.is_running());
  7424. });
  7425. svr.wait_until_ready();
  7426. Client cli("localhost", port);
  7427. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7428. EXPECT_EQ("hello", string(data, data_length));
  7429. return false; // close the socket immediately.
  7430. });
  7431. ASSERT_FALSE(res);
  7432. }
  7433. TEST(GetWithParametersTest, GetWithParameters) {
  7434. Server svr;
  7435. svr.Get("/", [&](const Request &req, Response &) {
  7436. EXPECT_EQ("world", req.get_param_value("hello"));
  7437. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7438. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7439. });
  7440. svr.Get("/params", [&](const Request &req, Response &) {
  7441. EXPECT_EQ("world", req.get_param_value("hello"));
  7442. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7443. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7444. });
  7445. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7446. EXPECT_EQ("resource-id", req.matches[1]);
  7447. EXPECT_EQ("foo", req.get_param_value("param1"));
  7448. EXPECT_EQ("bar", req.get_param_value("param2"));
  7449. });
  7450. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7451. EXPECT_EQ("user-id", req.path_params.at("id"));
  7452. EXPECT_EQ("foo", req.get_param_value("param1"));
  7453. EXPECT_EQ("bar", req.get_param_value("param2"));
  7454. });
  7455. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7456. auto se = detail::scope_exit([&] {
  7457. svr.stop();
  7458. listen_thread.join();
  7459. ASSERT_FALSE(svr.is_running());
  7460. });
  7461. svr.wait_until_ready();
  7462. {
  7463. Client cli(HOST, PORT);
  7464. Params params;
  7465. params.emplace("hello", "world");
  7466. params.emplace("hello2", "world2");
  7467. params.emplace("hello3", "world3");
  7468. auto res = cli.Get("/", params, Headers{});
  7469. ASSERT_TRUE(res);
  7470. EXPECT_EQ(StatusCode::OK_200, res->status);
  7471. }
  7472. {
  7473. Client cli(HOST, PORT);
  7474. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7475. ASSERT_TRUE(res);
  7476. EXPECT_EQ(StatusCode::OK_200, res->status);
  7477. }
  7478. {
  7479. Client cli(HOST, PORT);
  7480. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7481. ASSERT_TRUE(res);
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. }
  7484. {
  7485. Client cli(HOST, PORT);
  7486. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7487. ASSERT_TRUE(res);
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. }
  7491. TEST(GetWithParametersTest, GetWithParameters2) {
  7492. Server svr;
  7493. svr.Get("/", [&](const Request &req, Response &res) {
  7494. auto text = req.get_param_value("hello");
  7495. res.set_content(text, "text/plain");
  7496. });
  7497. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7498. auto se = detail::scope_exit([&] {
  7499. svr.stop();
  7500. listen_thread.join();
  7501. ASSERT_FALSE(svr.is_running());
  7502. });
  7503. svr.wait_until_ready();
  7504. Client cli("localhost", PORT);
  7505. Params params;
  7506. params.emplace("hello", "world");
  7507. std::string body;
  7508. auto res = cli.Get("/", params, Headers{},
  7509. [&](const char *data, size_t data_length) {
  7510. body.append(data, data_length);
  7511. return true;
  7512. });
  7513. ASSERT_TRUE(res);
  7514. EXPECT_EQ(StatusCode::OK_200, res->status);
  7515. EXPECT_EQ("world", body);
  7516. }
  7517. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7518. auto host = "httpbingo.org";
  7519. auto path = std::string{"/range/32"};
  7520. #ifdef CPPHTTPLIB_SSL_ENABLED
  7521. SSLClient cli(host);
  7522. #else
  7523. Client cli(host);
  7524. #endif
  7525. cli.set_default_headers({make_range_header({{1, 10}})});
  7526. cli.set_connection_timeout(5);
  7527. {
  7528. auto res = cli.Get(path);
  7529. ASSERT_TRUE(res);
  7530. EXPECT_EQ("bcdefghijk", res->body);
  7531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7532. }
  7533. {
  7534. auto res = cli.Get(path);
  7535. ASSERT_TRUE(res);
  7536. EXPECT_EQ("bcdefghijk", res->body);
  7537. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7538. }
  7539. }
  7540. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7541. Server svr;
  7542. svr.set_default_headers({{"Hello", "World"}});
  7543. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7544. res.set_content("ok", "text/plain");
  7545. });
  7546. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7547. auto se = detail::scope_exit([&] {
  7548. svr.stop();
  7549. listen_thread.join();
  7550. ASSERT_FALSE(svr.is_running());
  7551. });
  7552. svr.wait_until_ready();
  7553. Client cli("localhost", PORT);
  7554. auto res = cli.Get("/");
  7555. ASSERT_TRUE(res);
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ("ok", res->body);
  7558. EXPECT_EQ("World", res->get_header_value("Hello"));
  7559. }
  7560. #ifdef CPPHTTPLIB_SSL_ENABLED
  7561. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7563. ASSERT_TRUE(svr.is_valid());
  7564. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7565. std::this_thread::sleep_for(std::chrono::seconds(2));
  7566. res.set_content("a", "text/plain");
  7567. });
  7568. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7569. res.set_content("b", "text/plain");
  7570. });
  7571. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7572. auto se = detail::scope_exit([&] {
  7573. svr.stop();
  7574. listen_thread.join();
  7575. ASSERT_FALSE(svr.is_running());
  7576. });
  7577. svr.wait_until_ready();
  7578. SSLClient cli("localhost", PORT);
  7579. cli.enable_server_certificate_verification(false);
  7580. cli.set_keep_alive(true);
  7581. cli.set_read_timeout(std::chrono::seconds(1));
  7582. auto resa = cli.Get("/a");
  7583. ASSERT_TRUE(!resa);
  7584. EXPECT_EQ(Error::Read, resa.error());
  7585. auto resb = cli.Get("/b");
  7586. ASSERT_TRUE(resb);
  7587. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7588. EXPECT_EQ("b", resb->body);
  7589. }
  7590. #endif
  7591. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7592. protected:
  7593. ServerTestWithAI_PASSIVE()
  7594. : cli_(HOST, PORT)
  7595. #ifdef CPPHTTPLIB_SSL_ENABLED
  7596. ,
  7597. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7598. #endif
  7599. {
  7600. #ifdef CPPHTTPLIB_SSL_ENABLED
  7601. cli_.enable_server_certificate_verification(false);
  7602. #endif
  7603. }
  7604. virtual void SetUp() {
  7605. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7606. res.set_content("Hello World!", "text/plain");
  7607. });
  7608. t_ = thread(
  7609. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7610. svr_.wait_until_ready();
  7611. }
  7612. virtual void TearDown() {
  7613. svr_.stop();
  7614. t_.join();
  7615. }
  7616. #ifdef CPPHTTPLIB_SSL_ENABLED
  7617. SSLClient cli_;
  7618. SSLServer svr_;
  7619. #else
  7620. Client cli_;
  7621. Server svr_;
  7622. #endif
  7623. thread t_;
  7624. };
  7625. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7626. auto res = cli_.Get("/hi");
  7627. ASSERT_TRUE(res);
  7628. EXPECT_EQ(StatusCode::OK_200, res->status);
  7629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7630. EXPECT_EQ("Hello World!", res->body);
  7631. }
  7632. class ServerUpDownTest : public ::testing::Test {
  7633. protected:
  7634. ServerUpDownTest() : cli_(HOST, PORT) {}
  7635. virtual void SetUp() {
  7636. t_ = thread([&]() {
  7637. svr_.bind_to_any_port(HOST);
  7638. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7639. ASSERT_TRUE(svr_.listen_after_bind());
  7640. });
  7641. svr_.wait_until_ready();
  7642. }
  7643. virtual void TearDown() {
  7644. svr_.stop();
  7645. t_.join();
  7646. }
  7647. Client cli_;
  7648. Server svr_;
  7649. thread t_;
  7650. };
  7651. TEST_F(ServerUpDownTest, QuickStartStop) {
  7652. // Should not crash, especially when run with
  7653. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7654. }
  7655. class PayloadMaxLengthTest : public ::testing::Test {
  7656. protected:
  7657. PayloadMaxLengthTest()
  7658. : cli_(HOST, PORT)
  7659. #ifdef CPPHTTPLIB_SSL_ENABLED
  7660. ,
  7661. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7662. #endif
  7663. {
  7664. #ifdef CPPHTTPLIB_SSL_ENABLED
  7665. cli_.enable_server_certificate_verification(false);
  7666. #endif
  7667. }
  7668. virtual void SetUp() {
  7669. svr_.set_payload_max_length(8);
  7670. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7671. res.set_content("test", "text/plain");
  7672. });
  7673. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7674. svr_.wait_until_ready();
  7675. }
  7676. virtual void TearDown() {
  7677. svr_.stop();
  7678. t_.join();
  7679. }
  7680. #ifdef CPPHTTPLIB_SSL_ENABLED
  7681. SSLClient cli_;
  7682. SSLServer svr_;
  7683. #else
  7684. Client cli_;
  7685. Server svr_;
  7686. #endif
  7687. thread t_;
  7688. };
  7689. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7690. auto res = cli_.Post("/test", "123456789", "text/plain");
  7691. ASSERT_TRUE(res);
  7692. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7693. res = cli_.Post("/test", "12345678", "text/plain");
  7694. ASSERT_TRUE(res);
  7695. EXPECT_EQ(StatusCode::OK_200, res->status);
  7696. }
  7697. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7698. // Test chunked encoding with payload exceeding the 8-byte limit
  7699. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7700. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7701. ASSERT_TRUE(res);
  7702. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7703. }
  7704. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7705. // Test chunked encoding with payload within the 8-byte limit
  7706. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7707. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7708. ASSERT_TRUE(res);
  7709. EXPECT_EQ(StatusCode::OK_200, res->status);
  7710. }
  7711. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7712. // Test using send_request to send chunked data exceeding payload limit
  7713. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7714. "Host: " +
  7715. std::string(HOST) + ":" + std::to_string(PORT) +
  7716. "\r\n"
  7717. "Transfer-Encoding: chunked\r\n"
  7718. "Connection: close\r\n"
  7719. "\r\n"
  7720. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7721. "0123456789\r\n"
  7722. "0\r\n" // End chunk
  7723. "\r\n";
  7724. std::string response;
  7725. bool result = send_request(1, chunked_request, &response);
  7726. if (!result) {
  7727. // If send_request fails, it might be because the server closed the
  7728. // connection due to payload limit enforcement, which is acceptable
  7729. SUCCEED()
  7730. << "Server rejected oversized chunked request (connection closed)";
  7731. } else {
  7732. // If we got a response, check if it's an error response or connection was
  7733. // closed early Short response length indicates connection was closed due to
  7734. // payload limit
  7735. if (response.length() <= 10) {
  7736. SUCCEED() << "Server closed connection for oversized chunked request";
  7737. } else {
  7738. // Check for error status codes
  7739. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7740. response.find("Payload Too Large") != std::string::npos ||
  7741. response.find("400") != std::string::npos);
  7742. }
  7743. }
  7744. }
  7745. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7746. // Test request without Content-Length header exceeding payload limit
  7747. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7748. "Host: " +
  7749. std::string(HOST) + ":" +
  7750. std::to_string(PORT) +
  7751. "\r\n"
  7752. "Connection: close\r\n"
  7753. "\r\n";
  7754. // Add payload exceeding the 8-byte limit
  7755. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7756. request_without_content_length += large_payload;
  7757. std::string response;
  7758. bool result = send_request(1, request_without_content_length, &response);
  7759. if (!result) {
  7760. // If send_request fails, server likely closed connection due to payload
  7761. // limit
  7762. SUCCEED() << "Server rejected oversized request without Content-Length "
  7763. "(connection closed)";
  7764. } else {
  7765. // Check if server responded with error or closed connection early
  7766. if (response.length() <= 10) {
  7767. SUCCEED() << "Server closed connection for oversized request without "
  7768. "Content-Length";
  7769. } else {
  7770. // Check for error status codes
  7771. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7772. response.find("Payload Too Large") != std::string::npos ||
  7773. response.find("400") != std::string::npos);
  7774. }
  7775. }
  7776. }
  7777. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7778. // Test request without Content-Length header within payload limit
  7779. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7780. "Host: " +
  7781. std::string(HOST) + ":" +
  7782. std::to_string(PORT) +
  7783. "\r\n"
  7784. "Connection: close\r\n"
  7785. "\r\n";
  7786. // Add payload within the 8-byte limit
  7787. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7788. request_without_content_length += small_payload;
  7789. std::string response;
  7790. bool result = send_request(1, request_without_content_length, &response);
  7791. // For requests without Content-Length, the server may have different behavior
  7792. // The key is that it should not reject due to payload limit for small
  7793. // payloads
  7794. if (result) {
  7795. // Check for any HTTP response (success or error, but not connection closed)
  7796. if (response.length() > 10) {
  7797. SUCCEED()
  7798. << "Server processed request without Content-Length within limit";
  7799. } else {
  7800. // Short response might indicate connection closed, which is acceptable
  7801. SUCCEED() << "Server closed connection for request without "
  7802. "Content-Length (acceptable behavior)";
  7803. }
  7804. } else {
  7805. // Connection failure might be due to protocol requirements
  7806. SUCCEED() << "Connection issue with request without Content-Length "
  7807. "(environment-specific)";
  7808. }
  7809. }
  7810. class LargePayloadMaxLengthTest : public ::testing::Test {
  7811. protected:
  7812. LargePayloadMaxLengthTest()
  7813. : cli_(HOST, PORT)
  7814. #ifdef CPPHTTPLIB_SSL_ENABLED
  7815. ,
  7816. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7817. #endif
  7818. {
  7819. #ifdef CPPHTTPLIB_SSL_ENABLED
  7820. cli_.enable_server_certificate_verification(false);
  7821. #endif
  7822. }
  7823. virtual void SetUp() {
  7824. // Set 10MB payload limit
  7825. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7826. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7827. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7828. res.set_content("Large payload test", "text/plain");
  7829. });
  7830. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7831. svr_.wait_until_ready();
  7832. }
  7833. virtual void TearDown() {
  7834. svr_.stop();
  7835. t_.join();
  7836. }
  7837. #ifdef CPPHTTPLIB_SSL_ENABLED
  7838. SSLClient cli_;
  7839. SSLServer svr_;
  7840. #else
  7841. Client cli_;
  7842. Server svr_;
  7843. #endif
  7844. thread t_;
  7845. };
  7846. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7847. // Test chunked encoding with payload within 10MB limit
  7848. std::string medium_payload(5 * 1024 * 1024,
  7849. 'A'); // 5MB payload, within 10MB limit
  7850. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7851. ASSERT_TRUE(res);
  7852. EXPECT_EQ(StatusCode::OK_200, res->status);
  7853. }
  7854. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7855. // Test chunked encoding with payload exceeding 10MB limit
  7856. std::string large_payload(12 * 1024 * 1024,
  7857. 'B'); // 12MB payload, exceeds 10MB limit
  7858. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7859. // Server may either return 413 or close the connection
  7860. if (res) {
  7861. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7862. } else {
  7863. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7864. }
  7865. }
  7866. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7867. // Test request without Content-Length header within 10MB limit
  7868. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7869. "Host: " +
  7870. std::string(HOST) + ":" +
  7871. std::to_string(PORT) +
  7872. "\r\n"
  7873. "Connection: close\r\n"
  7874. "\r\n";
  7875. // Add 1MB payload (within 10MB limit)
  7876. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7877. request_without_content_length += medium_payload;
  7878. std::string response;
  7879. bool result = send_request(5, request_without_content_length, &response);
  7880. if (result) {
  7881. // Should get a proper HTTP response for payloads within limit
  7882. if (response.length() > 10) {
  7883. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7884. "10MB limit";
  7885. } else {
  7886. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7887. "Content-Length)";
  7888. }
  7889. } else {
  7890. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7891. }
  7892. }
  7893. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7894. // Test request without Content-Length header exceeding 10MB limit
  7895. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7896. "Host: " +
  7897. std::string(HOST) + ":" +
  7898. std::to_string(PORT) +
  7899. "\r\n"
  7900. "Connection: close\r\n"
  7901. "\r\n";
  7902. // Add 12MB payload (exceeds 10MB limit)
  7903. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7904. request_without_content_length += large_payload;
  7905. std::string response;
  7906. bool result = send_request(10, request_without_content_length, &response);
  7907. if (!result) {
  7908. // Server should close connection due to payload limit
  7909. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7910. "(connection closed)";
  7911. } else {
  7912. // Check for error response
  7913. if (response.length() <= 10) {
  7914. SUCCEED()
  7915. << "Server closed connection for 12MB request exceeding 10MB limit";
  7916. } else {
  7917. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7918. response.find("Payload Too Large") != std::string::npos ||
  7919. response.find("400") != std::string::npos);
  7920. }
  7921. }
  7922. }
  7923. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7924. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7925. // path.
  7926. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7927. Server svr;
  7928. const size_t LIMIT = 64 * 1024; // 64KB
  7929. svr.set_payload_max_length(LIMIT);
  7930. size_t total = 0;
  7931. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7932. const ContentReader &content_reader) {
  7933. content_reader([&](const char * /*data*/, size_t len) {
  7934. total += len;
  7935. return true;
  7936. });
  7937. res.status = 200;
  7938. res.set_content("stream_ok", "text/plain");
  7939. });
  7940. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7941. auto se = detail::scope_exit([&] {
  7942. svr.stop();
  7943. thread.join();
  7944. ASSERT_FALSE(svr.is_running());
  7945. });
  7946. svr.wait_until_ready();
  7947. // Prepare 256KB raw data and gzip-compress it
  7948. std::string raw(256 * 1024, 'A');
  7949. std::string gz;
  7950. {
  7951. z_stream zs{};
  7952. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7953. Z_DEFAULT_STRATEGY);
  7954. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7955. zs.avail_in = static_cast<uInt>(raw.size());
  7956. char outbuf[4096];
  7957. int ret;
  7958. do {
  7959. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7960. zs.avail_out = sizeof(outbuf);
  7961. ret = deflate(&zs, Z_FINISH);
  7962. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7963. } while (ret != Z_STREAM_END);
  7964. deflateEnd(&zs);
  7965. }
  7966. Client cli(HOST, PORT);
  7967. cli.set_connection_timeout(std::chrono::seconds(5));
  7968. Headers headers = {{"Content-Encoding", "gzip"}};
  7969. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7970. "application/octet-stream");
  7971. ASSERT_TRUE(res);
  7972. // Server must reject oversized decompressed payloads with 413.
  7973. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7974. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7975. EXPECT_LE(total, LIMIT);
  7976. }
  7977. #endif
  7978. // Regression test for DoS vulnerability: a malicious server sending a response
  7979. // without Content-Length header must not cause unbounded memory consumption on
  7980. // the client side. The client should stop reading after a reasonable limit,
  7981. // similar to the server-side set_payload_max_length protection.
  7982. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7983. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7984. #ifndef _WIN32
  7985. signal(SIGPIPE, SIG_IGN);
  7986. #endif
  7987. auto server_thread = std::thread([] {
  7988. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7989. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7990. default_socket_options(srv);
  7991. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7992. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7993. sockaddr_in addr{};
  7994. addr.sin_family = AF_INET;
  7995. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7996. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7997. int opt = 1;
  7998. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7999. #ifdef _WIN32
  8000. reinterpret_cast<const char *>(&opt),
  8001. #else
  8002. &opt,
  8003. #endif
  8004. sizeof(opt));
  8005. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8006. ::listen(srv, 1);
  8007. sockaddr_in cli_addr{};
  8008. socklen_t cli_len = sizeof(cli_addr);
  8009. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8010. if (cli != INVALID_SOCKET) {
  8011. char buf[4096];
  8012. ::recv(cli, buf, sizeof(buf), 0);
  8013. // Malicious response: no Content-Length, no chunked encoding
  8014. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8015. "Connection: close\r\n"
  8016. "\r\n";
  8017. ::send(cli,
  8018. #ifdef _WIN32
  8019. static_cast<const char *>(response_header.c_str()),
  8020. static_cast<int>(response_header.size()),
  8021. #else
  8022. response_header.c_str(), response_header.size(),
  8023. #endif
  8024. 0);
  8025. // Send 10MB of data
  8026. std::string chunk(64 * 1024, 'A');
  8027. size_t total_sent = 0;
  8028. while (total_sent < MALICIOUS_DATA_SIZE) {
  8029. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8030. auto sent = ::send(cli,
  8031. #ifdef _WIN32
  8032. static_cast<const char *>(chunk.c_str()),
  8033. static_cast<int>(to_send),
  8034. #else
  8035. chunk.c_str(), to_send,
  8036. #endif
  8037. 0);
  8038. if (sent <= 0) break;
  8039. total_sent += static_cast<size_t>(sent);
  8040. }
  8041. detail::close_socket(cli);
  8042. }
  8043. detail::close_socket(srv);
  8044. });
  8045. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8046. size_t total_read = 0;
  8047. {
  8048. Client cli("127.0.0.1", PORT + 2);
  8049. cli.set_read_timeout(5, 0);
  8050. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8051. auto stream = cli.open_stream("GET", "/malicious");
  8052. ASSERT_TRUE(stream.is_valid());
  8053. char buffer[64 * 1024];
  8054. ssize_t n;
  8055. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8056. total_read += static_cast<size_t>(n);
  8057. }
  8058. } // StreamHandle and Client destroyed here, closing the socket
  8059. server_thread.join();
  8060. // With set_payload_max_length, the client must stop reading before consuming
  8061. // all 10MB. The read loop should be cut off at or near the configured limit.
  8062. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8063. << "Client read " << total_read << " bytes, exceeding the configured "
  8064. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8065. }
  8066. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8067. // the entire response body without truncation.
  8068. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8069. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8070. #ifndef _WIN32
  8071. signal(SIGPIPE, SIG_IGN);
  8072. #endif
  8073. auto server_thread = std::thread([] {
  8074. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8075. default_socket_options(srv);
  8076. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8077. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8078. sockaddr_in addr{};
  8079. addr.sin_family = AF_INET;
  8080. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8081. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8082. int opt = 1;
  8083. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8084. #ifdef _WIN32
  8085. reinterpret_cast<const char *>(&opt),
  8086. #else
  8087. &opt,
  8088. #endif
  8089. sizeof(opt));
  8090. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8091. ::listen(srv, 1);
  8092. sockaddr_in cli_addr{};
  8093. socklen_t cli_len = sizeof(cli_addr);
  8094. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8095. if (cli != INVALID_SOCKET) {
  8096. char buf[4096];
  8097. ::recv(cli, buf, sizeof(buf), 0);
  8098. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8099. "Connection: close\r\n"
  8100. "\r\n";
  8101. ::send(cli,
  8102. #ifdef _WIN32
  8103. static_cast<const char *>(response_header.c_str()),
  8104. static_cast<int>(response_header.size()),
  8105. #else
  8106. response_header.c_str(), response_header.size(),
  8107. #endif
  8108. 0);
  8109. std::string chunk(64 * 1024, 'A');
  8110. size_t total_sent = 0;
  8111. while (total_sent < DATA_SIZE) {
  8112. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8113. auto sent = ::send(cli,
  8114. #ifdef _WIN32
  8115. static_cast<const char *>(chunk.c_str()),
  8116. static_cast<int>(to_send),
  8117. #else
  8118. chunk.c_str(), to_send,
  8119. #endif
  8120. 0);
  8121. if (sent <= 0) break;
  8122. total_sent += static_cast<size_t>(sent);
  8123. }
  8124. #ifdef _WIN32
  8125. ::shutdown(cli, SD_SEND);
  8126. #else
  8127. ::shutdown(cli, SHUT_WR);
  8128. #endif
  8129. // Drain until the client closes its end, ensuring all data is delivered
  8130. char drain[1024];
  8131. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8132. detail::close_socket(cli);
  8133. }
  8134. detail::close_socket(srv);
  8135. });
  8136. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8137. size_t total_read = 0;
  8138. {
  8139. Client cli("127.0.0.1", PORT + 2);
  8140. cli.set_read_timeout(5, 0);
  8141. cli.set_payload_max_length(0); // 0 means no limit
  8142. auto stream = cli.open_stream("GET", "/data");
  8143. ASSERT_TRUE(stream.is_valid());
  8144. char buffer[64 * 1024];
  8145. ssize_t n;
  8146. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8147. total_read += static_cast<size_t>(n);
  8148. }
  8149. }
  8150. server_thread.join();
  8151. EXPECT_EQ(total_read, DATA_SIZE)
  8152. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8153. << " bytes without truncation, but only read " << total_read << " bytes.";
  8154. }
  8155. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8156. // enormous Content-Length must not cause the client to pre-allocate a huge
  8157. // response body buffer. The reservation is capped at payload_max_length_, and
  8158. // the read itself fails when the body exceeds the limit.
  8159. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8160. #ifndef _WIN32
  8161. signal(SIGPIPE, SIG_IGN);
  8162. #endif
  8163. auto server_thread = std::thread([] {
  8164. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8165. default_socket_options(srv);
  8166. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8167. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8168. sockaddr_in addr{};
  8169. addr.sin_family = AF_INET;
  8170. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8171. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8172. int opt = 1;
  8173. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8174. #ifdef _WIN32
  8175. reinterpret_cast<const char *>(&opt),
  8176. #else
  8177. &opt,
  8178. #endif
  8179. sizeof(opt));
  8180. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8181. ::listen(srv, 1);
  8182. sockaddr_in cli_addr{};
  8183. socklen_t cli_len = sizeof(cli_addr);
  8184. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8185. if (cli != INVALID_SOCKET) {
  8186. char buf[4096];
  8187. ::recv(cli, buf, sizeof(buf), 0);
  8188. // Malicious response: claim a 20GB body but send only a tiny payload.
  8189. std::string response = "HTTP/1.1 200 OK\r\n"
  8190. "Content-Length: 20000000000\r\n"
  8191. "\r\n"
  8192. "abc";
  8193. ::send(cli,
  8194. #ifdef _WIN32
  8195. static_cast<const char *>(response.c_str()),
  8196. static_cast<int>(response.size()),
  8197. #else
  8198. response.c_str(), response.size(),
  8199. #endif
  8200. 0);
  8201. detail::close_socket(cli);
  8202. }
  8203. detail::close_socket(srv);
  8204. });
  8205. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8206. {
  8207. Client cli("127.0.0.1", PORT + 2);
  8208. cli.set_read_timeout(5, 0);
  8209. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8210. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8211. // (server claims more bytes than payload_max_length permits), but it must
  8212. // not exhaust memory before getting there.
  8213. auto res = cli.Get("/malicious");
  8214. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8215. }
  8216. server_thread.join();
  8217. }
  8218. // Verify that content_receiver bypasses the default payload_max_length,
  8219. // allowing streaming downloads larger than 100MB without requiring an explicit
  8220. // set_payload_max_length call.
  8221. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8222. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8223. #ifndef _WIN32
  8224. signal(SIGPIPE, SIG_IGN);
  8225. #endif
  8226. auto server_thread = std::thread([] {
  8227. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8228. default_socket_options(srv);
  8229. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8230. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8231. sockaddr_in addr{};
  8232. addr.sin_family = AF_INET;
  8233. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8234. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8235. int opt = 1;
  8236. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8237. #ifdef _WIN32
  8238. reinterpret_cast<const char *>(&opt),
  8239. #else
  8240. &opt,
  8241. #endif
  8242. sizeof(opt));
  8243. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8244. ::listen(srv, 1);
  8245. sockaddr_in cli_addr{};
  8246. socklen_t cli_len = sizeof(cli_addr);
  8247. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8248. if (cli != INVALID_SOCKET) {
  8249. char buf[4096];
  8250. ::recv(cli, buf, sizeof(buf), 0);
  8251. // Response with Content-Length larger than default 100MB limit
  8252. auto content_length = std::to_string(DATA_SIZE);
  8253. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8254. "Content-Length: " +
  8255. content_length +
  8256. "\r\n"
  8257. "Connection: close\r\n"
  8258. "\r\n";
  8259. ::send(cli,
  8260. #ifdef _WIN32
  8261. static_cast<const char *>(response_header.c_str()),
  8262. static_cast<int>(response_header.size()),
  8263. #else
  8264. response_header.c_str(), response_header.size(),
  8265. #endif
  8266. 0);
  8267. std::string chunk(64 * 1024, 'A');
  8268. size_t total_sent = 0;
  8269. while (total_sent < DATA_SIZE) {
  8270. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8271. auto sent = ::send(cli,
  8272. #ifdef _WIN32
  8273. static_cast<const char *>(chunk.c_str()),
  8274. static_cast<int>(to_send),
  8275. #else
  8276. chunk.c_str(), to_send,
  8277. #endif
  8278. 0);
  8279. if (sent <= 0) break;
  8280. total_sent += static_cast<size_t>(sent);
  8281. }
  8282. detail::close_socket(cli);
  8283. }
  8284. detail::close_socket(srv);
  8285. });
  8286. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8287. size_t total_received = 0;
  8288. {
  8289. Client cli("127.0.0.1", PORT + 2);
  8290. cli.set_read_timeout(10, 0);
  8291. // Do NOT call set_payload_max_length — use the default 100MB limit
  8292. auto res =
  8293. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8294. total_received += data_length;
  8295. return true;
  8296. });
  8297. ASSERT_TRUE(res);
  8298. EXPECT_EQ(StatusCode::OK_200, res->status);
  8299. }
  8300. server_thread.join();
  8301. EXPECT_EQ(total_received, DATA_SIZE)
  8302. << "With content_receiver, the client should read all " << DATA_SIZE
  8303. << " bytes despite the default 100MB payload_max_length, but only read "
  8304. << total_received << " bytes.";
  8305. }
  8306. // Verify that an explicit set_payload_max_length smaller than the response is
  8307. // enforced even when a content_receiver is used.
  8308. TEST(ClientVulnerabilityTest,
  8309. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8310. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8311. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8312. #ifndef _WIN32
  8313. signal(SIGPIPE, SIG_IGN);
  8314. #endif
  8315. auto server_thread = std::thread([] {
  8316. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8317. default_socket_options(srv);
  8318. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8319. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8320. sockaddr_in addr{};
  8321. addr.sin_family = AF_INET;
  8322. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8323. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8324. int opt = 1;
  8325. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8326. #ifdef _WIN32
  8327. reinterpret_cast<const char *>(&opt),
  8328. #else
  8329. &opt,
  8330. #endif
  8331. sizeof(opt));
  8332. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8333. ::listen(srv, 1);
  8334. sockaddr_in cli_addr{};
  8335. socklen_t cli_len = sizeof(cli_addr);
  8336. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8337. if (cli != INVALID_SOCKET) {
  8338. char buf[4096];
  8339. ::recv(cli, buf, sizeof(buf), 0);
  8340. auto content_length = std::to_string(DATA_SIZE);
  8341. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8342. "Content-Length: " +
  8343. content_length +
  8344. "\r\n"
  8345. "Connection: close\r\n"
  8346. "\r\n";
  8347. ::send(cli,
  8348. #ifdef _WIN32
  8349. static_cast<const char *>(response_header.c_str()),
  8350. static_cast<int>(response_header.size()),
  8351. #else
  8352. response_header.c_str(), response_header.size(),
  8353. #endif
  8354. 0);
  8355. std::string chunk(64 * 1024, 'A');
  8356. size_t total_sent = 0;
  8357. while (total_sent < DATA_SIZE) {
  8358. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8359. auto sent = ::send(cli,
  8360. #ifdef _WIN32
  8361. static_cast<const char *>(chunk.c_str()),
  8362. static_cast<int>(to_send),
  8363. #else
  8364. chunk.c_str(), to_send,
  8365. #endif
  8366. 0);
  8367. if (sent <= 0) break;
  8368. total_sent += static_cast<size_t>(sent);
  8369. }
  8370. detail::close_socket(cli);
  8371. }
  8372. detail::close_socket(srv);
  8373. });
  8374. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8375. size_t total_received = 0;
  8376. {
  8377. Client cli("127.0.0.1", PORT + 2);
  8378. cli.set_read_timeout(10, 0);
  8379. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8380. auto res =
  8381. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8382. total_received += data_length;
  8383. return true;
  8384. });
  8385. // Should fail because 200MB exceeds the explicit 150MB limit
  8386. EXPECT_FALSE(res);
  8387. }
  8388. server_thread.join();
  8389. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8390. << "Client with content_receiver should respect the explicit "
  8391. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8392. << total_received << " bytes.";
  8393. }
  8394. // Verify that an explicit set_payload_max_length larger than the response
  8395. // allows the content_receiver to read all data successfully.
  8396. TEST(ClientVulnerabilityTest,
  8397. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8398. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8399. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8400. #ifndef _WIN32
  8401. signal(SIGPIPE, SIG_IGN);
  8402. #endif
  8403. auto server_thread = std::thread([] {
  8404. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8405. default_socket_options(srv);
  8406. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8407. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8408. sockaddr_in addr{};
  8409. addr.sin_family = AF_INET;
  8410. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8411. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8412. int opt = 1;
  8413. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8414. #ifdef _WIN32
  8415. reinterpret_cast<const char *>(&opt),
  8416. #else
  8417. &opt,
  8418. #endif
  8419. sizeof(opt));
  8420. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8421. ::listen(srv, 1);
  8422. sockaddr_in cli_addr{};
  8423. socklen_t cli_len = sizeof(cli_addr);
  8424. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8425. if (cli != INVALID_SOCKET) {
  8426. char buf[4096];
  8427. ::recv(cli, buf, sizeof(buf), 0);
  8428. auto content_length = std::to_string(DATA_SIZE);
  8429. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8430. "Content-Length: " +
  8431. content_length +
  8432. "\r\n"
  8433. "Connection: close\r\n"
  8434. "\r\n";
  8435. ::send(cli,
  8436. #ifdef _WIN32
  8437. static_cast<const char *>(response_header.c_str()),
  8438. static_cast<int>(response_header.size()),
  8439. #else
  8440. response_header.c_str(), response_header.size(),
  8441. #endif
  8442. 0);
  8443. std::string chunk(64 * 1024, 'A');
  8444. size_t total_sent = 0;
  8445. while (total_sent < DATA_SIZE) {
  8446. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8447. auto sent = ::send(cli,
  8448. #ifdef _WIN32
  8449. static_cast<const char *>(chunk.c_str()),
  8450. static_cast<int>(to_send),
  8451. #else
  8452. chunk.c_str(), to_send,
  8453. #endif
  8454. 0);
  8455. if (sent <= 0) break;
  8456. total_sent += static_cast<size_t>(sent);
  8457. }
  8458. #ifdef _WIN32
  8459. ::shutdown(cli, SD_SEND);
  8460. #else
  8461. ::shutdown(cli, SHUT_WR);
  8462. #endif
  8463. char drain[1024];
  8464. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8465. detail::close_socket(cli);
  8466. }
  8467. detail::close_socket(srv);
  8468. });
  8469. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8470. size_t total_received = 0;
  8471. {
  8472. Client cli("127.0.0.1", PORT + 2);
  8473. cli.set_read_timeout(10, 0);
  8474. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8475. auto res =
  8476. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8477. total_received += data_length;
  8478. return true;
  8479. });
  8480. ASSERT_TRUE(res);
  8481. EXPECT_EQ(StatusCode::OK_200, res->status);
  8482. }
  8483. server_thread.join();
  8484. EXPECT_EQ(total_received, DATA_SIZE)
  8485. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8486. << " bytes (larger than " << DATA_SIZE
  8487. << " bytes response), content_receiver should read all data, but only "
  8488. "read "
  8489. << total_received << " bytes.";
  8490. }
  8491. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8492. // Regression test for "zip bomb" attack on the client side: a malicious server
  8493. // sends a small gzip-compressed response that decompresses to a huge payload.
  8494. // The client must enforce payload_max_length on the decompressed size.
  8495. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8496. constexpr size_t DECOMPRESSED_SIZE =
  8497. 10 * 1024 * 1024; // 10MB after decompression
  8498. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8499. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8500. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8501. std::string compressed;
  8502. {
  8503. httplib::detail::gzip_compressor compressor;
  8504. bool ok =
  8505. compressor.compress(uncompressed.data(), uncompressed.size(),
  8506. /*last=*/true, [&](const char *buf, size_t len) {
  8507. compressed.append(buf, len);
  8508. return true;
  8509. });
  8510. ASSERT_TRUE(ok);
  8511. }
  8512. // Sanity: compressed data should be much smaller than the decompressed size
  8513. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8514. #ifndef _WIN32
  8515. signal(SIGPIPE, SIG_IGN);
  8516. #endif
  8517. // Set up the listening socket in the main thread so the server is guaranteed
  8518. // to be ready before the client connects (eliminates race condition).
  8519. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8520. default_socket_options(srv);
  8521. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8522. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8523. sockaddr_in addr{};
  8524. addr.sin_family = AF_INET;
  8525. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8526. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8527. int opt = 1;
  8528. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8529. #ifdef _WIN32
  8530. reinterpret_cast<const char *>(&opt),
  8531. #else
  8532. &opt,
  8533. #endif
  8534. sizeof(opt));
  8535. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8536. ASSERT_EQ(0, ::listen(srv, 1));
  8537. auto server_thread = std::thread([&compressed, srv] {
  8538. sockaddr_in cli_addr{};
  8539. socklen_t cli_len = sizeof(cli_addr);
  8540. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8541. if (cli != INVALID_SOCKET) {
  8542. // Read the full HTTP request (until \r\n\r\n)
  8543. char buf[4096];
  8544. size_t total = 0;
  8545. while (total < sizeof(buf)) {
  8546. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8547. if (n <= 0) break;
  8548. total += static_cast<size_t>(n);
  8549. // Check for end of headers
  8550. if (total >= 4) {
  8551. std::string req(buf, total);
  8552. if (req.find("\r\n\r\n") != std::string::npos) break;
  8553. }
  8554. }
  8555. // Malicious response: gzip-compressed body, no Content-Length
  8556. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8557. "Content-Encoding: gzip\r\n"
  8558. "Connection: close\r\n"
  8559. "\r\n";
  8560. ::send(cli,
  8561. #ifdef _WIN32
  8562. static_cast<const char *>(response_header.c_str()),
  8563. static_cast<int>(response_header.size()),
  8564. #else
  8565. response_header.c_str(), response_header.size(),
  8566. #endif
  8567. 0);
  8568. // Send the compressed payload (small on the wire, huge when decompressed)
  8569. size_t total_sent = 0;
  8570. while (total_sent < compressed.size()) {
  8571. auto to_send = std::min(compressed.size() - total_sent,
  8572. static_cast<size_t>(64 * 1024));
  8573. auto sent =
  8574. ::send(cli,
  8575. #ifdef _WIN32
  8576. static_cast<const char *>(compressed.c_str() + total_sent),
  8577. static_cast<int>(to_send),
  8578. #else
  8579. compressed.c_str() + total_sent, to_send,
  8580. #endif
  8581. 0);
  8582. if (sent <= 0) break;
  8583. total_sent += static_cast<size_t>(sent);
  8584. }
  8585. detail::close_socket(cli);
  8586. }
  8587. });
  8588. auto se = detail::scope_exit([&] {
  8589. detail::close_socket(srv);
  8590. server_thread.join();
  8591. });
  8592. size_t total_decompressed = 0;
  8593. {
  8594. Client cli("127.0.0.1", PORT + 3);
  8595. cli.set_read_timeout(5, 0);
  8596. cli.set_decompress(true);
  8597. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8598. auto stream = cli.open_stream("GET", "/zipbomb");
  8599. ASSERT_TRUE(stream.is_valid());
  8600. char buffer[64 * 1024];
  8601. ssize_t n;
  8602. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8603. total_decompressed += static_cast<size_t>(n);
  8604. }
  8605. }
  8606. // The decompressed size must be capped by payload_max_length. Without
  8607. // protection, the client would decompress the full 10MB from a tiny
  8608. // compressed payload, enabling a zip bomb DoS attack.
  8609. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8610. << "Client decompressed " << total_decompressed
  8611. << " bytes from a gzip response. The decompressed size should be "
  8612. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8613. }
  8614. #endif
  8615. TEST(HostAndPortPropertiesTest, NoSSL) {
  8616. httplib::Client cli("www.google.com", 1234);
  8617. ASSERT_EQ("www.google.com", cli.host());
  8618. ASSERT_EQ(1234, cli.port());
  8619. }
  8620. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8621. httplib::Client cli("www.google.com:1234");
  8622. ASSERT_EQ("www.google.com", cli.host());
  8623. ASSERT_EQ(1234, cli.port());
  8624. }
  8625. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8626. // Port number that overflows int — should not crash, client becomes invalid
  8627. httplib::Client cli("http://www.google.com:99999999999999999999");
  8628. ASSERT_FALSE(cli.is_valid());
  8629. }
  8630. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8631. // Port 99999 exceeds valid range (1-65535) — should not crash
  8632. httplib::Client cli("http://www.google.com:99999");
  8633. ASSERT_FALSE(cli.is_valid());
  8634. }
  8635. #ifdef CPPHTTPLIB_SSL_ENABLED
  8636. TEST(HostAndPortPropertiesTest, SSL) {
  8637. httplib::SSLClient cli("www.google.com");
  8638. ASSERT_EQ("www.google.com", cli.host());
  8639. ASSERT_EQ(443, cli.port());
  8640. }
  8641. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8642. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8643. std::string cert;
  8644. read_file(CA_CERT_FILE, cert);
  8645. httplib::SSLClient httplib_client("www.google.com");
  8646. // Load CA store first time
  8647. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8648. // Load CA store second time (update)
  8649. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8650. // Verify client is still valid and can make connections
  8651. httplib_client.enable_server_certificate_verification(true);
  8652. auto res = httplib_client.Get("/");
  8653. ASSERT_TRUE(res);
  8654. // Google may return 200 or 301 depending on various factors
  8655. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8656. res->status == StatusCode::MovedPermanently_301);
  8657. }
  8658. TEST(SSLClientTest, ServerNameIndication_Online) {
  8659. auto host = "httpbingo.org";
  8660. auto path = std::string{"/get"};
  8661. SSLClient cli(host, 443);
  8662. auto res = cli.Get(path);
  8663. ASSERT_TRUE(res);
  8664. ASSERT_EQ(StatusCode::OK_200, res->status);
  8665. }
  8666. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8667. // Use a site that will cause SSL verification failure due to self-signed cert
  8668. SSLClient cli("self-signed.badssl.com", 443);
  8669. cli.enable_server_certificate_verification(true);
  8670. auto res = cli.Get("/");
  8671. ASSERT_TRUE(!res);
  8672. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8673. // Verify backend error is captured for SSLServerVerification
  8674. // This occurs when certificate verification fails
  8675. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8676. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8677. EXPECT_NE(0UL, res.ssl_backend_error());
  8678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8679. // For OpenSSL, ssl_error is 0 for verification errors
  8680. EXPECT_EQ(0, res.ssl_error());
  8681. #if !defined(_WIN32) || \
  8682. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8683. // On non-Windows or when Windows Schannel is disabled, the error comes
  8684. // from OpenSSL's verification
  8685. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8686. res.ssl_backend_error());
  8687. #endif
  8688. #endif
  8689. }
  8690. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8691. // Use a site where hostname doesn't match the certificate
  8692. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8693. SSLClient cli("wrong.host.badssl.com", 443);
  8694. cli.enable_server_certificate_verification(true);
  8695. cli.enable_server_hostname_verification(true);
  8696. auto res = cli.Get("/");
  8697. ASSERT_TRUE(!res);
  8698. // The error type depends on when hostname verification occurs:
  8699. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8700. // - Mbed TLS: SSLServerVerification (during handshake)
  8701. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8702. res.error() == Error::SSLServerVerification);
  8703. // Verify backend error is captured for hostname verification failure
  8704. EXPECT_NE(0UL, res.ssl_backend_error());
  8705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8706. // For OpenSSL, ssl_error is 0 for verification errors
  8707. EXPECT_EQ(0, res.ssl_error());
  8708. #if !defined(_WIN32) || \
  8709. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8710. // On non-Windows or when Windows Schannel is disabled, the error comes
  8711. // from OpenSSL's hostname verification
  8712. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8713. res.ssl_backend_error());
  8714. #endif
  8715. #endif
  8716. }
  8717. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8718. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8719. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8720. SSLClient cli("www.google.com", 443);
  8721. cli.enable_server_certificate_verification(true);
  8722. auto res = cli.Get("/");
  8723. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8724. }
  8725. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8726. SSLClient cli("www.google.com", 443);
  8727. cli.enable_server_certificate_verification(true);
  8728. cli.enable_windows_certificate_verification(false);
  8729. auto res = cli.Get("/");
  8730. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8731. }
  8732. #endif
  8733. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8734. Client cli("https://google.com");
  8735. auto res = cli.Get("/");
  8736. ASSERT_TRUE(res);
  8737. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8738. }
  8739. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8740. SSLClient cli("google.com");
  8741. cli.set_ca_cert_path(CA_CERT_FILE);
  8742. auto res = cli.Get("/");
  8743. ASSERT_TRUE(res);
  8744. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8745. }
  8746. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8747. SSLClient cli("google.com");
  8748. cli.enable_server_certificate_verification(true);
  8749. cli.set_ca_cert_path("hello");
  8750. auto res = cli.Get("/");
  8751. ASSERT_TRUE(!res);
  8752. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8753. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8754. // should be set
  8755. EXPECT_EQ(0, res.ssl_error());
  8756. // Verify backend error is captured for SSLLoadingCerts
  8757. // This error occurs when loading CA certificates fails
  8758. EXPECT_NE(0UL, res.ssl_backend_error());
  8759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8760. // OpenSSL specific error codes:
  8761. // > openssl errstr 0x80000002
  8762. // error:80000002:system library::No such file or directory
  8763. // > openssl errstr 0xA000126
  8764. // error:0A000126:SSL routines::unexpected eof while reading
  8765. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8766. res.ssl_backend_error() == 0xA000126);
  8767. #endif
  8768. }
  8769. TEST(SSLClientTest, ServerCertificateVerification4) {
  8770. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8771. ASSERT_TRUE(svr.is_valid());
  8772. svr.Get("/test", [&](const Request &, Response &res) {
  8773. res.set_content("test", "text/plain");
  8774. svr.stop();
  8775. ASSERT_TRUE(true);
  8776. });
  8777. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8778. auto se = detail::scope_exit([&] {
  8779. t.join();
  8780. ASSERT_FALSE(svr.is_running());
  8781. });
  8782. svr.wait_until_ready();
  8783. SSLClient cli("127.0.0.1", PORT);
  8784. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8785. cli.enable_server_certificate_verification(true);
  8786. cli.set_connection_timeout(30);
  8787. auto res = cli.Get("/test");
  8788. ASSERT_TRUE(res);
  8789. ASSERT_EQ(StatusCode::OK_200, res->status);
  8790. }
  8791. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8792. std::string cert;
  8793. read_file(CA_CERT_FILE, cert);
  8794. SSLClient cli("google.com");
  8795. cli.load_ca_cert_store(cert.data(), cert.size());
  8796. const auto res = cli.Get("/");
  8797. ASSERT_TRUE(res);
  8798. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8799. }
  8800. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8801. // clang-format off
  8802. static constexpr char cert[] =
  8803. "GlobalSign Root CA\n"
  8804. "==================\n"
  8805. "-----BEGIN CERTIFICATE-----\n"
  8806. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8807. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8808. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8809. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8810. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8811. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8812. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8813. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8814. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8815. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8816. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8817. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8818. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8819. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8820. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8821. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8822. "-----END CERTIFICATE-----\n";
  8823. // clang-format on
  8824. SSLClient cli("google.com");
  8825. cli.load_ca_cert_store(cert, sizeof(cert));
  8826. const auto res = cli.Get("/");
  8827. ASSERT_TRUE(res);
  8828. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8829. }
  8830. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8831. SSLClient cli("www.youtube.com");
  8832. cli.set_ca_cert_path(CA_CERT_FILE);
  8833. cli.enable_server_certificate_verification(true);
  8834. cli.set_follow_location(true);
  8835. auto res = cli.Get("/");
  8836. ASSERT_TRUE(res);
  8837. ASSERT_EQ(StatusCode::OK_200, res->status);
  8838. }
  8839. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8840. SSLClient cli("wWw.YouTube.Com");
  8841. cli.set_ca_cert_path(CA_CERT_FILE);
  8842. cli.enable_server_certificate_verification(true);
  8843. cli.enable_server_hostname_verification(true);
  8844. cli.set_follow_location(true);
  8845. auto res = cli.Get("/");
  8846. ASSERT_TRUE(res);
  8847. ASSERT_EQ(StatusCode::OK_200, res->status);
  8848. }
  8849. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8850. SSLClient cli("gOoGlE.COm");
  8851. cli.enable_server_certificate_verification(true);
  8852. cli.enable_server_hostname_verification(true);
  8853. cli.set_follow_location(true);
  8854. auto res = cli.Get("/");
  8855. ASSERT_TRUE(res);
  8856. ASSERT_EQ(StatusCode::OK_200, res->status);
  8857. }
  8858. TEST(SSLClientTest, Issue2004_Online) {
  8859. Client client("https://google.com");
  8860. client.set_follow_location(true);
  8861. auto res = client.Get("/");
  8862. ASSERT_TRUE(res);
  8863. ASSERT_EQ(StatusCode::OK_200, res->status);
  8864. auto body = res->body;
  8865. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8866. }
  8867. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8868. // Create SSLClient with invalid cert/key to make is_valid() return false
  8869. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8870. "nonexistent_key.pem");
  8871. // is_valid() should be false due to cert loading failure
  8872. ASSERT_FALSE(cli.is_valid());
  8873. auto res = cli.Get("/");
  8874. ASSERT_FALSE(res);
  8875. EXPECT_EQ(Error::SSLConnection, res.error());
  8876. }
  8877. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8878. // Test for Issue #2251: SSL error not properly reported when client cert
  8879. // and key paths are swapped or mismatched
  8880. // This simulates the scenario where user accidentally swaps the cert and key
  8881. // files
  8882. // Using client cert file as private key and vice versa (completely wrong)
  8883. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8884. // Should fail validation due to cert/key mismatch
  8885. ASSERT_FALSE(cli.is_valid());
  8886. // Attempt to make a request should fail with proper error
  8887. auto res = cli.Get("/");
  8888. ASSERT_FALSE(res);
  8889. EXPECT_EQ(Error::SSLConnection, res.error());
  8890. // SSL error should be recorded in the Result object (this is the key fix for
  8891. // Issue #2251)
  8892. auto backend_error = res.ssl_backend_error();
  8893. EXPECT_NE(0u, backend_error);
  8894. }
  8895. // Tests cert/key mismatch detection at the TLS context level
  8896. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8897. // Test that using mismatched cert/key causes connection failure.
  8898. // We verify this at the SSLClient level rather than through internal
  8899. // TLS API functions.
  8900. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8901. cli.enable_server_certificate_verification(false);
  8902. cli.set_connection_timeout(2);
  8903. // The mismatch should cause a connection or handshake error
  8904. auto res = cli.Get("/test");
  8905. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8906. // Either way, the request should fail
  8907. EXPECT_FALSE(res);
  8908. }
  8909. #endif
  8910. #if 0
  8911. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8912. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8913. ASSERT_TRUE(cli != nullptr);
  8914. cli->set_address_family(AF_INET6);
  8915. cli->set_interface("en0");
  8916. auto res = cli->Get("/get");
  8917. ASSERT_TRUE(res);
  8918. ASSERT_EQ(StatusCode::OK_200, res->status);
  8919. }
  8920. #endif
  8921. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8922. #ifdef CPPHTTPLIB_SSL_ENABLED
  8923. void ClientCertPresent(
  8924. const std::string &client_cert_file,
  8925. const std::string &client_private_key_file,
  8926. const std::string &client_encrypted_private_key_pass = std::string()) {
  8927. using namespace httplib::tls;
  8928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8929. CLIENT_CA_CERT_DIR);
  8930. ASSERT_TRUE(svr.is_valid());
  8931. svr.Get("/test", [&](const Request &req, Response &res) {
  8932. res.set_content("test", "text/plain");
  8933. auto cert = req.peer_cert();
  8934. ASSERT_TRUE(static_cast<bool>(cert));
  8935. std::string common_name = cert.subject_cn();
  8936. EXPECT_EQ("Common Name", common_name);
  8937. });
  8938. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8939. auto se = detail::scope_exit([&] {
  8940. svr.stop();
  8941. t.join();
  8942. ASSERT_FALSE(svr.is_running());
  8943. });
  8944. svr.wait_until_ready();
  8945. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8946. client_encrypted_private_key_pass);
  8947. cli.enable_server_certificate_verification(false);
  8948. cli.set_connection_timeout(30);
  8949. auto res = cli.Get("/test");
  8950. ASSERT_TRUE(res);
  8951. ASSERT_EQ(StatusCode::OK_200, res->status);
  8952. }
  8953. TEST(SSLClientServerTest, ClientCertPresent) {
  8954. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8955. }
  8956. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8957. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8958. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8959. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8960. }
  8961. // PEM memory-based constructor tests (works with all TLS backends)
  8962. void PemMemoryClientCertPresent(
  8963. const std::string &client_cert_file,
  8964. const std::string &client_private_key_file,
  8965. const std::string &client_encrypted_private_key_pass = std::string()) {
  8966. // Read PEM files into memory
  8967. std::string server_cert_pem, server_key_pem;
  8968. std::string client_ca_pem;
  8969. std::string client_cert_pem, client_key_pem;
  8970. read_file(SERVER_CERT_FILE, server_cert_pem);
  8971. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8972. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8973. read_file(client_cert_file, client_cert_pem);
  8974. read_file(client_private_key_file, client_key_pem);
  8975. // Create server with PEM memory
  8976. SSLServer::PemMemory server_pem = {
  8977. server_cert_pem.c_str(),
  8978. server_cert_pem.size(),
  8979. server_key_pem.c_str(),
  8980. server_key_pem.size(),
  8981. client_ca_pem.c_str(),
  8982. client_ca_pem.size(),
  8983. nullptr // no password for server key
  8984. };
  8985. SSLServer svr(server_pem);
  8986. ASSERT_TRUE(svr.is_valid());
  8987. svr.Get("/test", [&](const Request &, Response &res) {
  8988. res.set_content("test", "text/plain");
  8989. });
  8990. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8991. auto se = detail::scope_exit([&] {
  8992. svr.stop();
  8993. t.join();
  8994. ASSERT_FALSE(svr.is_running());
  8995. });
  8996. svr.wait_until_ready();
  8997. // Create client with PEM memory
  8998. const char *password = client_encrypted_private_key_pass.empty()
  8999. ? nullptr
  9000. : client_encrypted_private_key_pass.c_str();
  9001. SSLClient::PemMemory client_pem = {
  9002. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9003. client_key_pem.size(), password};
  9004. SSLClient cli(HOST, PORT, client_pem);
  9005. cli.enable_server_certificate_verification(false);
  9006. cli.set_connection_timeout(30);
  9007. auto res = cli.Get("/test");
  9008. ASSERT_TRUE(res);
  9009. ASSERT_EQ(StatusCode::OK_200, res->status);
  9010. }
  9011. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9012. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9013. }
  9014. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9015. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9016. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9017. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9018. }
  9019. TEST(SSLClientServerTest, ClientCertMissing) {
  9020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9021. CLIENT_CA_CERT_DIR);
  9022. ASSERT_TRUE(svr.is_valid());
  9023. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9024. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9025. auto se = detail::scope_exit([&] {
  9026. svr.stop();
  9027. t.join();
  9028. ASSERT_FALSE(svr.is_running());
  9029. });
  9030. svr.wait_until_ready();
  9031. SSLClient cli(HOST, PORT);
  9032. cli.set_connection_timeout(30);
  9033. auto res = cli.Get("/test");
  9034. ASSERT_TRUE(!res);
  9035. // When client cert is missing and server requires it, connection fails
  9036. // Error type depends on backend implementation
  9037. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9038. res.error() == Error::SSLConnection);
  9039. // Verify backend error is captured
  9040. // Note: This test may have different error codes depending on the exact
  9041. // verification failure
  9042. EXPECT_NE(0UL, res.ssl_backend_error());
  9043. }
  9044. TEST(SSLClientServerTest, TrustDirOptional) {
  9045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9046. ASSERT_TRUE(svr.is_valid());
  9047. svr.Get("/test", [&](const Request &, Response &res) {
  9048. res.set_content("test", "text/plain");
  9049. });
  9050. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9051. auto se = detail::scope_exit([&] {
  9052. svr.stop();
  9053. t.join();
  9054. ASSERT_FALSE(svr.is_running());
  9055. });
  9056. svr.wait_until_ready();
  9057. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9058. cli.enable_server_certificate_verification(false);
  9059. cli.set_connection_timeout(30);
  9060. auto res = cli.Get("/test");
  9061. ASSERT_TRUE(res);
  9062. ASSERT_EQ(StatusCode::OK_200, res->status);
  9063. }
  9064. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9065. class NoListenSSLServer : public SSLServer {
  9066. public:
  9067. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9068. const char *client_ca_cert_file_path,
  9069. const char *client_ca_cert_dir_path = nullptr)
  9070. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9071. client_ca_cert_dir_path),
  9072. stop_(false) {}
  9073. std::atomic_bool stop_;
  9074. private:
  9075. bool process_and_close_socket(socket_t /*sock*/) override {
  9076. // Don't create SSL context
  9077. while (!stop_.load()) {
  9078. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9079. }
  9080. return true;
  9081. }
  9082. };
  9083. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9084. CLIENT_CA_CERT_FILE);
  9085. ASSERT_TRUE(svr.is_valid());
  9086. svr.Get("/test", [&](const Request &, Response &res) {
  9087. res.set_content("test", "text/plain");
  9088. });
  9089. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9090. auto se = detail::scope_exit([&] {
  9091. svr.stop_ = true;
  9092. svr.stop();
  9093. t.join();
  9094. ASSERT_FALSE(svr.is_running());
  9095. });
  9096. svr.wait_until_ready();
  9097. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9098. cli.enable_server_certificate_verification(false);
  9099. cli.set_connection_timeout(1);
  9100. auto res = cli.Get("/test");
  9101. ASSERT_TRUE(!res);
  9102. EXPECT_EQ(Error::SSLConnection, res.error());
  9103. // Timeout results in WantRead error code (maps to backend-specific value)
  9104. EXPECT_NE(0, res.ssl_error());
  9105. }
  9106. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9107. // Test SSLServer with client certificate verification using the standard
  9108. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9110. CLIENT_CA_CERT_DIR);
  9111. ASSERT_TRUE(svr.is_valid());
  9112. svr.Get("/test", [&](const Request &req, Response &res) {
  9113. res.set_content("test", "text/plain");
  9114. auto cert = req.peer_cert();
  9115. ASSERT_TRUE(static_cast<bool>(cert));
  9116. auto common_name = cert.subject_cn();
  9117. EXPECT_EQ("Common Name", common_name);
  9118. });
  9119. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9120. auto se = detail::scope_exit([&] {
  9121. svr.stop();
  9122. t.join();
  9123. ASSERT_FALSE(svr.is_running());
  9124. });
  9125. svr.wait_until_ready();
  9126. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9127. cli.enable_server_certificate_verification(false);
  9128. cli.set_connection_timeout(30);
  9129. auto res = cli.Get("/test");
  9130. ASSERT_TRUE(res);
  9131. ASSERT_EQ(StatusCode::OK_200, res->status);
  9132. }
  9133. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9134. // Verifies that wildcard matching and exact matching work consistently
  9135. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9136. using namespace httplib::tls;
  9137. // We need a running server to test against
  9138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9139. ASSERT_TRUE(svr.is_valid());
  9140. svr.Get("/test", [](const Request &, Response &res) {
  9141. res.set_content("ok", "text/plain");
  9142. });
  9143. thread t([&]() { svr.listen(HOST, PORT); });
  9144. auto se = detail::scope_exit([&] {
  9145. svr.stop();
  9146. t.join();
  9147. });
  9148. svr.wait_until_ready();
  9149. bool verify_callback_called = false;
  9150. bool verify_result_wrong = false;
  9151. SSLClient cli(HOST, PORT);
  9152. cli.enable_server_certificate_verification(true);
  9153. cli.set_ca_cert_path(CA_CERT_FILE);
  9154. cli.set_connection_timeout(5);
  9155. // Note: Test certificate has CN="Common Name", not "localhost"
  9156. bool verify_result_cn = false;
  9157. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9158. verify_callback_called = true;
  9159. if (!ctx.cert) return false;
  9160. // Test 1: "Common Name" should match (our test server cert CN)
  9161. verify_result_cn = ctx.check_hostname("Common Name");
  9162. // Test 2: wrong hostname should not match
  9163. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9164. return true; // Accept for the purpose of this test
  9165. });
  9166. auto res = cli.Get("/test");
  9167. // The request may succeed or fail depending on cert configuration
  9168. // but the callback should have been called
  9169. ASSERT_TRUE(verify_callback_called)
  9170. << "Verify callback should have been called";
  9171. // CN="Common Name" should match our test certificate
  9172. //
  9173. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9174. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9175. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9176. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9177. // <openssl/base.h>, which is included transitively when
  9178. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9179. #if defined(OPENSSL_IS_BORINGSSL)
  9180. EXPECT_FALSE(verify_result_cn)
  9181. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9182. #else
  9183. EXPECT_TRUE(verify_result_cn)
  9184. << "verify_hostname should match 'Common Name' (certificate CN)";
  9185. #endif
  9186. // Wrong hostname should not match
  9187. EXPECT_FALSE(verify_result_wrong)
  9188. << "verify_hostname should not match 'wronghost.example.com'";
  9189. }
  9190. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9191. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9192. // X509_check_ip behavior and must hold for every backend.
  9193. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9194. using namespace httplib::tls;
  9195. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9196. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9197. ASSERT_TRUE(svr.is_valid());
  9198. svr.Get("/test", [](const Request &, Response &res) {
  9199. res.set_content("ok", "text/plain");
  9200. });
  9201. thread t([&]() { svr.listen(HOST, PORT); });
  9202. auto se = detail::scope_exit([&] {
  9203. svr.stop();
  9204. t.join();
  9205. });
  9206. svr.wait_until_ready();
  9207. bool verify_callback_called = false;
  9208. bool ip_matched_via_cn = true;
  9209. SSLClient cli(HOST, PORT);
  9210. cli.enable_server_certificate_verification(true);
  9211. cli.set_ca_cert_path(CA_CERT_FILE);
  9212. cli.set_connection_timeout(5);
  9213. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9214. verify_callback_called = true;
  9215. if (!ctx.cert) return false;
  9216. // The IP appears only in the CN, so it must NOT be accepted.
  9217. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9218. return true; // Accept for the purpose of this test
  9219. });
  9220. cli.Get("/test");
  9221. ASSERT_TRUE(verify_callback_called)
  9222. << "Verify callback should have been called";
  9223. EXPECT_FALSE(ip_matched_via_cn)
  9224. << "An IP host must not be authenticated via the certificate CN";
  9225. }
  9226. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9227. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9228. using namespace httplib::tls;
  9229. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9230. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9231. ASSERT_TRUE(svr.is_valid());
  9232. svr.Get("/test", [](const Request &, Response &res) {
  9233. res.set_content("ok", "text/plain");
  9234. });
  9235. thread t([&]() { svr.listen(HOST, PORT); });
  9236. auto se = detail::scope_exit([&] {
  9237. svr.stop();
  9238. t.join();
  9239. });
  9240. svr.wait_until_ready();
  9241. bool verify_callback_called = false;
  9242. bool san_matched = false;
  9243. bool wrong_ipv6_matched = true;
  9244. bool cn_ipv6_matched = true;
  9245. SSLClient cli(HOST, PORT);
  9246. cli.enable_server_certificate_verification(true);
  9247. cli.set_ca_cert_path(CA_CERT_FILE);
  9248. cli.set_connection_timeout(5);
  9249. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9250. verify_callback_called = true;
  9251. if (!ctx.cert) return false;
  9252. // Matches the IPv6 iPAddress SAN.
  9253. san_matched = ctx.check_hostname("2001:db8::1");
  9254. // A different IPv6 address must not match.
  9255. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9256. // "::1" lives only in the CN, so it must not be accepted.
  9257. cn_ipv6_matched = ctx.check_hostname("::1");
  9258. return true; // Accept for the purpose of this test
  9259. });
  9260. cli.Get("/test");
  9261. ASSERT_TRUE(verify_callback_called)
  9262. << "Verify callback should have been called";
  9263. EXPECT_TRUE(san_matched)
  9264. << "verify_hostname should match an IPv6 iPAddress SAN";
  9265. EXPECT_FALSE(wrong_ipv6_matched)
  9266. << "verify_hostname should not match a non-matching IPv6 address";
  9267. EXPECT_FALSE(cn_ipv6_matched)
  9268. << "An IPv6 host must not be authenticated via the certificate CN";
  9269. }
  9270. #endif
  9271. // mbedTLS-specific callback constructor test
  9272. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9273. #ifdef CPPHTTPLIB_SSL_ENABLED
  9274. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9276. ASSERT_TRUE(svr.is_valid());
  9277. // Set up a handler to verify client certificate is present
  9278. bool client_cert_verified = false;
  9279. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9280. // Verify that client certificate was provided
  9281. client_cert_verified = true;
  9282. res.set_content("success", "text/plain");
  9283. });
  9284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9285. auto se = detail::scope_exit([&] {
  9286. svr.stop();
  9287. t.join();
  9288. ASSERT_FALSE(svr.is_running());
  9289. });
  9290. svr.wait_until_ready();
  9291. // Client with certificate
  9292. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9293. cli.enable_server_certificate_verification(false);
  9294. cli.set_connection_timeout(30);
  9295. auto res = cli.Get("/test");
  9296. ASSERT_TRUE(res);
  9297. ASSERT_EQ(StatusCode::OK_200, res->status);
  9298. ASSERT_TRUE(client_cert_verified);
  9299. EXPECT_EQ("success", res->body);
  9300. }
  9301. #endif
  9302. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9303. // backends
  9304. #ifdef CPPHTTPLIB_SSL_ENABLED
  9305. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9306. using namespace httplib::tls;
  9307. // Test that when client CA cert file is provided,
  9308. // the server properly requests and validates client certificates
  9309. // Create a server with client authentication
  9310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9311. ASSERT_TRUE(svr.is_valid());
  9312. bool handler_called = false;
  9313. svr.Get("/test", [&](const Request &req, Response &res) {
  9314. handler_called = true;
  9315. // Verify that a client certificate was provided
  9316. auto cert = req.peer_cert();
  9317. ASSERT_TRUE(static_cast<bool>(cert));
  9318. // Get the issuer name
  9319. std::string issuer_str = cert.issuer_name();
  9320. ASSERT_FALSE(issuer_str.empty());
  9321. // The client certificate should be issued by our test CA
  9322. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9323. res.set_content("authenticated", "text/plain");
  9324. });
  9325. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9326. auto se = detail::scope_exit([&] {
  9327. svr.stop();
  9328. t.join();
  9329. ASSERT_FALSE(svr.is_running());
  9330. });
  9331. svr.wait_until_ready();
  9332. // Connect with a client certificate issued by the CA
  9333. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9334. cli.enable_server_certificate_verification(false);
  9335. cli.set_connection_timeout(30);
  9336. auto res = cli.Get("/test");
  9337. ASSERT_TRUE(res);
  9338. ASSERT_EQ(StatusCode::OK_200, res->status);
  9339. ASSERT_TRUE(handler_called);
  9340. EXPECT_EQ("authenticated", res->body);
  9341. }
  9342. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9343. using namespace httplib::tls;
  9344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9345. ASSERT_TRUE(svr.is_valid());
  9346. svr.Get("/test", [](const Request &, Response &res) {
  9347. res.set_content("ok", "text/plain");
  9348. });
  9349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9350. auto se = detail::scope_exit([&] {
  9351. svr.stop();
  9352. t.join();
  9353. });
  9354. svr.wait_until_ready();
  9355. SSLClient cli(HOST, PORT);
  9356. cli.enable_server_certificate_verification(false);
  9357. cli.set_connection_timeout(30);
  9358. bool cert_checked = false;
  9359. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9360. if (ctx.cert) {
  9361. auto sans = ctx.sans();
  9362. // Test certificate may or may not have SANs - just verify the API
  9363. // works If SANs exist, verify the types are valid
  9364. for (const auto &san : sans) {
  9365. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9366. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9367. san.type == SanType::OTHER);
  9368. EXPECT_FALSE(san.value.empty());
  9369. }
  9370. cert_checked = true;
  9371. }
  9372. return true;
  9373. });
  9374. auto res = cli.Get("/test");
  9375. ASSERT_TRUE(res);
  9376. EXPECT_TRUE(cert_checked);
  9377. }
  9378. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9379. using namespace httplib::tls;
  9380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9381. ASSERT_TRUE(svr.is_valid());
  9382. svr.Get("/test", [](const Request &, Response &res) {
  9383. res.set_content("ok", "text/plain");
  9384. });
  9385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9386. auto se = detail::scope_exit([&] {
  9387. svr.stop();
  9388. t.join();
  9389. });
  9390. svr.wait_until_ready();
  9391. SSLClient cli(HOST, PORT);
  9392. cli.enable_server_certificate_verification(false);
  9393. cli.set_connection_timeout(30);
  9394. bool validity_checked = false;
  9395. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9396. if (ctx.cert) {
  9397. time_t not_before = 0, not_after = 0;
  9398. bool result = ctx.validity(not_before, not_after);
  9399. EXPECT_TRUE(result);
  9400. // Verify that not_before < now < not_after for a valid cert
  9401. time_t now = time(nullptr);
  9402. EXPECT_LT(not_before, now);
  9403. EXPECT_GT(not_after, now);
  9404. validity_checked = true;
  9405. }
  9406. return true;
  9407. });
  9408. auto res = cli.Get("/test");
  9409. ASSERT_TRUE(res);
  9410. EXPECT_TRUE(validity_checked);
  9411. }
  9412. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9413. using namespace httplib::tls;
  9414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9415. ASSERT_TRUE(svr.is_valid());
  9416. svr.Get("/test", [](const Request &, Response &res) {
  9417. res.set_content("ok", "text/plain");
  9418. });
  9419. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9420. auto se = detail::scope_exit([&] {
  9421. svr.stop();
  9422. t.join();
  9423. });
  9424. svr.wait_until_ready();
  9425. SSLClient cli(HOST, PORT);
  9426. cli.enable_server_certificate_verification(false);
  9427. cli.set_connection_timeout(30);
  9428. bool serial_checked = false;
  9429. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9430. if (ctx.cert) {
  9431. std::string serial = ctx.serial();
  9432. EXPECT_FALSE(serial.empty());
  9433. // Serial should be a hex string
  9434. for (char c : serial) {
  9435. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9436. (c >= 'a' && c <= 'f'));
  9437. }
  9438. serial_checked = true;
  9439. }
  9440. return true;
  9441. });
  9442. auto res = cli.Get("/test");
  9443. ASSERT_TRUE(res);
  9444. EXPECT_TRUE(serial_checked);
  9445. }
  9446. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9447. // Test 1: Valid CA file - no error should be recorded
  9448. {
  9449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9450. CLIENT_CA_CERT_FILE);
  9451. ASSERT_TRUE(svr.is_valid());
  9452. // With valid setup, last_ssl_error should be 0
  9453. EXPECT_EQ(0, svr.ssl_last_error());
  9454. }
  9455. // Test 2: Invalid CA file content
  9456. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9457. {
  9458. // Create a temporary file with completely invalid content
  9459. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9460. {
  9461. std::ofstream ofs(temp_invalid_ca);
  9462. ofs << "This is not a certificate file at all\n";
  9463. ofs << "Just plain text content\n";
  9464. }
  9465. // Create server with invalid CA file
  9466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9467. // Clean up temporary file
  9468. std::remove(temp_invalid_ca);
  9469. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9470. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9471. // Note: SSL_CTX_load_verify_locations typically fails first,
  9472. // but our error handling code path is still exercised
  9473. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9474. }
  9475. }
  9476. TEST(VerifyCallbackTest, VerifyContextFields) {
  9477. using namespace httplib::tls;
  9478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9479. ASSERT_TRUE(svr.is_valid());
  9480. svr.Get("/test", [](const Request &, Response &res) {
  9481. res.set_content("ok", "text/plain");
  9482. });
  9483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9484. auto se = detail::scope_exit([&] {
  9485. svr.stop();
  9486. t.join();
  9487. });
  9488. svr.wait_until_ready();
  9489. SSLClient cli(HOST, PORT);
  9490. cli.enable_server_certificate_verification(false);
  9491. cli.set_connection_timeout(30);
  9492. int callback_count = 0;
  9493. bool saw_leaf_cert = false;
  9494. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9495. if (ctx.cert) {
  9496. callback_count++;
  9497. // We should see at least one certificate (the leaf)
  9498. std::string cn = ctx.subject_cn();
  9499. if (!cn.empty()) { saw_leaf_cert = true; }
  9500. // Verify context fields are populated
  9501. EXPECT_NE(ctx.session, nullptr);
  9502. EXPECT_GE(ctx.depth, 0);
  9503. }
  9504. return true;
  9505. });
  9506. auto res = cli.Get("/test");
  9507. ASSERT_TRUE(res);
  9508. EXPECT_GT(callback_count, 0);
  9509. EXPECT_TRUE(saw_leaf_cert);
  9510. }
  9511. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9512. using httplib::tls::TlsError;
  9513. // Test that verify_error_to_string returns empty for success
  9514. std::string success_str = TlsError::verify_error_to_string(0);
  9515. EXPECT_TRUE(success_str.empty());
  9516. // Test that verify_error_to_string returns non-empty for error codes
  9517. // Using a common error code (certificate expired)
  9518. std::string error_str =
  9519. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9520. EXPECT_FALSE(error_str.empty());
  9521. }
  9522. TEST(SessionVerifierTest, CertificateAccepted) {
  9523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9524. ASSERT_TRUE(svr.is_valid());
  9525. svr.Get("/test", [](const Request &, Response &res) {
  9526. res.set_content("ok", "text/plain");
  9527. });
  9528. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. });
  9533. svr.wait_until_ready();
  9534. SSLClient cli(HOST, PORT);
  9535. cli.enable_server_certificate_verification(false);
  9536. cli.set_connection_timeout(30);
  9537. bool callback_called = false;
  9538. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9539. EXPECT_NE(session, nullptr);
  9540. callback_called = true;
  9541. return SSLVerifierResponse::CertificateAccepted;
  9542. });
  9543. auto res = cli.Get("/test");
  9544. ASSERT_TRUE(res);
  9545. EXPECT_EQ(200, res->status);
  9546. EXPECT_TRUE(callback_called);
  9547. }
  9548. TEST(SessionVerifierTest, CertificateRejected) {
  9549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9550. ASSERT_TRUE(svr.is_valid());
  9551. svr.Get("/test", [](const Request &, Response &res) {
  9552. res.set_content("ok", "text/plain");
  9553. });
  9554. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9555. auto se = detail::scope_exit([&] {
  9556. svr.stop();
  9557. t.join();
  9558. });
  9559. svr.wait_until_ready();
  9560. SSLClient cli(HOST, PORT);
  9561. cli.enable_server_certificate_verification(false);
  9562. cli.set_connection_timeout(30);
  9563. bool callback_called = false;
  9564. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9565. EXPECT_NE(session, nullptr);
  9566. callback_called = true;
  9567. return SSLVerifierResponse::CertificateRejected;
  9568. });
  9569. auto res = cli.Get("/test");
  9570. EXPECT_FALSE(res);
  9571. EXPECT_TRUE(callback_called);
  9572. }
  9573. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9575. ASSERT_TRUE(svr.is_valid());
  9576. svr.Get("/test", [](const Request &, Response &res) {
  9577. res.set_content("ok", "text/plain");
  9578. });
  9579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9580. auto se = detail::scope_exit([&] {
  9581. svr.stop();
  9582. t.join();
  9583. });
  9584. svr.wait_until_ready();
  9585. // NoDecisionMade with verification disabled should succeed (no default check)
  9586. SSLClient cli(HOST, PORT);
  9587. cli.enable_server_certificate_verification(false);
  9588. cli.set_connection_timeout(30);
  9589. bool callback_called = false;
  9590. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9591. EXPECT_NE(session, nullptr);
  9592. callback_called = true;
  9593. return SSLVerifierResponse::NoDecisionMade;
  9594. });
  9595. auto res = cli.Get("/test");
  9596. ASSERT_TRUE(res);
  9597. EXPECT_EQ(200, res->status);
  9598. EXPECT_TRUE(callback_called);
  9599. }
  9600. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9602. ASSERT_TRUE(svr.is_valid());
  9603. svr.Get("/test", [](const Request &, Response &res) {
  9604. res.set_content("ok", "text/plain");
  9605. });
  9606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9607. auto se = detail::scope_exit([&] {
  9608. svr.stop();
  9609. t.join();
  9610. });
  9611. svr.wait_until_ready();
  9612. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9613. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9614. // so we only check that the request fails, not whether the callback was
  9615. // called.
  9616. SSLClient cli(HOST, PORT);
  9617. cli.enable_server_certificate_verification(true);
  9618. cli.set_connection_timeout(30);
  9619. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9620. EXPECT_NE(session, nullptr);
  9621. return SSLVerifierResponse::NoDecisionMade;
  9622. });
  9623. auto res = cli.Get("/test");
  9624. EXPECT_FALSE(res);
  9625. }
  9626. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9627. // Test SSL server using PemMemory constructor with client CA certificates
  9628. // Read PEM files
  9629. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9630. read_file(SERVER_CERT_FILE, server_cert_pem);
  9631. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9632. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9633. // Create SSLServer with PemMemory constructor including client CA
  9634. SSLServer::PemMemory server_pem = {
  9635. server_cert_pem.c_str(),
  9636. server_cert_pem.size(),
  9637. server_key_pem.c_str(),
  9638. server_key_pem.size(),
  9639. client_ca_pem.c_str(),
  9640. client_ca_pem.size(),
  9641. nullptr // no password for server key
  9642. };
  9643. SSLServer svr(server_pem);
  9644. ASSERT_TRUE(svr.is_valid());
  9645. // No SSL error should be recorded for valid setup
  9646. EXPECT_EQ(0, svr.ssl_last_error());
  9647. // Set up server endpoints
  9648. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9649. res.set_content("ok", "text/plain");
  9650. });
  9651. // Start server in a thread
  9652. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9653. svr.wait_until_ready();
  9654. // Connect with client certificate (using constructor with paths)
  9655. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9656. cli.enable_server_certificate_verification(false);
  9657. auto res = cli.Get("/test-pem-ca");
  9658. ASSERT_TRUE(res);
  9659. EXPECT_EQ(200, res->status);
  9660. EXPECT_EQ("ok", res->body);
  9661. svr.stop();
  9662. server_thread.join();
  9663. }
  9664. #endif
  9665. #ifdef _WIN32
  9666. TEST(CleanupTest, WSACleanup) {
  9667. int ret = WSACleanup();
  9668. ASSERT_EQ(0, ret);
  9669. }
  9670. #endif
  9671. #ifndef CPPHTTPLIB_SSL_ENABLED
  9672. TEST(NoSSLSupport, SimpleInterface) {
  9673. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9674. }
  9675. #endif
  9676. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9677. TEST(InvalidScheme, SimpleInterface) {
  9678. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9679. }
  9680. #endif
  9681. TEST(NoScheme, SimpleInterface) {
  9682. Client cli("yahoo.com:80");
  9683. ASSERT_TRUE(cli.is_valid());
  9684. }
  9685. TEST(SendAPI, SimpleInterface_Online) {
  9686. Client cli("http://yahoo.com");
  9687. Request req;
  9688. req.method = "GET";
  9689. req.path = "/";
  9690. auto res = cli.send(req);
  9691. ASSERT_TRUE(res);
  9692. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9693. }
  9694. TEST(SendAPI, WithParamsInRequest) {
  9695. Server svr;
  9696. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9697. EXPECT_TRUE(req.has_param("test"));
  9698. EXPECT_EQ("test_value", req.get_param_value("test"));
  9699. });
  9700. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9701. auto se = detail::scope_exit([&] {
  9702. svr.stop();
  9703. t.join();
  9704. ASSERT_FALSE(svr.is_running());
  9705. });
  9706. svr.wait_until_ready();
  9707. Client cli(HOST, PORT);
  9708. {
  9709. Request req;
  9710. req.method = "GET";
  9711. req.path = "/";
  9712. req.params.emplace("test", "test_value");
  9713. auto res = cli.send(req);
  9714. ASSERT_TRUE(res);
  9715. }
  9716. {
  9717. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9718. ASSERT_TRUE(res);
  9719. }
  9720. }
  9721. TEST(ClientImplMethods, GetSocketTest) {
  9722. httplib::Server svr;
  9723. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9724. res.status = StatusCode::OK_200;
  9725. });
  9726. auto port = svr.bind_to_any_port("127.0.0.1");
  9727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9728. auto se = detail::scope_exit([&] {
  9729. svr.stop();
  9730. thread.join();
  9731. ASSERT_FALSE(svr.is_running());
  9732. });
  9733. svr.wait_until_ready();
  9734. {
  9735. httplib::Client cli("127.0.0.1", port);
  9736. cli.set_keep_alive(true);
  9737. // Use the behavior of cpp-httplib of opening the connection
  9738. // only when the first request happens. If that changes,
  9739. // this test would be obsolete.
  9740. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9741. // This also implicitly tests the server. But other tests would fail much
  9742. // earlier than this one to be considered.
  9743. auto res = cli.Get("/");
  9744. ASSERT_TRUE(res);
  9745. EXPECT_EQ(StatusCode::OK_200, res->status);
  9746. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9747. }
  9748. }
  9749. #ifdef CPPHTTPLIB_SSL_ENABLED
  9750. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9751. Client cli("http://yahoo.com");
  9752. auto res = cli.Get("/");
  9753. ASSERT_TRUE(res);
  9754. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9755. cli.set_follow_location(true);
  9756. res = cli.Get("/");
  9757. ASSERT_TRUE(res);
  9758. EXPECT_EQ(StatusCode::OK_200, res->status);
  9759. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9760. }
  9761. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9762. Client cli("https://yahoo.com");
  9763. auto res = cli.Get("/");
  9764. ASSERT_TRUE(res);
  9765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9766. cli.set_follow_location(true);
  9767. res = cli.Get("/");
  9768. ASSERT_TRUE(res);
  9769. EXPECT_EQ(StatusCode::OK_200, res->status);
  9770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9771. }
  9772. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9773. Client cli("https://yahoo.com");
  9774. auto res = cli.Get("/");
  9775. ASSERT_TRUE(res);
  9776. ASSERT_FALSE(!res);
  9777. ASSERT_TRUE(res);
  9778. ASSERT_FALSE(res == nullptr);
  9779. ASSERT_TRUE(res != nullptr);
  9780. EXPECT_EQ(Error::Success, res.error());
  9781. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9782. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9783. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9784. cli.set_follow_location(true);
  9785. res = cli.Get("/");
  9786. ASSERT_TRUE(res);
  9787. EXPECT_EQ(Error::Success, res.error());
  9788. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9789. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9790. EXPECT_EQ(StatusCode::OK_200, res->status);
  9791. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9792. }
  9793. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9794. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9795. Client cli("https://cdnjs.cloudflare.com");
  9796. auto res =
  9797. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9798. ASSERT_TRUE(res);
  9799. EXPECT_EQ(StatusCode::OK_200, res->status);
  9800. EXPECT_EQ(287630U, res->body.size());
  9801. EXPECT_EQ("application/javascript; charset=utf-8",
  9802. res->get_header_value("Content-Type"));
  9803. }
  9804. #endif
  9805. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9806. #undef REDIR_HOST // Silence compiler warning
  9807. #define REDIR_HOST "https://httpbingo.org"
  9808. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9809. Client cli(REDIR_HOST);
  9810. cli.set_follow_location(true);
  9811. auto res =
  9812. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9813. ASSERT_TRUE(res);
  9814. EXPECT_EQ(StatusCode::OK_200, res->status);
  9815. }
  9816. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9817. Client cli(REDIR_HOST);
  9818. cli.set_follow_location(true);
  9819. Params params;
  9820. params.emplace("url", "http://example.com");
  9821. params.emplace("status_code", "302");
  9822. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9823. ASSERT_TRUE(res);
  9824. EXPECT_EQ(StatusCode::OK_200, res->status);
  9825. }
  9826. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9827. Client cli(REDIR_HOST);
  9828. cli.set_follow_location(true);
  9829. Params params;
  9830. params.emplace("url", "http://example.com");
  9831. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9832. ASSERT_TRUE(res);
  9833. EXPECT_EQ(StatusCode::OK_200, res->status);
  9834. }
  9835. TEST(HttpToHttpsRedirectTest, CertFile) {
  9836. auto ssl_port = PORT + 1;
  9837. Server svr;
  9838. ASSERT_TRUE(svr.is_valid());
  9839. svr.Get("/index", [&](const Request &, Response &res) {
  9840. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9841. "/index");
  9842. svr.stop();
  9843. });
  9844. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9845. ASSERT_TRUE(ssl_svr.is_valid());
  9846. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9847. res.set_content("test", "text/plain");
  9848. ssl_svr.stop();
  9849. });
  9850. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9851. thread t2 =
  9852. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9853. auto se = detail::scope_exit([&] {
  9854. t2.join();
  9855. t.join();
  9856. ASSERT_FALSE(svr.is_running());
  9857. });
  9858. svr.wait_until_ready();
  9859. ssl_svr.wait_until_ready();
  9860. Client cli("127.0.0.1", PORT);
  9861. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9862. cli.enable_server_certificate_verification(true);
  9863. cli.set_follow_location(true);
  9864. cli.set_connection_timeout(30);
  9865. auto res = cli.Get("/index");
  9866. ASSERT_TRUE(res);
  9867. ASSERT_EQ(StatusCode::OK_200, res->status);
  9868. }
  9869. TEST(SSLClientRedirectTest, CertFile) {
  9870. auto ssl_port = PORT + 1;
  9871. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9872. ASSERT_TRUE(ssl_svr1.is_valid());
  9873. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9874. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9875. "/index");
  9876. ssl_svr1.stop();
  9877. });
  9878. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9879. ASSERT_TRUE(ssl_svr2.is_valid());
  9880. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9881. res.set_content("test", "text/plain");
  9882. ssl_svr2.stop();
  9883. });
  9884. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9885. thread t2 =
  9886. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9887. auto se = detail::scope_exit([&] {
  9888. t2.join();
  9889. t.join();
  9890. ASSERT_FALSE(ssl_svr1.is_running());
  9891. });
  9892. ssl_svr1.wait_until_ready();
  9893. ssl_svr2.wait_until_ready();
  9894. SSLClient cli("127.0.0.1", PORT);
  9895. std::string cert;
  9896. read_file(SERVER_CERT2_FILE, cert);
  9897. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9898. cli.enable_server_certificate_verification(true);
  9899. cli.set_follow_location(true);
  9900. cli.set_connection_timeout(30);
  9901. auto res = cli.Get("/index");
  9902. ASSERT_TRUE(res);
  9903. ASSERT_EQ(StatusCode::OK_200, res->status);
  9904. }
  9905. #endif
  9906. #ifdef CPPHTTPLIB_SSL_ENABLED
  9907. // Test that set_ca_cert_store() skips system certs (consistent with
  9908. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9909. // should be trusted - system certs should NOT be loaded.
  9910. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9911. // Load a specific cert that is NOT a system CA cert
  9912. std::string cert;
  9913. read_file(SERVER_CERT2_FILE, cert);
  9914. SSLClient cli("google.com");
  9915. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9916. cli.enable_server_certificate_verification(true);
  9917. // This should FAIL because:
  9918. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9919. // 2. System certs should NOT be loaded when custom store is set
  9920. // If system certs WERE loaded, this would succeed
  9921. auto res = cli.Get("/");
  9922. ASSERT_FALSE(res);
  9923. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9924. }
  9925. // Same as above, but through the native store handle path. Regression test:
  9926. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  9927. // merged system certs into the user-provided store.
  9928. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  9929. std::string cert;
  9930. read_file(SERVER_CERT2_FILE, cert);
  9931. SSLClient cli("google.com");
  9932. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9933. cli.enable_server_certificate_verification(true);
  9934. auto res = cli.Get("/");
  9935. ASSERT_FALSE(res);
  9936. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9937. }
  9938. // A custom store set via the native handle must still verify a server whose
  9939. // cert it does contain.
  9940. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  9941. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9942. ASSERT_TRUE(svr.is_valid());
  9943. svr.Get("/test", [&](const Request &, Response &res) {
  9944. res.set_content("test", "text/plain");
  9945. });
  9946. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9947. auto se = detail::scope_exit([&] {
  9948. svr.stop();
  9949. t.join();
  9950. ASSERT_FALSE(svr.is_running());
  9951. });
  9952. svr.wait_until_ready();
  9953. SSLClient cli("127.0.0.1", PORT);
  9954. std::string cert;
  9955. read_file(SERVER_CERT2_FILE, cert);
  9956. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  9957. cli.enable_server_certificate_verification(true);
  9958. cli.set_connection_timeout(30);
  9959. auto res = cli.Get("/test");
  9960. ASSERT_TRUE(res);
  9961. ASSERT_EQ(StatusCode::OK_200, res->status);
  9962. }
  9963. // CA certs loaded through the universal Client must be transferred to the
  9964. // client created internally for following an HTTPS redirect. Regression test:
  9965. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  9966. // the CA data for redirect transfer.
  9967. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  9968. auto ssl_port = PORT + 1;
  9969. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9970. ASSERT_TRUE(ssl_svr1.is_valid());
  9971. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9972. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9973. "/index");
  9974. });
  9975. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9976. ASSERT_TRUE(ssl_svr2.is_valid());
  9977. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9978. res.set_content("test", "text/plain");
  9979. });
  9980. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9981. thread t2 =
  9982. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9983. auto se = detail::scope_exit([&] {
  9984. ssl_svr2.stop();
  9985. ssl_svr1.stop();
  9986. t2.join();
  9987. t.join();
  9988. ASSERT_FALSE(ssl_svr1.is_running());
  9989. });
  9990. ssl_svr1.wait_until_ready();
  9991. ssl_svr2.wait_until_ready();
  9992. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  9993. std::string cert;
  9994. read_file(SERVER_CERT2_FILE, cert);
  9995. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9996. cli.enable_server_certificate_verification(true);
  9997. cli.set_follow_location(true);
  9998. cli.set_connection_timeout(30);
  9999. auto res = cli.Get("/index");
  10000. ASSERT_TRUE(res);
  10001. ASSERT_EQ(StatusCode::OK_200, res->status);
  10002. }
  10003. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10004. // so a host signed by a system CA verifies even though a custom CA is set
  10005. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10006. std::string cert;
  10007. read_file(SERVER_CERT2_FILE, cert);
  10008. SSLClient cli("google.com");
  10009. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10010. cli.enable_system_ca(true);
  10011. cli.enable_server_certificate_verification(true);
  10012. auto res = cli.Get("/");
  10013. ASSERT_TRUE(res);
  10014. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10015. }
  10016. // The custom CA remains effective when combined with the system CA
  10017. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10018. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10019. ASSERT_TRUE(svr.is_valid());
  10020. svr.Get("/test", [&](const Request &, Response &res) {
  10021. res.set_content("test", "text/plain");
  10022. });
  10023. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  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. SSLClient cli("127.0.0.1", PORT);
  10031. std::string cert;
  10032. read_file(SERVER_CERT2_FILE, cert);
  10033. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10034. cli.enable_system_ca(true);
  10035. cli.enable_server_certificate_verification(true);
  10036. cli.set_connection_timeout(30);
  10037. auto res = cli.Get("/test");
  10038. ASSERT_TRUE(res);
  10039. ASSERT_EQ(StatusCode::OK_200, res->status);
  10040. }
  10041. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10042. // skip chain verification entirely (only the certificate identity was
  10043. // checked), so a server presenting an untrusted certificate with a matching
  10044. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10045. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10046. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10047. ASSERT_TRUE(svr.is_valid());
  10048. svr.Get("/test", [&](const Request &, Response &res) {
  10049. res.set_content("test", "text/plain");
  10050. });
  10051. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10052. auto se = detail::scope_exit([&] {
  10053. svr.stop();
  10054. t.join();
  10055. ASSERT_FALSE(svr.is_running());
  10056. });
  10057. svr.wait_until_ready();
  10058. SSLClient cli("127.0.0.1", PORT);
  10059. std::string cert;
  10060. // A trusted CA that did not sign the server certificate. The server cert
  10061. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10062. // this connection.
  10063. read_file(CLIENT_CA_CERT_FILE, cert);
  10064. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10065. cli.enable_server_certificate_verification(true);
  10066. cli.set_connection_timeout(30);
  10067. auto res = cli.Get("/test");
  10068. ASSERT_FALSE(res);
  10069. }
  10070. // enable_system_ca(false) prevents system CA loading entirely
  10071. TEST(SSLClientTest, DisableSystemCa_Online) {
  10072. SSLClient cli("google.com");
  10073. cli.enable_system_ca(false);
  10074. cli.enable_server_certificate_verification(true);
  10075. auto res = cli.Get("/");
  10076. ASSERT_FALSE(res);
  10077. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10078. // itself when the CA chain is empty
  10079. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10080. res.error() == Error::SSLConnection);
  10081. }
  10082. // The universal Client forwards enable_system_ca()
  10083. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10084. std::string cert;
  10085. read_file(SERVER_CERT2_FILE, cert);
  10086. Client cli("https://google.com");
  10087. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10088. cli.enable_system_ca(true);
  10089. cli.enable_server_certificate_verification(true);
  10090. auto res = cli.Get("/");
  10091. ASSERT_TRUE(res);
  10092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10093. }
  10094. // The system CA policy must carry over to the client created internally for
  10095. // following a cross-host HTTPS redirect
  10096. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10097. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10098. ASSERT_TRUE(svr.is_valid());
  10099. svr.Get("/index", [&](const Request &, Response &res) {
  10100. res.set_redirect("https://www.google.com/");
  10101. });
  10102. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10103. auto se = detail::scope_exit([&] {
  10104. svr.stop();
  10105. t.join();
  10106. ASSERT_FALSE(svr.is_running());
  10107. });
  10108. svr.wait_until_ready();
  10109. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10110. std::string cert;
  10111. read_file(SERVER_CERT2_FILE, cert);
  10112. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10113. cli.enable_system_ca(true);
  10114. cli.enable_server_certificate_verification(true);
  10115. cli.set_follow_location(true);
  10116. cli.set_connection_timeout(30);
  10117. // Receiving any response proves the redirect client completed the TLS
  10118. // handshake with a system-CA-signed host
  10119. auto res = cli.Get("/index");
  10120. ASSERT_TRUE(res);
  10121. }
  10122. TEST(MultipartFormDataTest, LargeData) {
  10123. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10124. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10125. const ContentReader &content_reader) {
  10126. if (req.is_multipart_form_data()) {
  10127. std::vector<FormData> items;
  10128. content_reader(
  10129. [&](const FormData &file) {
  10130. items.push_back(file);
  10131. return true;
  10132. },
  10133. [&](const char *data, size_t data_length) {
  10134. items.back().content.append(data, data_length);
  10135. return true;
  10136. });
  10137. EXPECT_TRUE(std::string(items[0].name) == "document");
  10138. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10139. EXPECT_TRUE(items[0].filename == "2MB_data");
  10140. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10141. EXPECT_TRUE(items[1].name == "hello");
  10142. EXPECT_TRUE(items[1].content == "world");
  10143. EXPECT_TRUE(items[1].filename == "");
  10144. EXPECT_TRUE(items[1].content_type == "");
  10145. } else {
  10146. std::string body;
  10147. content_reader([&](const char *data, size_t data_length) {
  10148. body.append(data, data_length);
  10149. return true;
  10150. });
  10151. }
  10152. });
  10153. auto port = svr.bind_to_any_port(HOST);
  10154. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10155. auto se = detail::scope_exit([&] {
  10156. svr.stop();
  10157. t.join();
  10158. ASSERT_FALSE(svr.is_running());
  10159. });
  10160. svr.wait_until_ready();
  10161. {
  10162. std::string data(1024 * 1024 * 2, '.');
  10163. std::stringstream buffer;
  10164. buffer << data;
  10165. SSLClient cli(HOST, port);
  10166. cli.enable_server_certificate_verification(false);
  10167. UploadFormDataItems items{
  10168. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10169. {"hello", "world", "", ""},
  10170. };
  10171. auto res = cli.Post("/post", items);
  10172. ASSERT_TRUE(res);
  10173. ASSERT_EQ(StatusCode::OK_200, res->status);
  10174. }
  10175. }
  10176. TEST(MultipartFormDataTest, DataProviderItems) {
  10177. std::random_device seed_gen;
  10178. std::mt19937 random(seed_gen());
  10179. std::string rand1;
  10180. rand1.resize(1000);
  10181. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10182. std::string rand2;
  10183. rand2.resize(3000);
  10184. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10186. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10187. const ContentReader &content_reader) {
  10188. ASSERT_FALSE(req.is_multipart_form_data());
  10189. std::string body;
  10190. content_reader([&](const char *data, size_t data_length) {
  10191. body.append(data, data_length);
  10192. return true;
  10193. });
  10194. EXPECT_EQ(body, "");
  10195. });
  10196. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10197. const ContentReader &content_reader) {
  10198. ASSERT_TRUE(req.is_multipart_form_data());
  10199. std::vector<FormData> items;
  10200. content_reader(
  10201. [&](const FormData &file) {
  10202. items.push_back(file);
  10203. return true;
  10204. },
  10205. [&](const char *data, size_t data_length) {
  10206. items.back().content.append(data, data_length);
  10207. return true;
  10208. });
  10209. ASSERT_TRUE(items.size() == 2);
  10210. EXPECT_EQ(std::string(items[0].name), "name1");
  10211. EXPECT_EQ(items[0].content, "Testing123");
  10212. EXPECT_EQ(items[0].filename, "filename1");
  10213. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10214. EXPECT_EQ(items[1].name, "name2");
  10215. EXPECT_EQ(items[1].content, "Testing456");
  10216. EXPECT_EQ(items[1].filename, "");
  10217. EXPECT_EQ(items[1].content_type, "");
  10218. });
  10219. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10220. const ContentReader &content_reader) {
  10221. ASSERT_TRUE(req.is_multipart_form_data());
  10222. std::vector<FormData> items;
  10223. content_reader(
  10224. [&](const FormData &file) {
  10225. items.push_back(file);
  10226. return true;
  10227. },
  10228. [&](const char *data, size_t data_length) {
  10229. items.back().content.append(data, data_length);
  10230. return true;
  10231. });
  10232. ASSERT_TRUE(items.size() == 2);
  10233. EXPECT_EQ(items[0].name, "name3");
  10234. EXPECT_EQ(items[0].content, rand1);
  10235. EXPECT_EQ(items[0].filename, "filename3");
  10236. EXPECT_EQ(items[0].content_type, "");
  10237. EXPECT_EQ(items[1].name, "name4");
  10238. EXPECT_EQ(items[1].content, rand2);
  10239. EXPECT_EQ(items[1].filename, "filename4");
  10240. EXPECT_EQ(items[1].content_type, "");
  10241. });
  10242. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10243. const ContentReader &content_reader) {
  10244. ASSERT_TRUE(req.is_multipart_form_data());
  10245. std::vector<FormData> items;
  10246. content_reader(
  10247. [&](const FormData &file) {
  10248. items.push_back(file);
  10249. return true;
  10250. },
  10251. [&](const char *data, size_t data_length) {
  10252. items.back().content.append(data, data_length);
  10253. return true;
  10254. });
  10255. ASSERT_TRUE(items.size() == 4);
  10256. EXPECT_EQ(std::string(items[0].name), "name1");
  10257. EXPECT_EQ(items[0].content, "Testing123");
  10258. EXPECT_EQ(items[0].filename, "filename1");
  10259. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10260. EXPECT_EQ(items[1].name, "name2");
  10261. EXPECT_EQ(items[1].content, "Testing456");
  10262. EXPECT_EQ(items[1].filename, "");
  10263. EXPECT_EQ(items[1].content_type, "");
  10264. EXPECT_EQ(items[2].name, "name3");
  10265. EXPECT_EQ(items[2].content, rand1);
  10266. EXPECT_EQ(items[2].filename, "filename3");
  10267. EXPECT_EQ(items[2].content_type, "");
  10268. EXPECT_EQ(items[3].name, "name4");
  10269. EXPECT_EQ(items[3].content, rand2);
  10270. EXPECT_EQ(items[3].filename, "filename4");
  10271. EXPECT_EQ(items[3].content_type, "");
  10272. });
  10273. auto port = svr.bind_to_any_port("localhost");
  10274. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10275. auto se = detail::scope_exit([&] {
  10276. svr.stop();
  10277. t.join();
  10278. ASSERT_FALSE(svr.is_running());
  10279. });
  10280. svr.wait_until_ready();
  10281. {
  10282. SSLClient cli("localhost", port);
  10283. cli.enable_server_certificate_verification(false);
  10284. UploadFormDataItems items{
  10285. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10286. {"name2", "Testing456", "", ""}, // not a file
  10287. };
  10288. {
  10289. auto res = cli.Post("/post-none", {}, {}, {});
  10290. ASSERT_TRUE(res);
  10291. ASSERT_EQ(StatusCode::OK_200, res->status);
  10292. }
  10293. FormDataProviderItems providers;
  10294. {
  10295. auto res =
  10296. cli.Post("/post-items", {}, items, providers); // empty providers
  10297. ASSERT_TRUE(res);
  10298. ASSERT_EQ(StatusCode::OK_200, res->status);
  10299. }
  10300. providers.push_back({"name3",
  10301. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10302. // test the offset is given correctly at each step
  10303. if (!offset)
  10304. sink.os.write(rand1.data(), 30);
  10305. else if (offset == 30)
  10306. sink.os.write(rand1.data() + 30, 300);
  10307. else if (offset == 330)
  10308. sink.os.write(rand1.data() + 330, 670);
  10309. else if (offset == rand1.size())
  10310. sink.done();
  10311. return true;
  10312. },
  10313. "filename3",
  10314. {}});
  10315. providers.push_back({"name4",
  10316. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10317. // test the offset is given correctly at each step
  10318. if (!offset)
  10319. sink.os.write(rand2.data(), 2000);
  10320. else if (offset == 2000)
  10321. sink.os.write(rand2.data() + 2000, 1);
  10322. else if (offset == 2001)
  10323. sink.os.write(rand2.data() + 2001, 999);
  10324. else if (offset == rand2.size())
  10325. sink.done();
  10326. return true;
  10327. },
  10328. "filename4",
  10329. {}});
  10330. {
  10331. auto res = cli.Post("/post-providers", {}, {}, providers);
  10332. ASSERT_TRUE(res);
  10333. ASSERT_EQ(StatusCode::OK_200, res->status);
  10334. }
  10335. {
  10336. auto res = cli.Post("/post-both", {}, items, providers);
  10337. ASSERT_TRUE(res);
  10338. ASSERT_EQ(StatusCode::OK_200, res->status);
  10339. }
  10340. }
  10341. }
  10342. TEST(MultipartFormDataTest, BadHeader) {
  10343. Server svr;
  10344. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10345. res.set_content("ok", "text/plain");
  10346. });
  10347. thread t = thread([&] { svr.listen(HOST, PORT); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. ASSERT_FALSE(svr.is_running());
  10352. });
  10353. svr.wait_until_ready();
  10354. const std::string body =
  10355. "This is the preamble. It is to be ignored, though it\r\n"
  10356. "is a handy place for composition agents to include an\r\n"
  10357. "explanatory note to non-MIME conformant readers.\r\n"
  10358. "\r\n"
  10359. "\r\n"
  10360. "--simple boundary\r\n"
  10361. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10362. ": BAD...\r\n"
  10363. "\r\n"
  10364. "value1\r\n"
  10365. "--simple boundary\r\n"
  10366. "Content-Disposition: form-data; name=\"field2\"; "
  10367. "filename=\"example.txt\"\r\n"
  10368. "\r\n"
  10369. "value2\r\n"
  10370. "--simple boundary--\r\n"
  10371. "This is the epilogue. It is also to be ignored.\r\n";
  10372. std::string content_type =
  10373. R"(multipart/form-data; boundary="simple boundary")";
  10374. Client cli(HOST, PORT);
  10375. auto res = cli.Post("/post", body, content_type.c_str());
  10376. ASSERT_TRUE(res);
  10377. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10378. }
  10379. TEST(MultipartFormDataTest, WithPreamble) {
  10380. Server svr;
  10381. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10382. res.set_content("ok", "text/plain");
  10383. });
  10384. thread t = thread([&] { svr.listen(HOST, PORT); });
  10385. auto se = detail::scope_exit([&] {
  10386. svr.stop();
  10387. t.join();
  10388. ASSERT_FALSE(svr.is_running());
  10389. });
  10390. svr.wait_until_ready();
  10391. const std::string body =
  10392. "This is the preamble. It is to be ignored, though it\r\n"
  10393. "is a handy place for composition agents to include an\r\n"
  10394. "explanatory note to non-MIME conformant readers.\r\n"
  10395. "\r\n"
  10396. "\r\n"
  10397. "--simple boundary\r\n"
  10398. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10399. "\r\n"
  10400. "value1\r\n"
  10401. "--simple boundary\r\n"
  10402. "Content-Disposition: form-data; name=\"field2\"; "
  10403. "filename=\"example.txt\"\r\n"
  10404. "\r\n"
  10405. "value2\r\n"
  10406. "--simple boundary--\r\n"
  10407. "This is the epilogue. It is also to be ignored.\r\n";
  10408. std::string content_type =
  10409. R"(multipart/form-data; boundary="simple boundary")";
  10410. Client cli(HOST, PORT);
  10411. auto res = cli.Post("/post", body, content_type.c_str());
  10412. ASSERT_TRUE(res);
  10413. EXPECT_EQ(StatusCode::OK_200, res->status);
  10414. }
  10415. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10417. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10418. const ContentReader &content_reader) {
  10419. if (req.is_multipart_form_data()) {
  10420. std::vector<FormData> items;
  10421. content_reader(
  10422. [&](const FormData &file) {
  10423. items.push_back(file);
  10424. return true;
  10425. },
  10426. [&](const char *data, size_t data_length) {
  10427. items.back().content.append(data, data_length);
  10428. return true;
  10429. });
  10430. EXPECT_TRUE(std::string(items[0].name) == "document");
  10431. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10432. EXPECT_TRUE(items[0].filename == "2MB_data");
  10433. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10434. EXPECT_TRUE(items[1].name == "hello");
  10435. EXPECT_TRUE(items[1].content == "world");
  10436. EXPECT_TRUE(items[1].filename == "");
  10437. EXPECT_TRUE(items[1].content_type == "");
  10438. } else {
  10439. std::string body;
  10440. content_reader([&](const char *data, size_t data_length) {
  10441. body.append(data, data_length);
  10442. return true;
  10443. });
  10444. }
  10445. });
  10446. auto port = svr.bind_to_any_port("localhost");
  10447. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10448. auto se = detail::scope_exit([&] {
  10449. svr.stop();
  10450. t.join();
  10451. ASSERT_FALSE(svr.is_running());
  10452. });
  10453. svr.wait_until_ready();
  10454. {
  10455. std::string data(1024 * 1024 * 2, '.');
  10456. std::stringstream buffer;
  10457. buffer << data;
  10458. SSLClient cli("localhost", port);
  10459. cli.enable_server_certificate_verification(false);
  10460. UploadFormDataItems items{
  10461. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10462. {"hello", "world", "", ""},
  10463. };
  10464. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10465. ASSERT_TRUE(res);
  10466. ASSERT_EQ(StatusCode::OK_200, res->status);
  10467. }
  10468. }
  10469. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10470. std::string data(1024 * 1024 * 2, '&');
  10471. std::stringstream buffer;
  10472. buffer << data;
  10473. Client cli("https://localhost:8080");
  10474. UploadFormDataItems items{
  10475. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10476. {"hello", "world", "", ""},
  10477. };
  10478. for (const char &c : " \t\r\n") {
  10479. auto res =
  10480. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10481. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10482. ASSERT_FALSE(res);
  10483. }
  10484. }
  10485. TEST(MultipartFormDataTest, PutFormData) {
  10486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10487. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10488. const ContentReader &content_reader) {
  10489. if (req.is_multipart_form_data()) {
  10490. std::vector<FormData> items;
  10491. content_reader(
  10492. [&](const FormData &file) {
  10493. items.push_back(file);
  10494. return true;
  10495. },
  10496. [&](const char *data, size_t data_length) {
  10497. items.back().content.append(data, data_length);
  10498. return true;
  10499. });
  10500. EXPECT_TRUE(std::string(items[0].name) == "document");
  10501. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10502. EXPECT_TRUE(items[0].filename == "2MB_data");
  10503. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10504. EXPECT_TRUE(items[1].name == "hello");
  10505. EXPECT_TRUE(items[1].content == "world");
  10506. EXPECT_TRUE(items[1].filename == "");
  10507. EXPECT_TRUE(items[1].content_type == "");
  10508. } else {
  10509. std::string body;
  10510. content_reader([&](const char *data, size_t data_length) {
  10511. body.append(data, data_length);
  10512. return true;
  10513. });
  10514. }
  10515. });
  10516. auto port = svr.bind_to_any_port("localhost");
  10517. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10518. auto se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. t.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. {
  10525. std::string data(1024 * 1024 * 2, '&');
  10526. std::stringstream buffer;
  10527. buffer << data;
  10528. SSLClient cli("localhost", port);
  10529. cli.enable_server_certificate_verification(false);
  10530. UploadFormDataItems items{
  10531. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10532. {"hello", "world", "", ""},
  10533. };
  10534. auto res = cli.Put("/put", items);
  10535. ASSERT_TRUE(res);
  10536. ASSERT_EQ(StatusCode::OK_200, res->status);
  10537. }
  10538. }
  10539. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10541. svr.Put("/put_customboundary",
  10542. [&](const Request &req, const Response & /*res*/,
  10543. const ContentReader &content_reader) {
  10544. if (req.is_multipart_form_data()) {
  10545. std::vector<FormData> items;
  10546. content_reader(
  10547. [&](const FormData &file) {
  10548. items.push_back(file);
  10549. return true;
  10550. },
  10551. [&](const char *data, size_t data_length) {
  10552. items.back().content.append(data, data_length);
  10553. return true;
  10554. });
  10555. EXPECT_TRUE(std::string(items[0].name) == "document");
  10556. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10557. EXPECT_TRUE(items[0].filename == "2MB_data");
  10558. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10559. EXPECT_TRUE(items[1].name == "hello");
  10560. EXPECT_TRUE(items[1].content == "world");
  10561. EXPECT_TRUE(items[1].filename == "");
  10562. EXPECT_TRUE(items[1].content_type == "");
  10563. } else {
  10564. std::string body;
  10565. content_reader([&](const char *data, size_t data_length) {
  10566. body.append(data, data_length);
  10567. return true;
  10568. });
  10569. }
  10570. });
  10571. auto port = svr.bind_to_any_port("localhost");
  10572. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10573. auto se = detail::scope_exit([&] {
  10574. svr.stop();
  10575. t.join();
  10576. ASSERT_FALSE(svr.is_running());
  10577. });
  10578. svr.wait_until_ready();
  10579. {
  10580. std::string data(1024 * 1024 * 2, '&');
  10581. std::stringstream buffer;
  10582. buffer << data;
  10583. SSLClient cli("localhost", port);
  10584. cli.enable_server_certificate_verification(false);
  10585. UploadFormDataItems items{
  10586. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10587. {"hello", "world", "", ""},
  10588. };
  10589. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10590. ASSERT_TRUE(res);
  10591. ASSERT_EQ(StatusCode::OK_200, res->status);
  10592. }
  10593. }
  10594. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10595. std::string data(1024 * 1024 * 2, '&');
  10596. std::stringstream buffer;
  10597. buffer << data;
  10598. Client cli("https://localhost:8080");
  10599. cli.enable_server_certificate_verification(false);
  10600. UploadFormDataItems items{
  10601. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10602. {"hello", "world", "", ""},
  10603. };
  10604. for (const char &c : " \t\r\n") {
  10605. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10606. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10607. ASSERT_FALSE(res);
  10608. }
  10609. }
  10610. TEST(MultipartFormDataTest, AlternateFilename) {
  10611. auto handled = false;
  10612. Server svr;
  10613. svr.Post("/test", [&](const Request &req, Response &res) {
  10614. ASSERT_EQ(2u, req.form.files.size());
  10615. ASSERT_EQ(1u, req.form.fields.size());
  10616. // Test files
  10617. const auto &file1 = req.form.get_file("file1");
  10618. ASSERT_EQ("file1", file1.name);
  10619. ASSERT_EQ("A.txt", file1.filename);
  10620. ASSERT_EQ("text/plain", file1.content_type);
  10621. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10622. const auto &file2 = req.form.get_file("file2");
  10623. ASSERT_EQ("file2", file2.name);
  10624. ASSERT_EQ("a.html", file2.filename);
  10625. ASSERT_EQ("text/html", file2.content_type);
  10626. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10627. file2.content);
  10628. // Test text field
  10629. const auto &text = req.form.get_field("text");
  10630. ASSERT_EQ("text default", text);
  10631. res.set_content("ok", "text/plain");
  10632. handled = true;
  10633. });
  10634. thread t = thread([&] { svr.listen(HOST, PORT); });
  10635. auto se = detail::scope_exit([&] {
  10636. svr.stop();
  10637. t.join();
  10638. ASSERT_FALSE(svr.is_running());
  10639. ASSERT_TRUE(handled);
  10640. });
  10641. svr.wait_until_ready();
  10642. auto req = "POST /test HTTP/1.1\r\n"
  10643. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10644. "Content-Length: 399\r\n"
  10645. "\r\n"
  10646. "----------\r\n"
  10647. "Content-Disposition: form-data; name=\"text\"\r\n"
  10648. "\r\n"
  10649. "text default\r\n"
  10650. "----------\r\n"
  10651. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10652. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10653. "Content-Type: text/plain\r\n"
  10654. "\r\n"
  10655. "Content of a.txt.\r\n"
  10656. "\r\n"
  10657. "----------\r\n"
  10658. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10659. "\"a.html\"\r\n"
  10660. "Content-Type: text/html\r\n"
  10661. "\r\n"
  10662. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10663. "\r\n"
  10664. "------------\r\n";
  10665. ASSERT_TRUE(send_request(1, req));
  10666. }
  10667. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10668. auto handled = false;
  10669. Server svr;
  10670. svr.Post("/test", [&](const Request &req, Response &res) {
  10671. // Case-insensitive "utf-8''" prefix with a long value
  10672. const auto &file = req.form.get_file("file1");
  10673. ASSERT_EQ("file1", file.name);
  10674. // 8000 chars exercises both the Content-Disposition parser and the
  10675. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10676. // Prior to the fix, std::regex_match on this header would cause O(N)
  10677. // stack recursion in libstdc++, leading to SIGSEGV.
  10678. std::string expected_filename(8000, 'A');
  10679. ASSERT_EQ(expected_filename, file.filename);
  10680. res.set_content("ok", "text/plain");
  10681. handled = true;
  10682. });
  10683. thread t = thread([&] { svr.listen(HOST, PORT); });
  10684. auto se = detail::scope_exit([&] {
  10685. svr.stop();
  10686. t.join();
  10687. ASSERT_FALSE(svr.is_running());
  10688. ASSERT_TRUE(handled);
  10689. });
  10690. svr.wait_until_ready();
  10691. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10692. // Regression test for GHSA-qq6v-r583-3h69
  10693. std::string long_filename(8000, 'A');
  10694. std::string body = "----------\r\n"
  10695. "Content-Disposition: form-data; name=\"file1\"; "
  10696. "filename*=\"Utf-8''" +
  10697. long_filename +
  10698. "\"\r\n"
  10699. "\r\n"
  10700. "hello\r\n"
  10701. "------------\r\n";
  10702. auto req = "POST /test HTTP/1.1\r\n"
  10703. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10704. "Content-Length: " +
  10705. std::to_string(body.size()) + "\r\n\r\n" + body;
  10706. ASSERT_TRUE(send_request(1, req));
  10707. }
  10708. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10709. auto handled = false;
  10710. Server svr;
  10711. svr.Post("/test", [&](const Request &req, Response &) {
  10712. ASSERT_EQ(2u, req.form.fields.size());
  10713. const auto &text1 = req.form.get_field("text1");
  10714. ASSERT_EQ("text1", text1);
  10715. const auto &text2 = req.form.get_field("text2");
  10716. ASSERT_EQ("text2", text2);
  10717. handled = true;
  10718. });
  10719. thread t = thread([&] { svr.listen(HOST, PORT); });
  10720. auto se = detail::scope_exit([&] {
  10721. svr.stop();
  10722. t.join();
  10723. ASSERT_FALSE(svr.is_running());
  10724. ASSERT_TRUE(handled);
  10725. });
  10726. svr.wait_until_ready();
  10727. auto req = "POST /test HTTP/1.1\r\n"
  10728. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10729. "Content-Length: 146\r\n"
  10730. "\r\n----------\r\n"
  10731. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10732. "\r\n"
  10733. "text1"
  10734. "\r\n----------\r\n"
  10735. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10736. "\r\n"
  10737. "text2"
  10738. "\r\n------------";
  10739. std::string response;
  10740. ASSERT_TRUE(send_request(1, req, &response));
  10741. ASSERT_EQ("200", response.substr(9, 3));
  10742. }
  10743. TEST(MultipartFormDataTest, ContentLength) {
  10744. auto handled = false;
  10745. Server svr;
  10746. svr.Post("/test", [&](const Request &req, Response &) {
  10747. ASSERT_EQ(2u, req.form.fields.size());
  10748. const auto &text1 = req.form.get_field("text1");
  10749. ASSERT_EQ("text1", text1);
  10750. const auto &text2 = req.form.get_field("text2");
  10751. ASSERT_EQ("text2", text2);
  10752. handled = true;
  10753. });
  10754. thread t = thread([&] { svr.listen(HOST, PORT); });
  10755. auto se = detail::scope_exit([&] {
  10756. svr.stop();
  10757. t.join();
  10758. ASSERT_FALSE(svr.is_running());
  10759. ASSERT_TRUE(handled);
  10760. });
  10761. svr.wait_until_ready();
  10762. auto req = "POST /test HTTP/1.1\r\n"
  10763. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10764. "Content-Length: 167\r\n"
  10765. "\r\n----------\r\n"
  10766. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10767. "Content-Length: 5\r\n"
  10768. "\r\n"
  10769. "text1"
  10770. "\r\n----------\r\n"
  10771. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10772. "\r\n"
  10773. "text2"
  10774. "\r\n------------\r\n";
  10775. std::string response;
  10776. ASSERT_TRUE(send_request(1, req, &response));
  10777. ASSERT_EQ("200", response.substr(9, 3));
  10778. }
  10779. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10780. auto handled = false;
  10781. Server svr;
  10782. svr.Post("/test", [&](const Request &req, Response &) {
  10783. ASSERT_EQ(2u, req.form.fields.size());
  10784. const auto &text1 = req.form.get_field("text1");
  10785. ASSERT_EQ("text1", text1);
  10786. // TODO: Add header access for text fields if needed
  10787. const auto &text2 = req.form.get_field("text2");
  10788. ASSERT_EQ("text2", text2);
  10789. // TODO: Header access for text fields needs to be implemented
  10790. // auto &headers = it->second.headers;
  10791. // ASSERT_EQ(3U, headers.size());
  10792. // auto custom_header = headers.find("x-whatever");
  10793. // ASSERT_TRUE(custom_header != headers.end());
  10794. // ASSERT_NE("customvalue", custom_header->second);
  10795. // ASSERT_EQ("CustomValue", custom_header->second);
  10796. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10797. handled = true;
  10798. });
  10799. thread t = thread([&] { svr.listen(HOST, PORT); });
  10800. auto se = detail::scope_exit([&] {
  10801. svr.stop();
  10802. t.join();
  10803. ASSERT_FALSE(svr.is_running());
  10804. ASSERT_TRUE(handled);
  10805. });
  10806. svr.wait_until_ready();
  10807. auto req = "POST /test HTTP/1.1\r\n"
  10808. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10809. "Content-Length: 232\r\n"
  10810. "\r\n----------\r\n"
  10811. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10812. "Content-Length: 5\r\n"
  10813. "X-Test: 1\r\n"
  10814. "\r\n"
  10815. "text1"
  10816. "\r\n----------\r\n"
  10817. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10818. "Content-Type: text/plain\r\n"
  10819. "X-Whatever: CustomValue\r\n"
  10820. "\r\n"
  10821. "text2"
  10822. "\r\n------------\r\n"
  10823. "That should be disregarded. Not even read";
  10824. std::string response;
  10825. ASSERT_TRUE(send_request(1, req, &response));
  10826. ASSERT_EQ("200", response.substr(9, 3));
  10827. }
  10828. TEST(MultipartFormDataTest, LargeHeader) {
  10829. auto handled = false;
  10830. Server svr;
  10831. svr.Post("/test", [&](const Request &req, Response &) {
  10832. ASSERT_EQ(1u, req.form.fields.size());
  10833. const auto &text = req.form.get_field("name1");
  10834. ASSERT_EQ("text1", text);
  10835. handled = true;
  10836. });
  10837. thread t = thread([&] { svr.listen(HOST, PORT); });
  10838. auto se = detail::scope_exit([&] {
  10839. svr.stop();
  10840. t.join();
  10841. ASSERT_FALSE(svr.is_running());
  10842. ASSERT_TRUE(handled);
  10843. });
  10844. svr.wait_until_ready();
  10845. auto boundary = std::string("cpp-httplib-multipart-data");
  10846. std::string content = "--" + boundary +
  10847. "\r\n"
  10848. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10849. "\r\n"
  10850. "text1\r\n"
  10851. "--" +
  10852. boundary + "--\r\n";
  10853. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10854. "Content-Type: multipart/form-data;boundary=" +
  10855. boundary +
  10856. "\r\n"
  10857. "Content-Length: " +
  10858. std::to_string(content.size()) +
  10859. "\r\n"
  10860. "Dummy-Header: ";
  10861. std::string header_suffix = "\r\n"
  10862. "\r\n";
  10863. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10864. size_t header_dummy_size =
  10865. read_buff_size -
  10866. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10867. auto header_dummy = std::string(header_dummy_size, '@');
  10868. auto req = header_prefix + header_dummy + header_suffix + content;
  10869. std::string response;
  10870. ASSERT_TRUE(send_request(1, req, &response));
  10871. ASSERT_EQ("200", response.substr(9, 3));
  10872. }
  10873. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10874. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10875. // (not chunked Transfer-Encoding) after the streaming refactor.
  10876. auto handled = false;
  10877. Server svr;
  10878. svr.Post("/upload", [&](const Request &req, Response &res) {
  10879. auto cl_it = req.headers.find("Content-Length");
  10880. EXPECT_TRUE(cl_it != req.headers.end());
  10881. auto te_it = req.headers.find("Transfer-Encoding");
  10882. EXPECT_TRUE(te_it == req.headers.end());
  10883. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10884. res.set_content("ok", "text/plain");
  10885. handled = true;
  10886. });
  10887. auto port = svr.bind_to_any_port(HOST);
  10888. auto t = thread([&] { svr.listen_after_bind(); });
  10889. auto se = detail::scope_exit([&] {
  10890. svr.stop();
  10891. t.join();
  10892. ASSERT_FALSE(svr.is_running());
  10893. ASSERT_TRUE(handled);
  10894. });
  10895. svr.wait_until_ready();
  10896. UploadFormDataItems items = {
  10897. {"field1", "hello", "", "text/plain"},
  10898. {"file1", "world", "test.txt", "application/octet-stream"},
  10899. };
  10900. Client cli(HOST, port);
  10901. auto res = cli.Post("/upload", {}, items);
  10902. ASSERT_TRUE(res);
  10903. EXPECT_EQ(StatusCode::OK_200, res->status);
  10904. }
  10905. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10906. // Verify that make_multipart_content_provider coalesces many small segments
  10907. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10908. constexpr size_t kItemCount = 1000;
  10909. UploadFormDataItems items;
  10910. items.reserve(kItemCount);
  10911. for (size_t i = 0; i < kItemCount; i++) {
  10912. items.push_back(
  10913. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10914. }
  10915. const std::string boundary = "----test-boundary";
  10916. auto content_length = detail::get_multipart_content_length(items, boundary);
  10917. auto provider = detail::make_multipart_content_provider(items, boundary);
  10918. // Drive the provider the same way write_content_with_progress does
  10919. size_t write_count = 0;
  10920. size_t total_bytes = 0;
  10921. DataSink sink;
  10922. size_t offset = 0;
  10923. sink.write = [&](const char *d, size_t l) -> bool {
  10924. (void)d;
  10925. write_count++;
  10926. total_bytes += l;
  10927. offset += l;
  10928. return true;
  10929. };
  10930. sink.is_writable = []() -> bool { return true; };
  10931. while (offset < content_length) {
  10932. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10933. }
  10934. EXPECT_EQ(content_length, total_bytes);
  10935. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10936. // With buffering into 64KB blocks, write_count should be much smaller.
  10937. auto segment_count = 3 * kItemCount + 1;
  10938. EXPECT_LT(write_count, segment_count / 10);
  10939. }
  10940. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10941. // Integration test: send many UploadFormDataItems and verify the server
  10942. // receives all of them correctly (#2410).
  10943. constexpr size_t kItemCount = 500;
  10944. auto handled = false;
  10945. Server svr;
  10946. svr.Post("/upload", [&](const Request &req, Response &res) {
  10947. EXPECT_EQ(kItemCount, req.form.fields.size());
  10948. for (size_t i = 0; i < kItemCount; i++) {
  10949. auto key = "field" + std::to_string(i);
  10950. auto val = "value" + std::to_string(i);
  10951. auto it = req.form.fields.find(key);
  10952. if (it != req.form.fields.end()) {
  10953. EXPECT_EQ(val, it->second.content);
  10954. } else {
  10955. ADD_FAILURE() << "Missing field: " << key;
  10956. }
  10957. }
  10958. res.set_content("ok", "text/plain");
  10959. handled = true;
  10960. });
  10961. auto port = svr.bind_to_any_port(HOST);
  10962. auto t = thread([&] { svr.listen_after_bind(); });
  10963. auto se = detail::scope_exit([&] {
  10964. svr.stop();
  10965. t.join();
  10966. ASSERT_FALSE(svr.is_running());
  10967. ASSERT_TRUE(handled);
  10968. });
  10969. svr.wait_until_ready();
  10970. UploadFormDataItems items;
  10971. items.reserve(kItemCount);
  10972. for (size_t i = 0; i < kItemCount; i++) {
  10973. items.push_back(
  10974. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10975. }
  10976. Client cli(HOST, port);
  10977. auto res = cli.Post("/upload", items);
  10978. ASSERT_TRUE(res);
  10979. EXPECT_EQ(StatusCode::OK_200, res->status);
  10980. }
  10981. TEST(MultipartFormDataTest, MakeFileProvider) {
  10982. // Verify make_file_provider sends a file's contents correctly.
  10983. const std::string file_content(4096, 'Z');
  10984. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10985. {
  10986. std::ofstream ofs(tmp_path, std::ios::binary);
  10987. ofs.write(file_content.data(),
  10988. static_cast<std::streamsize>(file_content.size()));
  10989. }
  10990. auto handled = false;
  10991. Server svr;
  10992. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10993. const ContentReader &content_reader) {
  10994. ASSERT_TRUE(req.is_multipart_form_data());
  10995. std::vector<FormData> items;
  10996. content_reader(
  10997. [&](const FormData &file) {
  10998. items.push_back(file);
  10999. return true;
  11000. },
  11001. [&](const char *data, size_t data_length) {
  11002. items.back().content.append(data, data_length);
  11003. return true;
  11004. });
  11005. ASSERT_EQ(1u, items.size());
  11006. EXPECT_EQ("myfile", items[0].name);
  11007. EXPECT_EQ("data.bin", items[0].filename);
  11008. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11009. EXPECT_EQ(file_content, items[0].content);
  11010. handled = true;
  11011. });
  11012. auto port = svr.bind_to_any_port(HOST);
  11013. auto t = thread([&] { svr.listen_after_bind(); });
  11014. auto se = detail::scope_exit([&] {
  11015. svr.stop();
  11016. t.join();
  11017. ASSERT_FALSE(svr.is_running());
  11018. ASSERT_TRUE(handled);
  11019. std::remove(tmp_path.c_str());
  11020. });
  11021. svr.wait_until_ready();
  11022. FormDataProviderItems providers;
  11023. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11024. "application/octet-stream"));
  11025. Client cli(HOST, port);
  11026. auto res = cli.Post("/upload", {}, {}, providers);
  11027. ASSERT_TRUE(res);
  11028. EXPECT_EQ(StatusCode::OK_200, res->status);
  11029. }
  11030. TEST(MakeFileBodyTest, Basic) {
  11031. const std::string file_content(4096, 'Z');
  11032. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11033. {
  11034. std::ofstream ofs(tmp_path, std::ios::binary);
  11035. ofs.write(file_content.data(),
  11036. static_cast<std::streamsize>(file_content.size()));
  11037. }
  11038. auto handled = false;
  11039. Server svr;
  11040. svr.Post("/upload", [&](const Request &req, Response &res) {
  11041. EXPECT_EQ(file_content, req.body);
  11042. handled = true;
  11043. res.status = StatusCode::OK_200;
  11044. });
  11045. auto port = svr.bind_to_any_port(HOST);
  11046. auto t = thread([&] { svr.listen_after_bind(); });
  11047. auto se = detail::scope_exit([&] {
  11048. svr.stop();
  11049. t.join();
  11050. ASSERT_FALSE(svr.is_running());
  11051. ASSERT_TRUE(handled);
  11052. std::remove(tmp_path.c_str());
  11053. });
  11054. svr.wait_until_ready();
  11055. auto fb = make_file_body(tmp_path);
  11056. ASSERT_GT(fb.first, 0u);
  11057. Client cli(HOST, port);
  11058. auto res =
  11059. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11060. ASSERT_TRUE(res);
  11061. EXPECT_EQ(StatusCode::OK_200, res->status);
  11062. }
  11063. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11064. static constexpr unsigned int number_of_tasks{1000000};
  11065. std::atomic_uint count{0};
  11066. std::unique_ptr<TaskQueue> task_queue{
  11067. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11068. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11069. auto queued = task_queue->enqueue(
  11070. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11071. EXPECT_TRUE(queued);
  11072. }
  11073. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11074. task_queue->shutdown();
  11075. #else
  11076. EXPECT_NO_THROW(task_queue->shutdown());
  11077. #endif
  11078. EXPECT_EQ(number_of_tasks, count.load());
  11079. }
  11080. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11081. static constexpr unsigned int number_of_tasks{1000000};
  11082. static constexpr unsigned int qlimit{2};
  11083. unsigned int queued_count{0};
  11084. std::atomic_uint count{0};
  11085. std::unique_ptr<TaskQueue> task_queue{
  11086. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11087. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11088. if (task_queue->enqueue(
  11089. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11090. queued_count++;
  11091. }
  11092. }
  11093. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11094. task_queue->shutdown();
  11095. #else
  11096. EXPECT_NO_THROW(task_queue->shutdown());
  11097. #endif
  11098. EXPECT_EQ(queued_count, count.load());
  11099. EXPECT_TRUE(queued_count <= number_of_tasks);
  11100. EXPECT_TRUE(queued_count >= qlimit);
  11101. }
  11102. TEST(TaskQueueTest, MaxQueuedRequests) {
  11103. static constexpr unsigned int qlimit{3};
  11104. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11105. std::condition_variable sem_cv;
  11106. std::mutex sem_mtx;
  11107. int credits = 0;
  11108. bool queued;
  11109. /* Fill up the queue with tasks that will block until we give them credits to
  11110. * complete. */
  11111. for (unsigned int n = 0; n <= qlimit;) {
  11112. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11113. std::unique_lock<std::mutex> lock(sem_mtx);
  11114. while (credits <= 0) {
  11115. sem_cv.wait(lock);
  11116. }
  11117. /* Consume the credit and signal the test code if they are all gone. */
  11118. if (--credits == 0) { sem_cv.notify_one(); }
  11119. });
  11120. if (n < qlimit) {
  11121. /* The first qlimit enqueues must succeed. */
  11122. EXPECT_TRUE(queued);
  11123. } else {
  11124. /* The last one will succeed only when the worker thread
  11125. * starts and dequeues the first blocking task. Although
  11126. * not necessary for the correctness of this test, we sleep for
  11127. * a short while to avoid busy waiting. */
  11128. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11129. }
  11130. if (queued) { n++; }
  11131. }
  11132. /* Further enqueues must fail since the queue is full. */
  11133. for (auto i = 0; i < 4; i++) {
  11134. queued = task_queue->enqueue([] {});
  11135. EXPECT_FALSE(queued);
  11136. }
  11137. /* Give the credits to allow the previous tasks to complete. */
  11138. {
  11139. std::unique_lock<std::mutex> lock(sem_mtx);
  11140. credits += qlimit + 1;
  11141. }
  11142. sem_cv.notify_all();
  11143. /* Wait for all the credits to be consumed. */
  11144. {
  11145. std::unique_lock<std::mutex> lock(sem_mtx);
  11146. while (credits > 0) {
  11147. sem_cv.wait(lock);
  11148. }
  11149. }
  11150. /* Check that we are able again to enqueue at least qlimit tasks. */
  11151. for (unsigned int i = 0; i < qlimit; i++) {
  11152. queued = task_queue->enqueue([] {});
  11153. EXPECT_TRUE(queued);
  11154. }
  11155. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11156. task_queue->shutdown();
  11157. #else
  11158. EXPECT_NO_THROW(task_queue->shutdown());
  11159. #endif
  11160. }
  11161. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11162. Server svr;
  11163. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11164. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11165. });
  11166. svr.Get("/hello", [](const Request &req, Response &res) {
  11167. res.set_content(req.get_param_value("key"), "text/plain");
  11168. });
  11169. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11170. auto se = detail::scope_exit([&] {
  11171. svr.stop();
  11172. thread.join();
  11173. ASSERT_FALSE(svr.is_running());
  11174. });
  11175. svr.wait_until_ready();
  11176. {
  11177. Client cli(HOST, PORT);
  11178. cli.set_follow_location(true);
  11179. auto res = cli.Get("/");
  11180. ASSERT_TRUE(res);
  11181. EXPECT_EQ(StatusCode::OK_200, res->status);
  11182. EXPECT_EQ("val&key2=val2", res->body);
  11183. }
  11184. }
  11185. #endif
  11186. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11187. Server svr;
  11188. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11189. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11190. });
  11191. svr.Get("/hello", [](const Request &req, Response &res) {
  11192. res.set_content(req.get_param_value("key"), "text/plain");
  11193. });
  11194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11195. auto se = detail::scope_exit([&] {
  11196. svr.stop();
  11197. thread.join();
  11198. ASSERT_FALSE(svr.is_running());
  11199. });
  11200. svr.wait_until_ready();
  11201. {
  11202. Client cli(HOST, PORT);
  11203. cli.set_follow_location(true);
  11204. auto res = cli.Get("/");
  11205. ASSERT_TRUE(res);
  11206. EXPECT_EQ(StatusCode::OK_200, res->status);
  11207. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11208. }
  11209. }
  11210. TEST(RedirectTest, RedirectWithPlusInPath) {
  11211. Server svr;
  11212. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11213. res.set_redirect("/a+b");
  11214. });
  11215. // Route pattern uses regex; escape + as \\+
  11216. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11217. res.set_content(req.path, "text/plain");
  11218. });
  11219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11220. auto se = detail::scope_exit([&] {
  11221. svr.stop();
  11222. thread.join();
  11223. ASSERT_FALSE(svr.is_running());
  11224. });
  11225. svr.wait_until_ready();
  11226. {
  11227. Client cli(HOST, PORT);
  11228. cli.set_follow_location(true);
  11229. auto res = cli.Get("/");
  11230. ASSERT_TRUE(res);
  11231. EXPECT_EQ(StatusCode::OK_200, res->status);
  11232. EXPECT_EQ("/a+b", res->body);
  11233. }
  11234. }
  11235. #ifdef CPPHTTPLIB_SSL_ENABLED
  11236. TEST(RedirectTest, Issue2185_Online) {
  11237. SSLClient client("github.com");
  11238. client.set_follow_location(true);
  11239. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11240. "Coollab-Windows.zip");
  11241. ASSERT_TRUE(res);
  11242. EXPECT_EQ(StatusCode::OK_200, res->status);
  11243. EXPECT_EQ(9920427U, res->body.size());
  11244. }
  11245. #endif
  11246. TEST(VulnerabilityTest, CRLFInjection) {
  11247. Server svr;
  11248. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11249. res.set_content("Hello 1", "text/plain");
  11250. });
  11251. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11252. res.set_content("Hello 2", "text/plain");
  11253. });
  11254. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11255. res.set_content("Hello 3", "text/plain");
  11256. });
  11257. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11258. res.set_content("Hello 4", "text/plain");
  11259. });
  11260. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11261. for (const auto &x : req.headers) {
  11262. auto key = x.first;
  11263. EXPECT_STRNE("evil", key.c_str());
  11264. }
  11265. });
  11266. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. thread.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. {
  11274. Client cli(HOST, PORT);
  11275. cli.Post("/test1", "A=B",
  11276. "application/x-www-form-urlencoded\r\nevil: hello1");
  11277. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11278. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11279. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11280. }
  11281. }
  11282. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11283. auto server_thread = std::thread([] {
  11284. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11285. default_socket_options(srv);
  11286. sockaddr_in addr{};
  11287. addr.sin_family = AF_INET;
  11288. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11289. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11290. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11291. ::listen(srv, 1);
  11292. sockaddr_in cli_addr{};
  11293. socklen_t cli_len = sizeof(cli_addr);
  11294. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11295. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11296. std::string buf_all;
  11297. char buf[2048];
  11298. ssize_t n;
  11299. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11300. buf_all.append(buf, static_cast<size_t>(n));
  11301. size_t pos;
  11302. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11303. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11304. auto e = request_block.find("\r\n");
  11305. if (e != std::string::npos) {
  11306. auto request_line = request_block.substr(0, e);
  11307. std::string msg =
  11308. "CRLF injection detected in request line: '" + request_line + "'";
  11309. EXPECT_FALSE(true) << msg;
  11310. }
  11311. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11312. ::send(cli,
  11313. #ifdef _WIN32
  11314. static_cast<const char *>(resp.c_str()),
  11315. static_cast<int>(resp.size()),
  11316. #else
  11317. resp.c_str(), resp.size(),
  11318. #endif
  11319. 0);
  11320. buf_all.erase(0, pos + 4);
  11321. }
  11322. }
  11323. detail::close_socket(cli);
  11324. detail::close_socket(srv);
  11325. });
  11326. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11327. auto cli = Client("127.0.0.1", PORT + 1);
  11328. auto headers = Headers{
  11329. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11330. {"Connection", "keep-alive"}};
  11331. auto res = cli.Get("/hi", headers);
  11332. EXPECT_FALSE(res);
  11333. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11334. server_thread.join();
  11335. }
  11336. TEST(PathParamsTest, StaticMatch) {
  11337. const auto pattern = "/users/all";
  11338. detail::PathParamsMatcher matcher(pattern);
  11339. Request request;
  11340. request.path = "/users/all";
  11341. ASSERT_TRUE(matcher.match(request));
  11342. std::unordered_map<std::string, std::string> expected_params = {};
  11343. EXPECT_EQ(request.path_params, expected_params);
  11344. }
  11345. TEST(PathParamsTest, StaticMismatch) {
  11346. const auto pattern = "/users/all";
  11347. detail::PathParamsMatcher matcher(pattern);
  11348. Request request;
  11349. request.path = "/users/1";
  11350. ASSERT_FALSE(matcher.match(request));
  11351. }
  11352. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11353. const auto pattern = "/users/:id/subscriptions";
  11354. detail::PathParamsMatcher matcher(pattern);
  11355. Request request;
  11356. request.path = "/users/42/subscriptions";
  11357. ASSERT_TRUE(matcher.match(request));
  11358. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11359. EXPECT_EQ(request.path_params, expected_params);
  11360. }
  11361. TEST(PathParamsTest, SingleParamInTheEnd) {
  11362. const auto pattern = "/users/:id";
  11363. detail::PathParamsMatcher matcher(pattern);
  11364. Request request;
  11365. request.path = "/users/24";
  11366. ASSERT_TRUE(matcher.match(request));
  11367. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11368. EXPECT_EQ(request.path_params, expected_params);
  11369. }
  11370. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11371. const auto pattern = "/users/:id/";
  11372. detail::PathParamsMatcher matcher(pattern);
  11373. Request request;
  11374. request.path = "/users/42/";
  11375. ASSERT_TRUE(matcher.match(request));
  11376. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11377. EXPECT_EQ(request.path_params, expected_params);
  11378. }
  11379. TEST(PathParamsTest, EmptyParam) {
  11380. const auto pattern = "/users/:id/";
  11381. detail::PathParamsMatcher matcher(pattern);
  11382. Request request;
  11383. request.path = "/users//";
  11384. ASSERT_TRUE(matcher.match(request));
  11385. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11386. EXPECT_EQ(request.path_params, expected_params);
  11387. }
  11388. TEST(PathParamsTest, FragmentMismatch) {
  11389. const auto pattern = "/users/:id/";
  11390. detail::PathParamsMatcher matcher(pattern);
  11391. Request request;
  11392. request.path = "/admins/24/";
  11393. ASSERT_FALSE(matcher.match(request));
  11394. }
  11395. TEST(PathParamsTest, ExtraFragments) {
  11396. const auto pattern = "/users/:id";
  11397. detail::PathParamsMatcher matcher(pattern);
  11398. Request request;
  11399. request.path = "/users/42/subscriptions";
  11400. ASSERT_FALSE(matcher.match(request));
  11401. }
  11402. TEST(PathParamsTest, MissingTrailingParam) {
  11403. const auto pattern = "/users/:id";
  11404. detail::PathParamsMatcher matcher(pattern);
  11405. Request request;
  11406. request.path = "/users";
  11407. ASSERT_FALSE(matcher.match(request));
  11408. }
  11409. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11410. const auto pattern = "/users/:id/subscriptions";
  11411. detail::PathParamsMatcher matcher(pattern);
  11412. Request request;
  11413. request.path = "/users/subscriptions";
  11414. ASSERT_FALSE(matcher.match(request));
  11415. }
  11416. TEST(PathParamsTest, MultipleParams) {
  11417. const auto pattern = "/users/:userid/subscriptions/:subid";
  11418. detail::PathParamsMatcher matcher(pattern);
  11419. Request request;
  11420. request.path = "/users/42/subscriptions/2";
  11421. ASSERT_TRUE(matcher.match(request));
  11422. std::unordered_map<std::string, std::string> expected_params = {
  11423. {"userid", "42"}, {"subid", "2"}};
  11424. EXPECT_EQ(request.path_params, expected_params);
  11425. }
  11426. TEST(PathParamsTest, SequenceOfParams) {
  11427. const auto pattern = "/values/:x/:y/:z";
  11428. detail::PathParamsMatcher matcher(pattern);
  11429. Request request;
  11430. request.path = "/values/1/2/3";
  11431. ASSERT_TRUE(matcher.match(request));
  11432. std::unordered_map<std::string, std::string> expected_params = {
  11433. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11434. EXPECT_EQ(request.path_params, expected_params);
  11435. }
  11436. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11437. const auto pattern = "/prefix:suffix";
  11438. detail::PathParamsMatcher matcher(pattern);
  11439. Request request;
  11440. request.path = "/prefix:suffix";
  11441. ASSERT_TRUE(matcher.match(request));
  11442. const std::unordered_map<std::string, std::string> expected_params = {};
  11443. EXPECT_EQ(request.path_params, expected_params);
  11444. }
  11445. TEST(ParseUrlTest, VariousPatterns) {
  11446. {
  11447. detail::UrlComponents uc;
  11448. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11449. EXPECT_EQ("http", uc.scheme);
  11450. EXPECT_EQ("example.com", uc.host);
  11451. EXPECT_EQ("8080", uc.port);
  11452. EXPECT_EQ("/path", uc.path);
  11453. EXPECT_EQ("?q=1", uc.query);
  11454. }
  11455. {
  11456. detail::UrlComponents uc;
  11457. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11458. EXPECT_EQ("https", uc.scheme);
  11459. EXPECT_EQ("example.com", uc.host);
  11460. EXPECT_TRUE(uc.port.empty());
  11461. EXPECT_EQ("/path", uc.path);
  11462. }
  11463. {
  11464. detail::UrlComponents uc;
  11465. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11466. EXPECT_EQ("::1", uc.host);
  11467. EXPECT_EQ("8080", uc.port);
  11468. EXPECT_EQ("/path", uc.path);
  11469. }
  11470. {
  11471. detail::UrlComponents uc;
  11472. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11473. }
  11474. {
  11475. detail::UrlComponents uc;
  11476. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11477. EXPECT_TRUE(uc.scheme.empty());
  11478. EXPECT_EQ("example.com", uc.host);
  11479. EXPECT_EQ("/path", uc.path);
  11480. EXPECT_EQ("?q=1", uc.query);
  11481. }
  11482. {
  11483. detail::UrlComponents uc;
  11484. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11485. EXPECT_TRUE(uc.host.empty());
  11486. EXPECT_EQ("/path", uc.path);
  11487. EXPECT_EQ("?q=1", uc.query);
  11488. }
  11489. {
  11490. detail::UrlComponents uc;
  11491. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11492. EXPECT_EQ("example.com", uc.host);
  11493. EXPECT_EQ("8080", uc.port);
  11494. }
  11495. {
  11496. // Unix socket path — must not be parsed as host
  11497. detail::UrlComponents uc;
  11498. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11499. EXPECT_TRUE(uc.host.empty());
  11500. }
  11501. {
  11502. detail::UrlComponents uc;
  11503. ASSERT_TRUE(detail::parse_url("", uc));
  11504. EXPECT_TRUE(uc.host.empty());
  11505. EXPECT_TRUE(uc.path.empty());
  11506. }
  11507. {
  11508. detail::UrlComponents uc;
  11509. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11510. }
  11511. {
  11512. detail::UrlComponents uc;
  11513. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11514. }
  11515. {
  11516. // Accepted by parse_url; callers restrict to http/https
  11517. detail::UrlComponents uc;
  11518. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11519. EXPECT_EQ("ftp", uc.scheme);
  11520. }
  11521. {
  11522. detail::UrlComponents uc;
  11523. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11524. }
  11525. {
  11526. detail::UrlComponents uc;
  11527. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11528. }
  11529. }
  11530. TEST(ParseUrlTest, FragmentHandling) {
  11531. {
  11532. detail::UrlComponents uc;
  11533. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11534. EXPECT_EQ("/path", uc.path);
  11535. EXPECT_TRUE(uc.query.empty());
  11536. }
  11537. {
  11538. detail::UrlComponents uc;
  11539. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11540. EXPECT_TRUE(uc.path.empty());
  11541. EXPECT_TRUE(uc.query.empty());
  11542. }
  11543. }
  11544. TEST(ParseUrlTest, UserinfoHandling) {
  11545. // Userinfo with @ but no colon — host includes @
  11546. detail::UrlComponents uc;
  11547. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11548. EXPECT_EQ("user@host.com", uc.host);
  11549. EXPECT_EQ("/path", uc.path);
  11550. }
  11551. TEST(ParseUrlTest, IPv6EdgeCases) {
  11552. {
  11553. detail::UrlComponents uc;
  11554. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11555. EXPECT_TRUE(uc.scheme.empty());
  11556. EXPECT_EQ("::1", uc.host);
  11557. EXPECT_EQ("8080", uc.port);
  11558. }
  11559. {
  11560. // Zone ID '%25' is not in [a-fA-F0-9:]
  11561. detail::UrlComponents uc;
  11562. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11563. }
  11564. }
  11565. TEST(ParseUrlTest, SchemeEdgeCases) {
  11566. {
  11567. detail::UrlComponents uc;
  11568. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11569. }
  11570. {
  11571. detail::UrlComponents uc;
  11572. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11573. }
  11574. {
  11575. detail::UrlComponents uc;
  11576. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11577. }
  11578. }
  11579. TEST(ParseUrlTest, PortEdgeCases) {
  11580. {
  11581. detail::UrlComponents uc;
  11582. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11583. EXPECT_TRUE(uc.port.empty());
  11584. EXPECT_EQ("/path", uc.path);
  11585. }
  11586. {
  11587. // parse_url accepts any port string; validation is done by parse_port
  11588. detail::UrlComponents uc;
  11589. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11590. EXPECT_EQ("abc", uc.port);
  11591. }
  11592. }
  11593. TEST(ParseUrlTest, WebSocketPatterns) {
  11594. {
  11595. detail::UrlComponents uc;
  11596. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11597. EXPECT_EQ("ws", uc.scheme);
  11598. EXPECT_EQ("echo.example.com", uc.host);
  11599. EXPECT_EQ("8080", uc.port);
  11600. EXPECT_EQ("/ws", uc.path);
  11601. }
  11602. {
  11603. detail::UrlComponents uc;
  11604. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11605. EXPECT_EQ("wss", uc.scheme);
  11606. EXPECT_EQ("echo.example.com", uc.host);
  11607. EXPECT_TRUE(uc.port.empty());
  11608. EXPECT_EQ("/ws", uc.path);
  11609. }
  11610. }
  11611. TEST(ParseUrlTest, QueryOnly) {
  11612. detail::UrlComponents uc;
  11613. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11614. EXPECT_TRUE(uc.host.empty());
  11615. EXPECT_TRUE(uc.path.empty());
  11616. EXPECT_EQ("?q=1&r=2", uc.query);
  11617. }
  11618. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11619. detail::UrlComponents uc;
  11620. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11621. EXPECT_TRUE(uc.scheme.empty());
  11622. EXPECT_EQ("example.com", uc.host);
  11623. EXPECT_EQ("443", uc.port);
  11624. EXPECT_EQ("/path", uc.path);
  11625. }
  11626. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11627. // If ipv6 regex working, regex match codepath is taken.
  11628. // else port will default to 80 in Client impl
  11629. int clientImplMagicPort = 80;
  11630. int port = 4321;
  11631. // above ports must be different to avoid false negative
  11632. EXPECT_NE(clientImplMagicPort, port);
  11633. std::string ipV6TestURL = "http://[ff06::c3]";
  11634. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11635. CLIENT_PRIVATE_KEY_FILE);
  11636. EXPECT_EQ(cli.port(), port);
  11637. }
  11638. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11639. auto file_path = "./www/dir/index.html";
  11640. auto dir_path = "./www/dir";
  11641. detail::FileStat stat_file(file_path);
  11642. EXPECT_TRUE(stat_file.is_file());
  11643. EXPECT_FALSE(stat_file.is_dir());
  11644. detail::FileStat stat_dir(dir_path);
  11645. EXPECT_FALSE(stat_dir.is_file());
  11646. EXPECT_TRUE(stat_dir.is_dir());
  11647. }
  11648. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11649. // IPv4 with default HTTP port (80)
  11650. EXPECT_EQ("example.com",
  11651. detail::make_host_and_port_string("example.com", 80, false));
  11652. // IPv4 with default HTTPS port (443)
  11653. EXPECT_EQ("example.com",
  11654. detail::make_host_and_port_string("example.com", 443, true));
  11655. // IPv4 with non-default HTTP port
  11656. EXPECT_EQ("example.com:8080",
  11657. detail::make_host_and_port_string("example.com", 8080, false));
  11658. // IPv4 with non-default HTTPS port
  11659. EXPECT_EQ("example.com:8443",
  11660. detail::make_host_and_port_string("example.com", 8443, true));
  11661. // IPv6 with default HTTP port (80)
  11662. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11663. // IPv6 with default HTTPS port (443)
  11664. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11665. // IPv6 with non-default HTTP port
  11666. EXPECT_EQ("[::1]:8080",
  11667. detail::make_host_and_port_string("::1", 8080, false));
  11668. // IPv6 with non-default HTTPS port
  11669. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11670. // IPv6 full address with default port
  11671. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11672. detail::make_host_and_port_string(
  11673. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11674. // IPv6 full address with non-default port
  11675. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11676. detail::make_host_and_port_string(
  11677. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11678. // IPv6 localhost with non-default port
  11679. EXPECT_EQ("[::1]:3000",
  11680. detail::make_host_and_port_string("::1", 3000, false));
  11681. // IPv6 with zone ID (link-local address) with default port
  11682. EXPECT_EQ("[fe80::1%eth0]",
  11683. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11684. // IPv6 with zone ID (link-local address) with non-default port
  11685. EXPECT_EQ("[fe80::1%eth0]:8080",
  11686. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11687. // Edge case: Port 443 with is_ssl=false (should add port)
  11688. EXPECT_EQ("example.com:443",
  11689. detail::make_host_and_port_string("example.com", 443, false));
  11690. // Edge case: Port 80 with is_ssl=true (should add port)
  11691. EXPECT_EQ("example.com:80",
  11692. detail::make_host_and_port_string("example.com", 80, true));
  11693. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11694. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11695. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11696. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11697. // Security fix: Already bracketed IPv6 should not get double brackets
  11698. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11699. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11700. EXPECT_EQ("[::1]:8080",
  11701. detail::make_host_and_port_string("[::1]", 8080, false));
  11702. EXPECT_EQ("[2001:db8::1]:8080",
  11703. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11704. EXPECT_EQ("[fe80::1%eth0]",
  11705. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11706. EXPECT_EQ("[fe80::1%eth0]:8080",
  11707. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11708. // Edge case: Empty host (should return as-is)
  11709. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11710. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11711. // This is a known limitation but shouldn't crash
  11712. EXPECT_EQ("[host:name]",
  11713. detail::make_host_and_port_string("host:name", 80, false));
  11714. // Port number edge cases (no validation, but should not crash)
  11715. EXPECT_EQ("example.com:0",
  11716. detail::make_host_and_port_string("example.com", 0, false));
  11717. EXPECT_EQ("example.com:-1",
  11718. detail::make_host_and_port_string("example.com", -1, false));
  11719. EXPECT_EQ("example.com:65535",
  11720. detail::make_host_and_port_string("example.com", 65535, false));
  11721. EXPECT_EQ("example.com:65536",
  11722. detail::make_host_and_port_string("example.com", 65536, false));
  11723. }
  11724. #ifdef CPPHTTPLIB_SSL_ENABLED
  11725. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11726. httplib::SSLClient cli("roblox.com", 443);
  11727. cli.set_follow_location(true);
  11728. auto res = cli.Get("/");
  11729. ASSERT_TRUE(res);
  11730. EXPECT_EQ(StatusCode::OK_200, res->status);
  11731. }
  11732. #endif
  11733. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11734. Server svr;
  11735. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11736. EXPECT_EQ(res.status, 400);
  11737. });
  11738. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11739. auto se = detail::scope_exit([&] {
  11740. svr.stop();
  11741. thread.join();
  11742. ASSERT_FALSE(svr.is_running());
  11743. });
  11744. svr.wait_until_ready();
  11745. Client cli(HOST, PORT);
  11746. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11747. }
  11748. TEST(InvalidHeaderCharsTest, is_field_name) {
  11749. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11750. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11751. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11752. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11753. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11754. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11755. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11756. EXPECT_FALSE(detail::fields::is_field_name(""));
  11757. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11758. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11759. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11760. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11761. }
  11762. TEST(InvalidHeaderCharsTest, is_field_value) {
  11763. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11764. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11765. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11766. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11767. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11768. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11769. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11770. EXPECT_TRUE(detail::fields::is_field_value(""));
  11771. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11772. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11773. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11774. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11775. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11776. }
  11777. TEST(InvalidHeaderCharsTest, OnServer) {
  11778. Server svr;
  11779. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11780. std::string header = "Not Set";
  11781. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11782. res.set_header(header, "value");
  11783. res.set_content("Page Content Page Content", "text/plain");
  11784. });
  11785. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11786. std::string header = "Not Set";
  11787. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11788. res.set_header("X-Test", header);
  11789. res.set_content("Page Content Page Content", "text/plain");
  11790. });
  11791. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11792. auto se = detail::scope_exit([&] {
  11793. svr.stop();
  11794. thread.join();
  11795. ASSERT_FALSE(svr.is_running());
  11796. });
  11797. svr.wait_until_ready();
  11798. Client cli(HOST, PORT);
  11799. {
  11800. auto res = cli.Get(
  11801. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11802. ASSERT_TRUE(res);
  11803. EXPECT_EQ("Page Content Page Content", res->body);
  11804. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11805. }
  11806. {
  11807. auto res = cli.Get(
  11808. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11809. ASSERT_TRUE(res);
  11810. EXPECT_EQ("Page Content Page Content", res->body);
  11811. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11812. }
  11813. }
  11814. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11815. auto handled = false;
  11816. Server svr;
  11817. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11818. thread t = thread([&] { svr.listen(HOST, PORT); });
  11819. auto se = detail::scope_exit([&] {
  11820. svr.stop();
  11821. t.join();
  11822. ASSERT_FALSE(svr.is_running());
  11823. ASSERT_FALSE(handled);
  11824. });
  11825. svr.wait_until_ready();
  11826. auto req = "POST /test HTTP/1.1\r\n"
  11827. "Content-Length: x\r\n"
  11828. "\r\n";
  11829. std::string response;
  11830. ASSERT_TRUE(send_request(1, req, &response));
  11831. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11832. response.substr(0, response.find("\r\n")));
  11833. }
  11834. #ifndef _WIN32
  11835. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11836. static constexpr char reject[] = "Unauthorized";
  11837. static constexpr char accept[] = "Upload accepted";
  11838. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11839. Server svr;
  11840. svr.set_expect_100_continue_handler(
  11841. [](const Request & /*req*/, Response &res) {
  11842. res.status = StatusCode::Unauthorized_401;
  11843. res.set_content(reject, "text/plain");
  11844. return res.status;
  11845. });
  11846. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11847. res.set_content(accept, "text/plain");
  11848. });
  11849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11850. auto se = detail::scope_exit([&] {
  11851. svr.stop();
  11852. thread.join();
  11853. ASSERT_FALSE(svr.is_running());
  11854. });
  11855. svr.wait_until_ready();
  11856. {
  11857. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11858. curl_easy_init(), &curl_easy_cleanup};
  11859. ASSERT_NE(curl, nullptr);
  11860. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11861. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11862. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11863. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11864. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11865. &curl_slist_free_all};
  11866. ASSERT_NE(list, nullptr);
  11867. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11868. struct read_data {
  11869. size_t read_size;
  11870. size_t total_size;
  11871. } data = {0, total_size};
  11872. using read_callback_t =
  11873. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11874. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11875. void *userdata) -> size_t {
  11876. read_data *d = (read_data *)userdata;
  11877. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11878. std::fill_n(ptr, size * nmemb, 'A');
  11879. d->read_size += size * nmemb;
  11880. return size * nmemb;
  11881. };
  11882. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11883. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11884. std::vector<char> buffer;
  11885. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11886. using write_callback_t =
  11887. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11888. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11889. void *userdata) -> size_t {
  11890. std::vector<char> *buf = (std::vector<char> *)userdata;
  11891. buf->reserve(buf->size() + size * nmemb + 1);
  11892. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11893. return size * nmemb;
  11894. };
  11895. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11896. {
  11897. const auto res = curl_easy_perform(curl.get());
  11898. ASSERT_EQ(res, CURLE_OK);
  11899. }
  11900. {
  11901. auto response_code = long{};
  11902. const auto res =
  11903. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11904. ASSERT_EQ(res, CURLE_OK);
  11905. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11906. }
  11907. {
  11908. auto dl = curl_off_t{};
  11909. const auto res =
  11910. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11911. ASSERT_EQ(res, CURLE_OK);
  11912. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11913. }
  11914. {
  11915. buffer.push_back('\0');
  11916. ASSERT_STRCASEEQ(buffer.data(), reject);
  11917. }
  11918. }
  11919. }
  11920. #endif
  11921. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  11922. // Regression test for #2458.
  11923. //
  11924. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  11925. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  11926. // ticket can make the client socket spuriously readable during the
  11927. // 100-continue wait. If the readiness is mistaken for an incoming response,
  11928. // the client withholds the body and then blocks reading a response that never
  11929. // comes, failing with `Failed to read connection`.
  11930. //
  11931. // A correct client (like curl) sends the body once no `100 Continue` arrives
  11932. // within the timeout. This raw OpenSSL server deliberately never sends
  11933. // `100 Continue`; the client must still deliver the body and receive 200.
  11934. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  11935. signal(SIGPIPE, SIG_IGN);
  11936. const auto port = PORT + 4;
  11937. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11938. ASSERT_NE(srv, INVALID_SOCKET);
  11939. int opt = 1;
  11940. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  11941. sockaddr_in addr{};
  11942. addr.sin_family = AF_INET;
  11943. addr.sin_port = htons(static_cast<uint16_t>(port));
  11944. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11945. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11946. ASSERT_EQ(0, ::listen(srv, 1));
  11947. std::atomic<size_t> server_body_bytes{0};
  11948. auto server_thread = std::thread([&] {
  11949. sockaddr_in cli_addr{};
  11950. socklen_t cli_len = sizeof(cli_addr);
  11951. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11952. if (cli == INVALID_SOCKET) { return; }
  11953. // Bound the lifetime of the server side so a buggy client (which never
  11954. // sends the body) cannot make this thread block forever on join.
  11955. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  11956. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  11957. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  11958. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  11959. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  11960. SSL *ssl = SSL_new(ctx);
  11961. SSL_set_fd(ssl, static_cast<int>(cli));
  11962. if (SSL_accept(ssl) > 0) {
  11963. // Read the request headers. Reading here also flushes the TLS 1.3
  11964. // session tickets to the client. Deliberately do NOT send
  11965. // `100 Continue`.
  11966. std::string buf;
  11967. char tmp[1024];
  11968. while (buf.find("\r\n\r\n") == std::string::npos) {
  11969. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11970. if (n <= 0) { break; }
  11971. buf.append(tmp, static_cast<size_t>(n));
  11972. }
  11973. // A correct client sends the body now; count what arrives.
  11974. auto pos = buf.find("\r\n\r\n");
  11975. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  11976. while (body < 4096) {
  11977. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11978. if (n <= 0) { break; }
  11979. body += static_cast<size_t>(n);
  11980. }
  11981. server_body_bytes = body;
  11982. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  11983. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  11984. SSL_shutdown(ssl);
  11985. }
  11986. SSL_free(ssl);
  11987. detail::close_socket(cli);
  11988. SSL_CTX_free(ctx);
  11989. });
  11990. auto se = detail::scope_exit([&] {
  11991. server_thread.join();
  11992. detail::close_socket(srv);
  11993. });
  11994. SSLClient cli("127.0.0.1", port);
  11995. cli.enable_server_certificate_verification(false);
  11996. cli.set_connection_timeout(5, 0);
  11997. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  11998. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  11999. std::string body(4096, 'A');
  12000. auto res = cli.Put("/api/test", body, "application/json");
  12001. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12002. EXPECT_EQ(StatusCode::OK_200, res->status);
  12003. EXPECT_EQ(body.size(), server_body_bytes.load());
  12004. }
  12005. #endif
  12006. template <typename S, typename C>
  12007. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12008. svr.Get("/stream", [&](const Request &, Response &res) {
  12009. auto data = new std::string("01234567890123456789");
  12010. res.set_content_provider(
  12011. data->size(), "text/plain",
  12012. [&, data](size_t offset, size_t length, DataSink &sink) {
  12013. const size_t DATA_CHUNK_SIZE = 4;
  12014. const auto &d = *data;
  12015. std::this_thread::sleep_for(std::chrono::seconds(1));
  12016. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12017. return true;
  12018. },
  12019. [data](bool success) {
  12020. EXPECT_FALSE(success);
  12021. delete data;
  12022. });
  12023. });
  12024. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12025. auto i = new size_t(0);
  12026. res.set_content_provider(
  12027. "text/plain",
  12028. [i](size_t, DataSink &sink) {
  12029. if (*i < 5) {
  12030. std::this_thread::sleep_for(std::chrono::seconds(1));
  12031. sink.write("abcd", 4);
  12032. (*i)++;
  12033. } else {
  12034. sink.done();
  12035. }
  12036. return true;
  12037. },
  12038. [i](bool success) {
  12039. EXPECT_FALSE(success);
  12040. delete i;
  12041. });
  12042. });
  12043. svr.Get("/chunked", [&](const Request &, Response &res) {
  12044. auto i = new size_t(0);
  12045. res.set_chunked_content_provider(
  12046. "text/plain",
  12047. [i](size_t, DataSink &sink) {
  12048. if (*i < 5) {
  12049. std::this_thread::sleep_for(std::chrono::seconds(1));
  12050. sink.os << "abcd";
  12051. (*i)++;
  12052. } else {
  12053. sink.done();
  12054. }
  12055. return true;
  12056. },
  12057. [i](bool success) {
  12058. EXPECT_FALSE(success);
  12059. delete i;
  12060. });
  12061. });
  12062. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12063. auto se = detail::scope_exit([&] {
  12064. svr.stop();
  12065. listen_thread.join();
  12066. ASSERT_FALSE(svr.is_running());
  12067. });
  12068. svr.wait_until_ready();
  12069. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12070. {
  12071. auto start = std::chrono::steady_clock::now();
  12072. auto res = cli.Get("/stream");
  12073. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12074. std::chrono::steady_clock::now() - start)
  12075. .count();
  12076. ASSERT_FALSE(res);
  12077. EXPECT_EQ(Error::Read, res.error());
  12078. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12079. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12080. }
  12081. {
  12082. auto start = std::chrono::steady_clock::now();
  12083. auto res = cli.Get("/stream_without_length");
  12084. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12085. std::chrono::steady_clock::now() - start)
  12086. .count();
  12087. ASSERT_FALSE(res);
  12088. EXPECT_EQ(Error::Read, res.error());
  12089. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12090. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12091. }
  12092. {
  12093. auto start = std::chrono::steady_clock::now();
  12094. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12095. EXPECT_EQ("abcd", string(data, data_length));
  12096. return true;
  12097. });
  12098. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12099. std::chrono::steady_clock::now() - start)
  12100. .count();
  12101. ASSERT_FALSE(res);
  12102. EXPECT_EQ(Error::Read, res.error());
  12103. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12104. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12105. }
  12106. }
  12107. TEST(MaxTimeoutTest, ContentStream) {
  12108. time_t timeout = 2000;
  12109. time_t threshold = 200;
  12110. Server svr;
  12111. Client cli("localhost", PORT);
  12112. max_timeout_test(svr, cli, timeout, threshold);
  12113. }
  12114. #ifdef CPPHTTPLIB_SSL_ENABLED
  12115. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12116. time_t timeout = 2000;
  12117. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12119. SSLClient cli("localhost", PORT);
  12120. cli.enable_server_certificate_verification(false);
  12121. max_timeout_test(svr, cli, timeout, threshold);
  12122. }
  12123. #endif
  12124. class EventDispatcher {
  12125. public:
  12126. EventDispatcher() {}
  12127. bool wait_event(DataSink *sink) {
  12128. unique_lock<mutex> lk(m_);
  12129. int id = id_;
  12130. // Wait with timeout to prevent hanging if client disconnects
  12131. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12132. [&] { return cid_ == id; })) {
  12133. return false; // Timeout occurred
  12134. }
  12135. sink->write(message_.data(), message_.size());
  12136. return true;
  12137. }
  12138. void send_event(const string &message) {
  12139. lock_guard<mutex> lk(m_);
  12140. cid_ = id_++;
  12141. message_ = message;
  12142. cv_.notify_all();
  12143. }
  12144. private:
  12145. mutex m_;
  12146. condition_variable cv_;
  12147. atomic_int id_{0};
  12148. atomic_int cid_{-1};
  12149. string message_;
  12150. };
  12151. TEST(ClientInThreadTest, Issue2068) {
  12152. EventDispatcher ed;
  12153. Server svr;
  12154. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12155. res.set_chunked_content_provider("text/event-stream",
  12156. [&](size_t /*offset*/, DataSink &sink) {
  12157. return ed.wait_event(&sink);
  12158. });
  12159. });
  12160. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12161. svr.wait_until_ready();
  12162. thread event_thread([&] {
  12163. int id = 0;
  12164. while (svr.is_running()) {
  12165. this_thread::sleep_for(chrono::milliseconds(500));
  12166. std::stringstream ss;
  12167. ss << "data: " << id << "\n\n";
  12168. ed.send_event(ss.str());
  12169. id++;
  12170. }
  12171. });
  12172. auto se = detail::scope_exit([&] {
  12173. svr.stop();
  12174. listen_thread.join();
  12175. event_thread.join();
  12176. ASSERT_FALSE(svr.is_running());
  12177. });
  12178. {
  12179. auto client = detail::make_unique<Client>(HOST, PORT);
  12180. client->set_read_timeout(std::chrono::minutes(10));
  12181. std::atomic<bool> stop{false};
  12182. std::thread t([&] {
  12183. client->Get("/event1",
  12184. [&](const char *, size_t) -> bool { return !stop; });
  12185. });
  12186. std::this_thread::sleep_for(std::chrono::seconds(2));
  12187. stop = true;
  12188. client->stop();
  12189. t.join();
  12190. // Reset client after thread has finished
  12191. client.reset();
  12192. }
  12193. }
  12194. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12195. auto handled = false;
  12196. Server svr;
  12197. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12199. auto se = detail::scope_exit([&] {
  12200. svr.stop();
  12201. t.join();
  12202. ASSERT_FALSE(svr.is_running());
  12203. ASSERT_FALSE(handled);
  12204. });
  12205. svr.wait_until_ready();
  12206. // Two Content-Length headers with different values — must be rejected
  12207. auto req = "POST /test HTTP/1.1\r\n"
  12208. "Content-Length: 5\r\n"
  12209. "Content-Length: 10\r\n"
  12210. "\r\n"
  12211. "hello";
  12212. std::string response;
  12213. ASSERT_TRUE(send_request(1, req, &response));
  12214. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12215. response.substr(0, response.find("\r\n")));
  12216. }
  12217. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12218. auto handled = false;
  12219. Server svr;
  12220. svr.Post("/test", [&](const Request &, Response &res) {
  12221. handled = true;
  12222. res.set_content("ok", "text/plain");
  12223. });
  12224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12225. auto se = detail::scope_exit([&] {
  12226. svr.stop();
  12227. t.join();
  12228. ASSERT_FALSE(svr.is_running());
  12229. ASSERT_TRUE(handled);
  12230. });
  12231. svr.wait_until_ready();
  12232. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12233. auto req = "POST /test HTTP/1.1\r\n"
  12234. "Content-Length: 5\r\n"
  12235. "Content-Length: 5\r\n"
  12236. "\r\n"
  12237. "hello";
  12238. std::string response;
  12239. ASSERT_TRUE(send_request(1, req, &response));
  12240. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12241. }
  12242. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12243. Server svr;
  12244. svr.Get("/", [](const Request &req, Response &res) {
  12245. EXPECT_EQ(2U, req.trailers.size());
  12246. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12247. // Denied
  12248. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12249. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12250. // Accepted
  12251. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12252. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12253. EXPECT_TRUE(req.has_trailer("X-World"));
  12254. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12255. res.set_content("ok", "text/plain");
  12256. });
  12257. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12258. auto se = detail::scope_exit([&] {
  12259. svr.stop();
  12260. t.join();
  12261. ASSERT_FALSE(svr.is_running());
  12262. });
  12263. svr.wait_until_ready();
  12264. const std::string req = "GET / HTTP/1.1\r\n"
  12265. "Transfer-Encoding: chunked\r\n"
  12266. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12267. "\r\n"
  12268. "0\r\n"
  12269. "Content-Length: 10\r\n"
  12270. "Host: internal.local\r\n"
  12271. "Content-Type: malicious/content\r\n"
  12272. "Cookie: any\r\n"
  12273. "Set-Cookie: any\r\n"
  12274. "X-Forwarded-For: attacker.com\r\n"
  12275. "X-Real-Ip: 1.1.1.1\r\n"
  12276. "X-Hello: hello\r\n"
  12277. "X-World: world\r\n"
  12278. "\r\n";
  12279. std::string res;
  12280. ASSERT_TRUE(send_request(1, req, &res));
  12281. }
  12282. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12283. Server svr;
  12284. std::string observed_remote_addr;
  12285. std::string observed_xff;
  12286. svr.Get("/ip", [&](const Request &req, Response &res) {
  12287. observed_remote_addr = req.remote_addr;
  12288. observed_xff = req.get_header_value("X-Forwarded-For");
  12289. res.set_content("ok", "text/plain");
  12290. });
  12291. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12292. auto se = detail::scope_exit([&] {
  12293. svr.stop();
  12294. t.join();
  12295. ASSERT_FALSE(svr.is_running());
  12296. });
  12297. svr.wait_until_ready();
  12298. Client cli(HOST, PORT);
  12299. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  12300. ASSERT_TRUE(res);
  12301. EXPECT_EQ(StatusCode::OK_200, res->status);
  12302. EXPECT_EQ(observed_xff, "203.0.113.66");
  12303. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12304. observed_remote_addr == "127.0.0.1");
  12305. }
  12306. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12307. Server svr;
  12308. svr.set_trusted_proxies({"203.0.113.66"});
  12309. std::string observed_remote_addr;
  12310. std::string observed_xff;
  12311. svr.Get("/ip", [&](const Request &req, Response &res) {
  12312. observed_remote_addr = req.remote_addr;
  12313. observed_xff = req.get_header_value("X-Forwarded-For");
  12314. res.set_content("ok", "text/plain");
  12315. });
  12316. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12317. auto se = detail::scope_exit([&] {
  12318. svr.stop();
  12319. t.join();
  12320. ASSERT_FALSE(svr.is_running());
  12321. });
  12322. svr.wait_until_ready();
  12323. Client cli(HOST, PORT);
  12324. auto res = cli.Get("/ip");
  12325. ASSERT_TRUE(res);
  12326. EXPECT_EQ(StatusCode::OK_200, res->status);
  12327. EXPECT_EQ(observed_xff, "");
  12328. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12329. observed_remote_addr == "127.0.0.1");
  12330. }
  12331. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12332. Server svr;
  12333. svr.set_trusted_proxies({"203.0.113.66"});
  12334. std::string observed_remote_addr;
  12335. std::string observed_xff;
  12336. svr.Get("/ip", [&](const Request &req, Response &res) {
  12337. observed_remote_addr = req.remote_addr;
  12338. observed_xff = req.get_header_value("X-Forwarded-For");
  12339. res.set_content("ok", "text/plain");
  12340. });
  12341. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12342. auto se = detail::scope_exit([&] {
  12343. svr.stop();
  12344. t.join();
  12345. ASSERT_FALSE(svr.is_running());
  12346. });
  12347. svr.wait_until_ready();
  12348. Client cli(HOST, PORT);
  12349. auto res =
  12350. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12351. ASSERT_TRUE(res);
  12352. EXPECT_EQ(StatusCode::OK_200, res->status);
  12353. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12354. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12355. }
  12356. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12357. Server svr;
  12358. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12359. std::string observed_remote_addr;
  12360. std::string observed_xff;
  12361. svr.Get("/ip", [&](const Request &req, Response &res) {
  12362. observed_remote_addr = req.remote_addr;
  12363. observed_xff = req.get_header_value("X-Forwarded-For");
  12364. res.set_content("ok", "text/plain");
  12365. });
  12366. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12367. auto se = detail::scope_exit([&] {
  12368. svr.stop();
  12369. t.join();
  12370. ASSERT_FALSE(svr.is_running());
  12371. });
  12372. svr.wait_until_ready();
  12373. Client cli(HOST, PORT);
  12374. auto res = cli.Get(
  12375. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12376. ASSERT_TRUE(res);
  12377. EXPECT_EQ(StatusCode::OK_200, res->status);
  12378. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12379. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12380. }
  12381. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12382. Server svr;
  12383. svr.set_trusted_proxies({"192.0.2.45"});
  12384. std::string observed_remote_addr;
  12385. std::string observed_xff;
  12386. svr.Get("/ip", [&](const Request &req, Response &res) {
  12387. observed_remote_addr = req.remote_addr;
  12388. observed_xff = req.get_header_value("X-Forwarded-For");
  12389. res.set_content("ok", "text/plain");
  12390. });
  12391. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12392. auto se = detail::scope_exit([&] {
  12393. svr.stop();
  12394. t.join();
  12395. ASSERT_FALSE(svr.is_running());
  12396. });
  12397. svr.wait_until_ready();
  12398. Client cli(HOST, PORT);
  12399. auto res =
  12400. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12401. ASSERT_TRUE(res);
  12402. EXPECT_EQ(StatusCode::OK_200, res->status);
  12403. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12404. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12405. }
  12406. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12407. Server svr;
  12408. svr.set_trusted_proxies({"192.0.2.45"});
  12409. std::string observed_remote_addr;
  12410. std::string observed_xff;
  12411. svr.Get("/ip", [&](const Request &req, Response &res) {
  12412. observed_remote_addr = req.remote_addr;
  12413. observed_xff = req.get_header_value("X-Forwarded-For");
  12414. res.set_content("ok", "text/plain");
  12415. });
  12416. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12417. auto se = detail::scope_exit([&] {
  12418. svr.stop();
  12419. t.join();
  12420. ASSERT_FALSE(svr.is_running());
  12421. });
  12422. svr.wait_until_ready();
  12423. Client cli(HOST, PORT);
  12424. auto res = cli.Get(
  12425. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12426. ASSERT_TRUE(res);
  12427. EXPECT_EQ(StatusCode::OK_200, res->status);
  12428. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12429. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12430. }
  12431. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12432. Server svr;
  12433. svr.set_trusted_proxies({"192.0.2.45"});
  12434. std::string observed_remote_addr;
  12435. std::string observed_xff;
  12436. svr.Get("/ip", [&](const Request &req, Response &res) {
  12437. observed_remote_addr = req.remote_addr;
  12438. observed_xff = req.get_header_value("X-Forwarded-For");
  12439. res.set_content("ok", "text/plain");
  12440. });
  12441. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12442. auto se = detail::scope_exit([&] {
  12443. svr.stop();
  12444. t.join();
  12445. ASSERT_FALSE(svr.is_running());
  12446. });
  12447. svr.wait_until_ready();
  12448. std::string raw_req =
  12449. "GET /ip HTTP/1.1\r\n"
  12450. "Host: localhost\r\n"
  12451. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12452. "Connection: close\r\n"
  12453. "\r\n";
  12454. std::string out;
  12455. ASSERT_TRUE(send_request(5, raw_req, &out));
  12456. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12457. // Header parser trims surrounding whitespace of the header value
  12458. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12459. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12460. }
  12461. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12462. // crash the server (it used to call front() on an empty vector inside
  12463. // get_client_ip). The connection-level remote address must be retained instead.
  12464. static void run_malformed_xff_test(const std::string &xff_value) {
  12465. Server svr;
  12466. svr.set_trusted_proxies({"192.0.2.45"});
  12467. std::string observed_remote_addr;
  12468. svr.Get("/ip", [&](const Request &req, Response &res) {
  12469. observed_remote_addr = req.remote_addr;
  12470. res.set_content("ok", "text/plain");
  12471. });
  12472. int port = 0;
  12473. thread t = thread([&]() {
  12474. port = svr.bind_to_any_port(HOST);
  12475. svr.listen_after_bind();
  12476. });
  12477. auto se = detail::scope_exit([&] {
  12478. svr.stop();
  12479. t.join();
  12480. ASSERT_FALSE(svr.is_running());
  12481. });
  12482. svr.wait_until_ready();
  12483. Client cli(HOST, port);
  12484. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12485. ASSERT_TRUE(res);
  12486. EXPECT_EQ(StatusCode::OK_200, res->status);
  12487. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12488. observed_remote_addr == "127.0.0.1");
  12489. }
  12490. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12491. run_malformed_xff_test("");
  12492. }
  12493. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12494. run_malformed_xff_test(",");
  12495. }
  12496. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12497. run_malformed_xff_test(", , ,");
  12498. }
  12499. #ifndef _WIN32
  12500. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12501. Server svr;
  12502. svr.Post("/post", [&](const Request &req, Response &res) {
  12503. res.set_content(req.body, "text/plain");
  12504. });
  12505. svr.Put("/put", [&](const Request &req, Response &res) {
  12506. res.set_content(req.body, "text/plain");
  12507. });
  12508. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12509. res.set_content(req.body, "text/plain");
  12510. });
  12511. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12512. res.set_content(req.body, "text/plain");
  12513. });
  12514. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12515. auto se = detail::scope_exit([&] {
  12516. svr.stop();
  12517. t.join();
  12518. ASSERT_FALSE(svr.is_running());
  12519. });
  12520. svr.wait_until_ready();
  12521. std::string resp;
  12522. // POST without Content-Length
  12523. ASSERT_TRUE(send_request(5,
  12524. "POST /post HTTP/1.1\r\n"
  12525. "Host: localhost\r\n"
  12526. "Connection: close\r\n"
  12527. "\r\n",
  12528. &resp));
  12529. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12530. // PUT without Content-Length
  12531. resp.clear();
  12532. ASSERT_TRUE(send_request(5,
  12533. "PUT /put HTTP/1.1\r\n"
  12534. "Host: localhost\r\n"
  12535. "Connection: close\r\n"
  12536. "\r\n",
  12537. &resp));
  12538. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12539. // PATCH without Content-Length
  12540. resp.clear();
  12541. ASSERT_TRUE(send_request(5,
  12542. "PATCH /patch HTTP/1.1\r\n"
  12543. "Host: localhost\r\n"
  12544. "Connection: close\r\n"
  12545. "\r\n",
  12546. &resp));
  12547. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12548. // DELETE without Content-Length
  12549. resp.clear();
  12550. ASSERT_TRUE(send_request(5,
  12551. "DELETE /delete HTTP/1.1\r\n"
  12552. "Host: localhost\r\n"
  12553. "Connection: close\r\n"
  12554. "\r\n",
  12555. &resp));
  12556. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12557. }
  12558. #endif
  12559. //==============================================================================
  12560. // open_stream() Tests
  12561. //==============================================================================
  12562. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12563. std::string result;
  12564. char buf[8192];
  12565. ssize_t n;
  12566. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12567. result.append(buf, static_cast<size_t>(n));
  12568. }
  12569. return result;
  12570. }
  12571. // Mock stream for unit tests
  12572. class MockStream : public Stream {
  12573. public:
  12574. std::string data;
  12575. size_t pos = 0;
  12576. ssize_t error_after = -1; // -1 = no error
  12577. explicit MockStream(const std::string &d, ssize_t err = -1)
  12578. : data(d), error_after(err) {}
  12579. bool is_readable() const override { return true; }
  12580. bool wait_readable() const override { return true; }
  12581. bool wait_writable() const override { return true; }
  12582. ssize_t read(char *ptr, size_t size) override {
  12583. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12584. if (pos >= data.size()) return 0;
  12585. size_t limit =
  12586. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12587. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12588. std::memcpy(ptr, data.data() + pos, to_read);
  12589. pos += to_read;
  12590. return static_cast<ssize_t>(to_read);
  12591. }
  12592. ssize_t write(const char *, size_t) override { return -1; }
  12593. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12594. ip = "127.0.0.1";
  12595. port = 0;
  12596. }
  12597. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12598. ip = "127.0.0.1";
  12599. port = 0;
  12600. }
  12601. socket_t socket() const override { return INVALID_SOCKET; }
  12602. time_t duration() const override { return 0; }
  12603. };
  12604. TEST(StreamHandleTest, Basic) {
  12605. ClientImpl::StreamHandle handle;
  12606. EXPECT_FALSE(handle.is_valid());
  12607. handle.response = detail::make_unique<Response>();
  12608. handle.error = Error::Connection;
  12609. EXPECT_FALSE(handle.is_valid());
  12610. handle.error = Error::Success;
  12611. EXPECT_TRUE(handle.is_valid());
  12612. }
  12613. TEST(BodyReaderTest, Basic) {
  12614. MockStream stream("Hello, World!");
  12615. detail::BodyReader reader;
  12616. reader.stream = &stream;
  12617. reader.content_length = 13;
  12618. char buf[32];
  12619. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12620. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12621. EXPECT_TRUE(reader.eof);
  12622. }
  12623. TEST(BodyReaderTest, NoStream) {
  12624. detail::BodyReader reader;
  12625. char buf[32];
  12626. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12627. EXPECT_EQ(Error::Connection, reader.last_error);
  12628. }
  12629. TEST(BodyReaderTest, Error) {
  12630. MockStream stream("Hello, World!", 5);
  12631. detail::BodyReader reader;
  12632. reader.stream = &stream;
  12633. reader.content_length = 13;
  12634. char buf[32];
  12635. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12636. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12637. EXPECT_EQ(Error::Read, reader.last_error);
  12638. }
  12639. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12640. // Mock-based StreamHandle tests relying on private internals are removed.
  12641. class OpenStreamTest : public ::testing::Test {
  12642. protected:
  12643. void SetUp() override {
  12644. svr_.Get("/hello", [](const Request &, Response &res) {
  12645. res.set_content("Hello World!", "text/plain");
  12646. });
  12647. svr_.Get("/large", [](const Request &, Response &res) {
  12648. res.set_content(std::string(10000, 'X'), "text/plain");
  12649. });
  12650. svr_.Get("/chunked", [](const Request &, Response &res) {
  12651. res.set_chunked_content_provider("text/plain",
  12652. [](size_t offset, DataSink &sink) {
  12653. if (offset < 15) {
  12654. sink.write("chunk", 5);
  12655. return true;
  12656. }
  12657. sink.done();
  12658. return true;
  12659. });
  12660. });
  12661. svr_.Get("/compressible", [](const Request &, Response &res) {
  12662. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12663. DataSink &sink) {
  12664. if (offset < 100 * 1024) {
  12665. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12666. sink.write(chunk.data(), chunk.size());
  12667. return true;
  12668. }
  12669. sink.done();
  12670. return true;
  12671. });
  12672. });
  12673. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12674. [](const Request & /*req*/, Response &res) {
  12675. auto i = new int(0);
  12676. res.set_header("Trailer", "Content-Length, X-Allowed");
  12677. res.set_chunked_content_provider(
  12678. "text/plain",
  12679. [i](size_t /*offset*/, DataSink &sink) {
  12680. switch (*i) {
  12681. case 0: sink.os << "123"; break;
  12682. case 1: sink.os << "456"; break;
  12683. case 2: sink.os << "789"; break;
  12684. case 3: {
  12685. sink.done_with_trailer(
  12686. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12687. } break;
  12688. }
  12689. (*i)++;
  12690. return true;
  12691. },
  12692. [i](bool success) {
  12693. EXPECT_TRUE(success);
  12694. delete i;
  12695. });
  12696. });
  12697. // Echo headers endpoint for header-related tests
  12698. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12699. std::string body;
  12700. for (const auto &h : req.headers) {
  12701. body.append(h.first);
  12702. body.push_back(':');
  12703. body.append(h.second);
  12704. body.push_back('\n');
  12705. }
  12706. res.set_content(body, "text/plain");
  12707. });
  12708. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12709. std::string body;
  12710. for (const auto &h : req.headers) {
  12711. body.append(h.first);
  12712. body.push_back(':');
  12713. body.append(h.second);
  12714. body.push_back('\n');
  12715. }
  12716. res.set_content(body, "text/plain");
  12717. });
  12718. port_ = svr_.bind_to_any_port("127.0.0.1");
  12719. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12720. svr_.wait_until_ready();
  12721. }
  12722. void TearDown() override {
  12723. svr_.stop();
  12724. if (thread_.joinable()) thread_.join();
  12725. }
  12726. Server svr_;
  12727. std::thread thread_;
  12728. int port_ = 0;
  12729. };
  12730. TEST_F(OpenStreamTest, Basic) {
  12731. Client cli("127.0.0.1", port_);
  12732. auto handle = cli.open_stream("GET", "/hello");
  12733. EXPECT_TRUE(handle.is_valid());
  12734. EXPECT_EQ("Hello World!", read_all(handle));
  12735. }
  12736. TEST_F(OpenStreamTest, SmallBuffer) {
  12737. Client cli("127.0.0.1", port_);
  12738. auto handle = cli.open_stream("GET", "/hello");
  12739. std::string result;
  12740. char buf[4];
  12741. ssize_t n;
  12742. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12743. result.append(buf, static_cast<size_t>(n));
  12744. EXPECT_EQ("Hello World!", result);
  12745. }
  12746. TEST_F(OpenStreamTest, DefaultHeaders) {
  12747. Client cli("127.0.0.1", port_);
  12748. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12749. {
  12750. auto handle = cli.open_stream("GET", "/echo-headers");
  12751. ASSERT_TRUE(handle.is_valid());
  12752. auto body = read_all(handle);
  12753. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12754. std::string::npos);
  12755. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12756. std::string::npos);
  12757. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12758. }
  12759. // open_stream POST with body and no explicit content_type should NOT add
  12760. // text/plain Content-Type (behavior differs from non-streaming path), but
  12761. // should include Content-Length
  12762. {
  12763. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12764. ASSERT_TRUE(handle.is_valid());
  12765. auto body = read_all(handle);
  12766. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12767. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12768. }
  12769. // open_stream POST with explicit Content-Type should preserve it
  12770. {
  12771. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12772. {{"Content-Type", "application/custom"}},
  12773. "{}", "application/custom");
  12774. ASSERT_TRUE(handle.is_valid());
  12775. auto body = read_all(handle);
  12776. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12777. }
  12778. // User-specified User-Agent must not be overwritten for stream API
  12779. {
  12780. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12781. {{"User-Agent", "MyAgent/1.2"}});
  12782. ASSERT_TRUE(handle.is_valid());
  12783. auto body = read_all(handle);
  12784. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12785. }
  12786. }
  12787. TEST_F(OpenStreamTest, Large) {
  12788. Client cli("127.0.0.1", port_);
  12789. auto handle = cli.open_stream("GET", "/large");
  12790. EXPECT_EQ(10000u, read_all(handle).size());
  12791. }
  12792. TEST_F(OpenStreamTest, ConnectionError) {
  12793. Client cli("127.0.0.1", 9999);
  12794. auto handle = cli.open_stream("GET", "/hello");
  12795. EXPECT_FALSE(handle.is_valid());
  12796. }
  12797. TEST_F(OpenStreamTest, Chunked) {
  12798. Client cli("127.0.0.1", port_);
  12799. auto handle = cli.open_stream("GET", "/chunked");
  12800. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12801. "Transfer-Encoding") == "chunked");
  12802. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12803. }
  12804. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12805. Client cli("127.0.0.1", port_);
  12806. auto handle =
  12807. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12808. ASSERT_TRUE(handle.is_valid());
  12809. // Consume body to allow trailers to be received/parsed
  12810. auto body = read_all(handle);
  12811. // Explicitly parse trailers (ensure trailers are available for assertion)
  12812. handle.parse_trailers_if_needed();
  12813. EXPECT_EQ(std::string("123456789"), body);
  12814. // The response should include a Trailer header declaring both names
  12815. ASSERT_TRUE(handle.response);
  12816. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12817. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12818. handle.response->get_header_value("Trailer"));
  12819. // Prohibited trailer must not be present
  12820. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12821. // Allowed trailer should be present
  12822. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12823. EXPECT_EQ(std::string("yes"),
  12824. handle.response->get_trailer_value("X-Allowed"));
  12825. // Verify trailers are NOT present as regular headers
  12826. EXPECT_EQ(std::string(""),
  12827. handle.response->get_header_value("Content-Length"));
  12828. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12829. }
  12830. static std::thread serve_single_response(std::promise<int> &port_promise,
  12831. const std::string &response) {
  12832. return std::thread([&port_promise, response] {
  12833. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12834. default_socket_options(srv);
  12835. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12836. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12837. sockaddr_in addr{};
  12838. addr.sin_family = AF_INET;
  12839. addr.sin_port = htons(0); // Let OS assign a free port
  12840. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12841. int opt = 1;
  12842. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12843. #ifdef _WIN32
  12844. reinterpret_cast<const char *>(&opt),
  12845. #else
  12846. &opt,
  12847. #endif
  12848. sizeof(opt));
  12849. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12850. ::listen(srv, 1) != 0) {
  12851. port_promise.set_value(-1);
  12852. detail::close_socket(srv);
  12853. return;
  12854. }
  12855. socklen_t addr_len = sizeof(addr);
  12856. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12857. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12858. sockaddr_in cli_addr{};
  12859. socklen_t cli_len = sizeof(cli_addr);
  12860. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12861. if (cli != INVALID_SOCKET) {
  12862. // Read the complete HTTP request (until the blank line that terminates
  12863. // headers) before sending the response. If the server closes the socket
  12864. // while the client's request data is still unread in the kernel receive
  12865. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12866. // connection on both sides: it discards the client's receive buffer
  12867. // (which already holds our response) and causes any in-progress write on
  12868. // the client to fail with ECONNRESET. Reading all request data first
  12869. // ensures close() emits a graceful FIN.
  12870. {
  12871. char rbuf[256];
  12872. std::string req;
  12873. while (req.find("\r\n\r\n") == std::string::npos) {
  12874. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12875. if (n <= 0) { break; }
  12876. req.append(rbuf, static_cast<size_t>(n));
  12877. }
  12878. }
  12879. ::send(cli,
  12880. #ifdef _WIN32
  12881. static_cast<const char *>(response.c_str()),
  12882. static_cast<int>(response.size()),
  12883. #else
  12884. response.c_str(), response.size(),
  12885. #endif
  12886. 0);
  12887. detail::close_socket(cli);
  12888. }
  12889. detail::close_socket(srv);
  12890. });
  12891. }
  12892. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12893. #ifndef _WIN32
  12894. signal(SIGPIPE, SIG_IGN);
  12895. #endif
  12896. std::promise<int> port_promise;
  12897. auto port_future = port_promise.get_future();
  12898. auto server_thread =
  12899. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12900. "Content-Type: text/plain\r\n"
  12901. "Content-Length: not-a-number\r\n"
  12902. "Connection: close\r\n"
  12903. "\r\n"
  12904. "hello");
  12905. auto port = port_future.get();
  12906. ASSERT_GT(port, 0);
  12907. Client cli("127.0.0.1", port);
  12908. auto handle = cli.open_stream("GET", "/");
  12909. EXPECT_FALSE(handle.is_valid());
  12910. server_thread.join();
  12911. }
  12912. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12913. #ifndef _WIN32
  12914. signal(SIGPIPE, SIG_IGN);
  12915. #endif
  12916. std::promise<int> port_promise;
  12917. auto port_future = port_promise.get_future();
  12918. auto server_thread = serve_single_response(
  12919. port_promise, "HTTP/1.1 200 OK\r\n"
  12920. "Content-Type: text/plain\r\n"
  12921. "Content-Length: 99999999999999999999999999\r\n"
  12922. "Connection: close\r\n"
  12923. "\r\n"
  12924. "hello");
  12925. auto port = port_future.get();
  12926. ASSERT_GT(port, 0);
  12927. // Before the fix, std::stoull would throw std::out_of_range here and
  12928. // crash the process. After the fix, strtoull silently clamps to
  12929. // ULLONG_MAX so the stream opens without crashing. The important thing
  12930. // is that the process does NOT terminate.
  12931. Client cli("127.0.0.1", port);
  12932. auto handle = cli.open_stream("GET", "/");
  12933. EXPECT_TRUE(handle.is_valid());
  12934. server_thread.join();
  12935. }
  12936. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12937. TEST_F(OpenStreamTest, Gzip) {
  12938. Client cli("127.0.0.1", port_);
  12939. auto handle = cli.open_stream("GET", "/compressible", {},
  12940. {{"Accept-Encoding", "gzip"}});
  12941. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12942. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12943. }
  12944. #endif
  12945. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12946. TEST_F(OpenStreamTest, Brotli) {
  12947. Client cli("127.0.0.1", port_);
  12948. auto handle =
  12949. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12950. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12951. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12952. }
  12953. #endif
  12954. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12955. TEST_F(OpenStreamTest, Zstd) {
  12956. Client cli("127.0.0.1", port_);
  12957. auto handle = cli.open_stream("GET", "/compressible", {},
  12958. {{"Accept-Encoding", "zstd"}});
  12959. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12960. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12961. }
  12962. #endif
  12963. #ifdef CPPHTTPLIB_SSL_ENABLED
  12964. class SSLOpenStreamTest : public ::testing::Test {
  12965. protected:
  12966. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12967. void SetUp() override {
  12968. svr_.Get("/hello", [](const Request &, Response &res) {
  12969. res.set_content("Hello SSL World!", "text/plain");
  12970. });
  12971. svr_.Get("/chunked", [](const Request &, Response &res) {
  12972. res.set_chunked_content_provider("text/plain",
  12973. [](size_t offset, DataSink &sink) {
  12974. if (offset < 15) {
  12975. sink.write("chunk", 5);
  12976. return true;
  12977. }
  12978. sink.done();
  12979. return true;
  12980. });
  12981. });
  12982. svr_.Post("/echo", [](const Request &req, Response &res) {
  12983. res.set_content(req.body, req.get_header_value("Content-Type"));
  12984. });
  12985. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12986. std::string body = req.body;
  12987. res.set_chunked_content_provider(
  12988. "text/plain", [body](size_t offset, DataSink &sink) {
  12989. if (offset < body.size()) {
  12990. sink.write(body.data() + offset, body.size() - offset);
  12991. }
  12992. sink.done();
  12993. return true;
  12994. });
  12995. });
  12996. port_ = svr_.bind_to_any_port("127.0.0.1");
  12997. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12998. svr_.wait_until_ready();
  12999. }
  13000. void TearDown() override {
  13001. svr_.stop();
  13002. if (thread_.joinable()) thread_.join();
  13003. }
  13004. SSLServer svr_;
  13005. std::thread thread_;
  13006. int port_ = 0;
  13007. };
  13008. TEST_F(SSLOpenStreamTest, Basic) {
  13009. SSLClient cli("127.0.0.1", port_);
  13010. cli.enable_server_certificate_verification(false);
  13011. auto handle = cli.open_stream("GET", "/hello");
  13012. ASSERT_TRUE(handle.is_valid());
  13013. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13014. }
  13015. TEST_F(SSLOpenStreamTest, Chunked) {
  13016. SSLClient cli("127.0.0.1", port_);
  13017. cli.enable_server_certificate_verification(false);
  13018. auto handle = cli.open_stream("GET", "/chunked");
  13019. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13020. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13021. "Transfer-Encoding") == "chunked");
  13022. auto body = read_all(handle);
  13023. EXPECT_EQ("chunkchunkchunk", body);
  13024. }
  13025. TEST_F(SSLOpenStreamTest, Post) {
  13026. SSLClient cli("127.0.0.1", port_);
  13027. cli.enable_server_certificate_verification(false);
  13028. auto handle =
  13029. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13030. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13031. EXPECT_EQ(200, handle.response->status);
  13032. auto body = read_all(handle);
  13033. EXPECT_EQ("Hello SSL POST", body);
  13034. }
  13035. TEST_F(SSLOpenStreamTest, PostChunked) {
  13036. SSLClient cli("127.0.0.1", port_);
  13037. cli.enable_server_certificate_verification(false);
  13038. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13039. "Chunked SSL Data", "text/plain");
  13040. ASSERT_TRUE(handle.is_valid());
  13041. EXPECT_EQ(200, handle.response->status);
  13042. auto body = read_all(handle);
  13043. EXPECT_EQ("Chunked SSL Data", body);
  13044. }
  13045. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13046. // Content-Length is terminated by the server closing the connection. When the
  13047. // SSL peer sends a close_notify after the body, the client must treat it as a
  13048. // clean EOF and return a successful response rather than an error.
  13049. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13051. ASSERT_TRUE(svr.is_valid());
  13052. svr.set_keep_alive_max_count(1);
  13053. const std::string expected_body = "Hello from connection-close response!";
  13054. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13055. res.set_content_provider("text/plain",
  13056. [&](size_t offset, DataSink &sink) -> bool {
  13057. if (offset < expected_body.size()) {
  13058. sink.write(expected_body.data() + offset,
  13059. expected_body.size() - offset);
  13060. }
  13061. sink.done();
  13062. return true;
  13063. });
  13064. });
  13065. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13066. auto se = detail::scope_exit([&] {
  13067. svr.stop();
  13068. listen_thread.join();
  13069. ASSERT_FALSE(svr.is_running());
  13070. });
  13071. svr.wait_until_ready();
  13072. SSLClient cli(HOST, PORT);
  13073. cli.enable_server_certificate_verification(false);
  13074. auto res = cli.Get("/no-content-length");
  13075. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13076. EXPECT_EQ(StatusCode::OK_200, res->status);
  13077. EXPECT_EQ(expected_body, res->body);
  13078. }
  13079. #endif // CPPHTTPLIB_SSL_ENABLED
  13080. //==============================================================================
  13081. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13082. // results for various scenarios.
  13083. //==============================================================================
  13084. TEST(ParityTest, GetVsOpenStream) {
  13085. Server svr;
  13086. const std::string path = "/parity";
  13087. const std::string content = "Parity test content: hello world";
  13088. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13089. res.set_content(content, "text/plain");
  13090. });
  13091. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13092. auto se = detail::scope_exit([&] {
  13093. svr.stop();
  13094. t.join();
  13095. ASSERT_FALSE(svr.is_running());
  13096. });
  13097. svr.wait_until_ready();
  13098. Client cli(HOST, PORT);
  13099. // Non-stream path
  13100. auto r1 = cli.Get(path);
  13101. ASSERT_TRUE(r1);
  13102. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13103. // Stream path
  13104. auto h = cli.open_stream("GET", path);
  13105. ASSERT_TRUE(h.is_valid());
  13106. EXPECT_EQ(r1->body, read_all(h));
  13107. }
  13108. // Helper to compress data with provided compressor type T
  13109. template <typename Compressor>
  13110. static std::string compress_payload_for_parity(const std::string &in) {
  13111. std::string out;
  13112. Compressor compressor;
  13113. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13114. [&](const char *data, size_t n) {
  13115. out.append(data, n);
  13116. return true;
  13117. });
  13118. EXPECT_TRUE(ok);
  13119. return out;
  13120. }
  13121. // Helper function for compression parity tests
  13122. template <typename Compressor>
  13123. static void test_compression_parity(const std::string &original,
  13124. const std::string &path,
  13125. const std::string &encoding) {
  13126. const std::string compressed =
  13127. compress_payload_for_parity<Compressor>(original);
  13128. Server svr;
  13129. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13130. res.set_content(compressed, "application/octet-stream");
  13131. res.set_header("Content-Encoding", encoding);
  13132. });
  13133. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13134. auto se = detail::scope_exit([&] {
  13135. svr.stop();
  13136. t.join();
  13137. ASSERT_FALSE(svr.is_running());
  13138. });
  13139. svr.wait_until_ready();
  13140. Client cli(HOST, PORT);
  13141. // Non-streaming
  13142. {
  13143. auto res = cli.Get(path);
  13144. ASSERT_TRUE(res);
  13145. EXPECT_EQ(StatusCode::OK_200, res->status);
  13146. EXPECT_EQ(original, res->body);
  13147. }
  13148. // Streaming
  13149. {
  13150. auto h = cli.open_stream("GET", path);
  13151. ASSERT_TRUE(h.is_valid());
  13152. EXPECT_EQ(original, read_all(h));
  13153. }
  13154. }
  13155. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13156. TEST(ParityTest, Gzip) {
  13157. test_compression_parity<detail::gzip_compressor>(
  13158. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13159. }
  13160. #endif
  13161. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13162. TEST(ParityTest, Brotli) {
  13163. test_compression_parity<detail::brotli_compressor>(
  13164. "Hello, brotli parity test payload", "/parity-br", "br");
  13165. }
  13166. #endif
  13167. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13168. TEST(ParityTest, Zstd) {
  13169. test_compression_parity<detail::zstd_compressor>(
  13170. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13171. }
  13172. #endif
  13173. //==============================================================================
  13174. // New Stream API Tests
  13175. //==============================================================================
  13176. inline std::string read_body(httplib::stream::Result &result) {
  13177. std::string body;
  13178. while (result.next()) {
  13179. body.append(result.data(), result.size());
  13180. }
  13181. return body;
  13182. }
  13183. TEST(ClientConnectionTest, Basic) {
  13184. httplib::ClientConnection conn;
  13185. EXPECT_FALSE(conn.is_open());
  13186. conn.sock = 1;
  13187. EXPECT_TRUE(conn.is_open());
  13188. httplib::ClientConnection conn2(std::move(conn));
  13189. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13190. conn2.sock = INVALID_SOCKET;
  13191. }
  13192. // Unified test server for all stream::* tests
  13193. class StreamApiTest : public ::testing::Test {
  13194. protected:
  13195. void SetUp() override {
  13196. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13197. res.set_content("Hello World!", "text/plain");
  13198. });
  13199. svr_.Get("/echo-params",
  13200. [](const httplib::Request &req, httplib::Response &res) {
  13201. std::string r;
  13202. for (const auto &p : req.params) {
  13203. if (!r.empty()) r += "&";
  13204. r += p.first + "=" + p.second;
  13205. }
  13206. res.set_content(r, "text/plain");
  13207. });
  13208. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13209. res.set_content(req.body, req.get_header_value("Content-Type"));
  13210. });
  13211. svr_.Post("/echo-headers",
  13212. [](const httplib::Request &req, httplib::Response &res) {
  13213. std::string r;
  13214. for (const auto &h : req.headers)
  13215. r += h.first + ": " + h.second + "\n";
  13216. res.set_content(r, "text/plain");
  13217. });
  13218. svr_.Post("/echo-params",
  13219. [](const httplib::Request &req, httplib::Response &res) {
  13220. std::string r = "params:";
  13221. for (const auto &p : req.params)
  13222. r += p.first + "=" + p.second + ";";
  13223. res.set_content(r + " body:" + req.body, "text/plain");
  13224. });
  13225. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13226. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13227. });
  13228. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13229. res.set_content("PUT:" + req.body, "text/plain");
  13230. });
  13231. svr_.Patch("/echo",
  13232. [](const httplib::Request &req, httplib::Response &res) {
  13233. res.set_content("PATCH:" + req.body, "text/plain");
  13234. });
  13235. svr_.Delete(
  13236. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13237. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13238. "text/plain");
  13239. });
  13240. svr_.Get("/head-test",
  13241. [](const httplib::Request &, httplib::Response &res) {
  13242. res.set_content("body for HEAD", "text/plain");
  13243. });
  13244. svr_.Options("/options",
  13245. [](const httplib::Request &, httplib::Response &res) {
  13246. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13247. });
  13248. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13249. svr_.wait_until_ready();
  13250. }
  13251. void TearDown() override {
  13252. svr_.stop();
  13253. if (thread_.joinable()) thread_.join();
  13254. }
  13255. httplib::Server svr_;
  13256. std::thread thread_;
  13257. };
  13258. // stream::Get tests
  13259. TEST_F(StreamApiTest, GetBasic) {
  13260. httplib::Client cli(HOST, PORT);
  13261. auto result = httplib::stream::Get(cli, "/hello");
  13262. ASSERT_TRUE(result.is_valid());
  13263. EXPECT_EQ(200, result.status());
  13264. EXPECT_EQ("Hello World!", read_body(result));
  13265. }
  13266. TEST_F(StreamApiTest, GetWithParams) {
  13267. httplib::Client cli(HOST, PORT);
  13268. httplib::Params params{{"foo", "bar"}};
  13269. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13270. ASSERT_TRUE(result.is_valid());
  13271. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13272. }
  13273. TEST_F(StreamApiTest, GetConnectionError) {
  13274. httplib::Client cli(HOST, 9999);
  13275. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13276. }
  13277. TEST_F(StreamApiTest, Get404) {
  13278. httplib::Client cli(HOST, PORT);
  13279. auto result = httplib::stream::Get(cli, "/nonexistent");
  13280. EXPECT_TRUE(result.is_valid());
  13281. EXPECT_EQ(404, result.status());
  13282. }
  13283. // stream::Post tests
  13284. TEST_F(StreamApiTest, PostBasic) {
  13285. httplib::Client cli(HOST, PORT);
  13286. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13287. "application/json");
  13288. ASSERT_TRUE(result.is_valid());
  13289. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13290. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13291. }
  13292. TEST_F(StreamApiTest, PostWithHeaders) {
  13293. httplib::Client cli(HOST, PORT);
  13294. httplib::Headers headers{{"X-Custom", "value"}};
  13295. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13296. "text/plain");
  13297. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13298. }
  13299. TEST_F(StreamApiTest, PostWithParams) {
  13300. httplib::Client cli(HOST, PORT);
  13301. httplib::Params params{{"k", "v"}};
  13302. auto result =
  13303. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13304. auto body = read_body(result);
  13305. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13306. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13307. }
  13308. TEST_F(StreamApiTest, PostLarge) {
  13309. httplib::Client cli(HOST, PORT);
  13310. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13311. size_t total = 0;
  13312. while (result.next()) {
  13313. total += result.size();
  13314. }
  13315. EXPECT_EQ(100u * 1024u, total);
  13316. }
  13317. // stream::Put/Patch tests
  13318. TEST_F(StreamApiTest, PutAndPatch) {
  13319. httplib::Client cli(HOST, PORT);
  13320. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13321. EXPECT_EQ("PUT:test", read_body(put));
  13322. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13323. EXPECT_EQ("PATCH:test", read_body(patch));
  13324. }
  13325. // stream::Delete tests
  13326. TEST_F(StreamApiTest, Delete) {
  13327. httplib::Client cli(HOST, PORT);
  13328. auto del1 = httplib::stream::Delete(cli, "/resource");
  13329. EXPECT_EQ("Deleted", read_body(del1));
  13330. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13331. EXPECT_EQ("Deleted:data", read_body(del2));
  13332. }
  13333. // stream::Head/Options tests
  13334. TEST_F(StreamApiTest, HeadAndOptions) {
  13335. httplib::Client cli(HOST, PORT);
  13336. auto head = httplib::stream::Head(cli, "/head-test");
  13337. EXPECT_TRUE(head.is_valid());
  13338. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13339. auto opts = httplib::stream::Options(cli, "/options");
  13340. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13341. }
  13342. // SSL stream::* tests
  13343. #ifdef CPPHTTPLIB_SSL_ENABLED
  13344. class SSLStreamApiTest : public ::testing::Test {
  13345. protected:
  13346. void SetUp() override {
  13347. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13348. res.set_content("Hello SSL!", "text/plain");
  13349. });
  13350. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13351. res.set_content(req.body, "text/plain");
  13352. });
  13353. port_ = svr_.bind_to_any_port("127.0.0.1");
  13354. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13355. svr_.wait_until_ready();
  13356. }
  13357. void TearDown() override {
  13358. svr_.stop();
  13359. if (thread_.joinable()) thread_.join();
  13360. }
  13361. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13362. std::thread thread_;
  13363. int port_ = 0;
  13364. };
  13365. TEST_F(SSLStreamApiTest, GetAndPost) {
  13366. httplib::SSLClient cli("127.0.0.1", port_);
  13367. cli.enable_server_certificate_verification(false);
  13368. auto get = httplib::stream::Get(cli, "/hello");
  13369. EXPECT_EQ("Hello SSL!", read_body(get));
  13370. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13371. EXPECT_EQ("test", read_body(post));
  13372. }
  13373. #endif
  13374. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13375. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13376. // BodyReader
  13377. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13378. // Test that read timeout during streaming is detected
  13379. // Use a large content-length response where server delays mid-stream
  13380. Server svr;
  13381. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13382. // Send a large response with delay in the middle
  13383. res.set_content_provider(
  13384. 1000, // content_length
  13385. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13386. if (offset < 100) {
  13387. // Send first 100 bytes immediately
  13388. std::string data(100, 'A');
  13389. sink.write(data.c_str(), data.size());
  13390. return true;
  13391. }
  13392. // Then delay longer than client timeout
  13393. std::this_thread::sleep_for(std::chrono::seconds(3));
  13394. std::string data(900, 'B');
  13395. sink.write(data.c_str(), data.size());
  13396. return true;
  13397. });
  13398. });
  13399. auto port = 8091;
  13400. std::thread t([&]() { svr.listen("localhost", port); });
  13401. svr.wait_until_ready();
  13402. Client cli("localhost", port);
  13403. cli.set_read_timeout(1, 0); // 1 second timeout
  13404. auto handle = cli.open_stream("GET", "/slow-stream");
  13405. ASSERT_TRUE(handle.is_valid());
  13406. char buf[256];
  13407. ssize_t total = 0;
  13408. ssize_t n;
  13409. bool got_error = false;
  13410. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13411. total += n;
  13412. }
  13413. if (n < 0) {
  13414. got_error = true;
  13415. // Should be timeout or read error
  13416. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13417. handle.get_read_error() == Error::Read)
  13418. << "Actual error: " << to_string(handle.get_read_error());
  13419. }
  13420. // Either we got an error, or we got less data than expected
  13421. EXPECT_TRUE(got_error || total < 1000)
  13422. << "Expected timeout but got all " << total << " bytes";
  13423. svr.stop();
  13424. t.join();
  13425. }
  13426. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13427. // Test connection closed detection via BodyReader
  13428. Server svr;
  13429. std::atomic<bool> close_now{false};
  13430. svr.Get("/will-close", [&](const Request &, Response &res) {
  13431. res.set_content_provider(
  13432. 10000, // Large content_length that we won't fully send
  13433. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13434. if (offset < 100) {
  13435. std::string data(100, 'X');
  13436. sink.write(data.c_str(), data.size());
  13437. return true;
  13438. }
  13439. // Wait for signal then abort
  13440. while (!close_now) {
  13441. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13442. }
  13443. return false; // Abort - server will close connection
  13444. });
  13445. });
  13446. auto port = 8092;
  13447. std::thread t([&]() { svr.listen("localhost", port); });
  13448. svr.wait_until_ready();
  13449. Client cli("localhost", port);
  13450. auto handle = cli.open_stream("GET", "/will-close");
  13451. ASSERT_TRUE(handle.is_valid());
  13452. char buf[256];
  13453. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13454. EXPECT_GT(n, 0) << "First read should succeed";
  13455. // Signal server to close
  13456. close_now = true;
  13457. // Keep reading until error or EOF
  13458. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13459. // Keep reading
  13460. }
  13461. // Should get an error since content_length wasn't satisfied
  13462. if (n < 0) {
  13463. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13464. handle.get_read_error() == Error::Read)
  13465. << "Actual error: " << to_string(handle.get_read_error());
  13466. }
  13467. svr.stop();
  13468. t.join();
  13469. }
  13470. #ifdef CPPHTTPLIB_SSL_ENABLED
  13471. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13472. // Test that read timeout during SSL streaming is detected
  13473. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13474. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13475. res.set_content_provider(
  13476. 1000, "text/plain",
  13477. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13478. if (offset < 100) {
  13479. std::string data(100, 'A');
  13480. sink.write(data.c_str(), data.size());
  13481. return true;
  13482. }
  13483. std::this_thread::sleep_for(std::chrono::seconds(3));
  13484. std::string data(900, 'B');
  13485. sink.write(data.c_str(), data.size());
  13486. return true;
  13487. });
  13488. });
  13489. auto port = 8093;
  13490. std::thread t([&]() { svr.listen("localhost", port); });
  13491. svr.wait_until_ready();
  13492. SSLClient cli("localhost", port);
  13493. cli.enable_server_certificate_verification(false);
  13494. cli.set_read_timeout(1, 0); // 1 second timeout
  13495. auto handle = cli.open_stream("GET", "/slow-stream");
  13496. ASSERT_TRUE(handle.is_valid());
  13497. char buf[256];
  13498. ssize_t total = 0;
  13499. ssize_t n;
  13500. bool got_error = false;
  13501. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13502. total += n;
  13503. }
  13504. if (n < 0) {
  13505. got_error = true;
  13506. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13507. handle.get_read_error() == Error::Read)
  13508. << "Actual error: " << to_string(handle.get_read_error());
  13509. }
  13510. EXPECT_TRUE(got_error || total < 1000)
  13511. << "Expected timeout but got all " << total << " bytes";
  13512. svr.stop();
  13513. t.join();
  13514. }
  13515. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13516. // Test SSL connection closed detection
  13517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13518. std::atomic<bool> close_now{false};
  13519. svr.Get("/will-close", [&](const Request &, Response &res) {
  13520. res.set_content_provider(
  13521. 10000, "text/plain",
  13522. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13523. if (offset < 100) {
  13524. std::string data(100, 'X');
  13525. sink.write(data.c_str(), data.size());
  13526. return true;
  13527. }
  13528. while (!close_now) {
  13529. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13530. }
  13531. return false;
  13532. });
  13533. });
  13534. auto port = 8094;
  13535. std::thread t([&]() { svr.listen("localhost", port); });
  13536. svr.wait_until_ready();
  13537. SSLClient cli("localhost", port);
  13538. cli.enable_server_certificate_verification(false);
  13539. auto handle = cli.open_stream("GET", "/will-close");
  13540. ASSERT_TRUE(handle.is_valid());
  13541. char buf[256];
  13542. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13543. EXPECT_GT(n, 0);
  13544. // Signal server to close
  13545. close_now = true;
  13546. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13547. // Keep reading
  13548. }
  13549. if (n < 0) {
  13550. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13551. handle.get_read_error() == Error::Read)
  13552. << "Actual error: " << to_string(handle.get_read_error());
  13553. }
  13554. svr.stop();
  13555. t.join();
  13556. }
  13557. #endif
  13558. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13559. using namespace httplib;
  13560. // Create a test file
  13561. const char *fname = "etag_testfile.txt";
  13562. const char *content = "etag-content";
  13563. {
  13564. std::ofstream ofs(fname);
  13565. ofs << content;
  13566. ASSERT_TRUE(ofs.good());
  13567. }
  13568. Server svr;
  13569. svr.set_mount_point("/static", ".");
  13570. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13571. svr.wait_until_ready();
  13572. Client cli(HOST, PORT);
  13573. // First request: should get 200 with ETag header
  13574. auto res1 = cli.Get("/static/etag_testfile.txt");
  13575. ASSERT_TRUE(res1);
  13576. ASSERT_EQ(200, res1->status);
  13577. ASSERT_TRUE(res1->has_header("ETag"));
  13578. std::string etag = res1->get_header_value("ETag");
  13579. EXPECT_FALSE(etag.empty());
  13580. // Verify ETag format: W/"hex-hex"
  13581. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13582. EXPECT_EQ('W', etag[0]);
  13583. EXPECT_EQ('/', etag[1]);
  13584. EXPECT_EQ('"', etag[2]);
  13585. EXPECT_EQ('"', etag.back());
  13586. // Exact match: expect 304 Not Modified
  13587. Headers h2 = {{"If-None-Match", etag}};
  13588. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13589. ASSERT_TRUE(res2);
  13590. EXPECT_EQ(304, res2->status);
  13591. // Wildcard match: expect 304 Not Modified
  13592. Headers h3 = {{"If-None-Match", "*"}};
  13593. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13594. ASSERT_TRUE(res3);
  13595. EXPECT_EQ(304, res3->status);
  13596. // Non-matching ETag: expect 200
  13597. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13598. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13599. ASSERT_TRUE(res4);
  13600. EXPECT_EQ(200, res4->status);
  13601. // Multiple ETags with one matching: expect 304
  13602. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13603. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13604. ASSERT_TRUE(res5);
  13605. EXPECT_EQ(304, res5->status);
  13606. svr.stop();
  13607. t.join();
  13608. std::remove(fname);
  13609. }
  13610. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13611. using namespace httplib;
  13612. Server svr;
  13613. svr.set_mount_point("/static", ".");
  13614. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13615. svr.wait_until_ready();
  13616. Client cli(HOST, PORT);
  13617. // Send If-None-Match: * to a non-existent file
  13618. Headers h = {{"If-None-Match", "*"}};
  13619. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13620. ASSERT_TRUE(res);
  13621. EXPECT_EQ(404, res->status);
  13622. svr.stop();
  13623. t.join();
  13624. }
  13625. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13626. using namespace httplib;
  13627. // Create a test file
  13628. const char *fname = "etag_boundary_testfile.txt";
  13629. const char *content = "boundary-test";
  13630. {
  13631. std::ofstream ofs(fname);
  13632. ofs << content;
  13633. ASSERT_TRUE(ofs.good());
  13634. }
  13635. Server svr;
  13636. svr.set_mount_point("/static", ".");
  13637. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13638. svr.wait_until_ready();
  13639. Client cli(HOST, PORT);
  13640. // Get the actual ETag
  13641. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13642. ASSERT_TRUE(res1);
  13643. ASSERT_EQ(200, res1->status);
  13644. ASSERT_TRUE(res1->has_header("ETag"));
  13645. std::string etag = res1->get_header_value("ETag");
  13646. // Test 1: Very long ETag value (longer than actual ETag)
  13647. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13648. Headers h1 = {{"If-None-Match", "W/"
  13649. "\"very-long-etag-value-that-is-much-longer-"
  13650. "than-the-actual-etag-value\""}};
  13651. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13652. ASSERT_TRUE(res2);
  13653. EXPECT_EQ(200, res2->status); // Should not match
  13654. // Test 2: Long string followed by wildcard
  13655. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13656. // string)
  13657. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13658. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13659. ASSERT_TRUE(res3);
  13660. EXPECT_EQ(304, res3->status); // Should match on "*"
  13661. // Test 3: Wildcard followed by long string
  13662. // Should match on "*" immediately and return 304
  13663. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13664. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13665. ASSERT_TRUE(res4);
  13666. EXPECT_EQ(304, res4->status); // Should match on "*"
  13667. // Test 4: Multiple long non-matching values
  13668. // Should NOT match and return 200 (test that all comparisons are safe)
  13669. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13670. "W/\"second-long-non-matching-value\", "
  13671. "W/\"third-long-non-matching-value\""}};
  13672. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13673. ASSERT_TRUE(res5);
  13674. EXPECT_EQ(200, res5->status); // Should not match
  13675. // Test 5: Single character that is not "*" (edge case)
  13676. Headers h5 = {{"If-None-Match", "X"}};
  13677. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13678. ASSERT_TRUE(res6);
  13679. EXPECT_EQ(200, res6->status); // Should not match
  13680. svr.stop();
  13681. t.join();
  13682. std::remove(fname);
  13683. }
  13684. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13685. using namespace httplib;
  13686. // Create a test file
  13687. const char *fname = "ims_testfile.txt";
  13688. const char *content = "if-modified-since-test";
  13689. {
  13690. std::ofstream ofs(fname);
  13691. ofs << content;
  13692. ASSERT_TRUE(ofs.good());
  13693. }
  13694. Server svr;
  13695. svr.set_mount_point("/static", ".");
  13696. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13697. svr.wait_until_ready();
  13698. Client cli(HOST, PORT);
  13699. // First request: should get 200 with Last-Modified header
  13700. auto res1 = cli.Get("/static/ims_testfile.txt");
  13701. ASSERT_TRUE(res1);
  13702. ASSERT_EQ(200, res1->status);
  13703. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13704. std::string last_modified = res1->get_header_value("Last-Modified");
  13705. EXPECT_FALSE(last_modified.empty());
  13706. // If-Modified-Since with same time: expect 304
  13707. Headers h2 = {{"If-Modified-Since", last_modified}};
  13708. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13709. ASSERT_TRUE(res2);
  13710. EXPECT_EQ(304, res2->status);
  13711. // If-Modified-Since with future time: expect 304
  13712. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13713. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13714. ASSERT_TRUE(res3);
  13715. EXPECT_EQ(304, res3->status);
  13716. // If-Modified-Since with past time: expect 200
  13717. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13718. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13719. ASSERT_TRUE(res4);
  13720. EXPECT_EQ(200, res4->status);
  13721. // If-None-Match takes precedence over If-Modified-Since
  13722. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13723. ASSERT_TRUE(res1->has_header("ETag"));
  13724. std::string etag = res1->get_header_value("ETag");
  13725. Headers h5 = {{"If-None-Match", etag},
  13726. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13727. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13728. ASSERT_TRUE(res5);
  13729. EXPECT_EQ(304, res5->status);
  13730. svr.stop();
  13731. t.join();
  13732. std::remove(fname);
  13733. }
  13734. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13735. using namespace httplib;
  13736. Server svr;
  13737. // Endpoint that returns compressible content
  13738. svr.Get("/compressible", [](const Request &, Response &res) {
  13739. // Return a large enough body to trigger compression
  13740. std::string body(1000, 'a');
  13741. res.set_content(body, "text/plain");
  13742. });
  13743. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13744. svr.wait_until_ready();
  13745. Client cli(HOST, PORT);
  13746. // Request with gzip support: should get Vary header when compressed
  13747. cli.set_compress(true);
  13748. auto res1 = cli.Get("/compressible");
  13749. ASSERT_TRUE(res1);
  13750. EXPECT_EQ(200, res1->status);
  13751. // If Content-Encoding is set, Vary should also be set
  13752. if (res1->has_header("Content-Encoding")) {
  13753. EXPECT_TRUE(res1->has_header("Vary"));
  13754. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13755. }
  13756. // Request without Accept-Encoding header: should not have compression
  13757. Headers h_no_compress;
  13758. auto res2 = cli.Get("/compressible", h_no_compress);
  13759. ASSERT_TRUE(res2);
  13760. EXPECT_EQ(200, res2->status);
  13761. // Verify Vary header is present when compression is applied
  13762. // (the exact behavior depends on server configuration)
  13763. svr.stop();
  13764. t.join();
  13765. }
  13766. TEST(ETagTest, IfRangeWithETag) {
  13767. using namespace httplib;
  13768. // Create a test file with known content
  13769. const char *fname = "if_range_testfile.txt";
  13770. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13771. {
  13772. std::ofstream ofs(fname);
  13773. ofs << content;
  13774. ASSERT_TRUE(ofs.good());
  13775. }
  13776. Server svr;
  13777. svr.set_mount_point("/static", ".");
  13778. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13779. svr.wait_until_ready();
  13780. Client cli(HOST, PORT);
  13781. // First request: get ETag
  13782. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13783. ASSERT_TRUE(res1);
  13784. ASSERT_EQ(200, res1->status);
  13785. ASSERT_TRUE(res1->has_header("ETag"));
  13786. std::string etag = res1->get_header_value("ETag");
  13787. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13788. // Since our server generates weak ETags (W/"..."), If-Range with our
  13789. // ETag should NOT result in partial content - it should return full content.
  13790. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13791. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13792. ASSERT_TRUE(res2);
  13793. // Weak ETag in If-Range -> full content (200), not partial (206)
  13794. EXPECT_EQ(200, res2->status);
  13795. EXPECT_EQ(content, res2->body);
  13796. EXPECT_FALSE(res2->has_header("Content-Range"));
  13797. // Range request with non-matching If-Range (ETag): should get 200 (full
  13798. // content)
  13799. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13800. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13801. ASSERT_TRUE(res3);
  13802. EXPECT_EQ(200, res3->status);
  13803. EXPECT_EQ(content, res3->body);
  13804. EXPECT_FALSE(res3->has_header("Content-Range"));
  13805. // Range request with strong ETag (hypothetical - our server doesn't generate
  13806. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13807. // should return full content)
  13808. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13809. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13810. ASSERT_TRUE(res4);
  13811. EXPECT_EQ(200, res4->status);
  13812. EXPECT_EQ(content, res4->body);
  13813. EXPECT_FALSE(res4->has_header("Content-Range"));
  13814. svr.stop();
  13815. t.join();
  13816. std::remove(fname);
  13817. }
  13818. TEST(ETagTest, IfRangeWithDate) {
  13819. using namespace httplib;
  13820. // Create a test file
  13821. const char *fname = "if_range_date_testfile.txt";
  13822. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13823. {
  13824. std::ofstream ofs(fname);
  13825. ofs << content;
  13826. ASSERT_TRUE(ofs.good());
  13827. }
  13828. Server svr;
  13829. svr.set_mount_point("/static", ".");
  13830. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13831. svr.wait_until_ready();
  13832. Client cli(HOST, PORT);
  13833. // First request: get Last-Modified
  13834. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13835. ASSERT_TRUE(res1);
  13836. ASSERT_EQ(200, res1->status);
  13837. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13838. std::string last_modified = res1->get_header_value("Last-Modified");
  13839. // Range request with matching If-Range (date): should get 206
  13840. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13841. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13842. ASSERT_TRUE(res2);
  13843. EXPECT_EQ(206, res2->status);
  13844. EXPECT_EQ("FGHIJ", res2->body);
  13845. // Range request with old If-Range date: should get 200 (full content)
  13846. Headers h3 = {{"Range", "bytes=5-9"},
  13847. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13848. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13849. ASSERT_TRUE(res3);
  13850. EXPECT_EQ(200, res3->status);
  13851. EXPECT_EQ(content, res3->body);
  13852. // Range request with future If-Range date: should get 206
  13853. Headers h4 = {{"Range", "bytes=0-4"},
  13854. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13855. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13856. ASSERT_TRUE(res4);
  13857. EXPECT_EQ(206, res4->status);
  13858. EXPECT_EQ("ABCDE", res4->body);
  13859. svr.stop();
  13860. t.join();
  13861. std::remove(fname);
  13862. }
  13863. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13864. using namespace httplib;
  13865. const char *fname = "etag_malformed.txt";
  13866. const char *content = "malformed-etag";
  13867. {
  13868. std::ofstream ofs(fname);
  13869. ofs << content;
  13870. ASSERT_TRUE(ofs.good());
  13871. }
  13872. Server svr;
  13873. svr.set_mount_point("/static", ".");
  13874. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13875. svr.wait_until_ready();
  13876. Client cli(HOST, PORT);
  13877. // baseline: should get 200 and an ETag
  13878. auto res1 = cli.Get("/static/etag_malformed.txt");
  13879. ASSERT_TRUE(res1);
  13880. ASSERT_EQ(200, res1->status);
  13881. ASSERT_TRUE(res1->has_header("ETag"));
  13882. // Malformed ETag value (missing quotes) should be treated as non-matching
  13883. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13884. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13885. ASSERT_TRUE(res_bad);
  13886. EXPECT_EQ(200, res_bad->status);
  13887. // Whitespace-only header value should be considered invalid / non-matching
  13888. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13889. "Host: localhost\r\n"
  13890. "If-None-Match: \r\n"
  13891. "Connection: close\r\n"
  13892. "\r\n";
  13893. std::string out;
  13894. ASSERT_TRUE(send_request(5, raw_req, &out));
  13895. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13896. svr.stop();
  13897. t.join();
  13898. std::remove(fname);
  13899. }
  13900. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13901. using namespace httplib;
  13902. const char *fname = "ims_invalid_format.txt";
  13903. const char *content = "ims-bad-format";
  13904. {
  13905. std::ofstream ofs(fname);
  13906. ofs << content;
  13907. ASSERT_TRUE(ofs.good());
  13908. }
  13909. Server svr;
  13910. svr.set_mount_point("/static", ".");
  13911. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13912. svr.wait_until_ready();
  13913. Client cli(HOST, PORT);
  13914. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13915. ASSERT_TRUE(res1);
  13916. ASSERT_EQ(200, res1->status);
  13917. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13918. // If-Modified-Since with invalid format should not result in 304
  13919. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13920. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13921. ASSERT_TRUE(res_bad);
  13922. EXPECT_EQ(200, res_bad->status);
  13923. // If-Range with invalid date format should be treated as mismatch -> full
  13924. // content (200)
  13925. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13926. {"If-Range", "invalid-date"}};
  13927. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13928. ASSERT_TRUE(res_ifrange);
  13929. EXPECT_EQ(200, res_ifrange->status);
  13930. svr.stop();
  13931. t.join();
  13932. std::remove(fname);
  13933. }
  13934. TEST(ETagTest, IfRangeWithMalformedETag) {
  13935. using namespace httplib;
  13936. const char *fname = "ifrange_malformed.txt";
  13937. const std::string content = "0123456789";
  13938. {
  13939. std::ofstream ofs(fname);
  13940. ofs << content;
  13941. ASSERT_TRUE(ofs.good());
  13942. }
  13943. Server svr;
  13944. svr.set_mount_point("/static", ".");
  13945. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13946. svr.wait_until_ready();
  13947. Client cli(HOST, PORT);
  13948. // First request: get ETag
  13949. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13950. ASSERT_TRUE(res1);
  13951. ASSERT_EQ(200, res1->status);
  13952. ASSERT_TRUE(res1->has_header("ETag"));
  13953. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13954. // full content (200)
  13955. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13956. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13957. ASSERT_TRUE(res2);
  13958. EXPECT_EQ(200, res2->status);
  13959. EXPECT_EQ(content, res2->body);
  13960. svr.stop();
  13961. t.join();
  13962. std::remove(fname);
  13963. }
  13964. TEST(ETagTest, ExtremeLargeDateValues) {
  13965. using namespace httplib;
  13966. const char *fname = "ims_extreme_date.txt";
  13967. const char *content = "ims-extreme-date";
  13968. {
  13969. std::ofstream ofs(fname);
  13970. ofs << content;
  13971. ASSERT_TRUE(ofs.good());
  13972. }
  13973. Server svr;
  13974. svr.set_mount_point("/static", ".");
  13975. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13976. svr.wait_until_ready();
  13977. Client cli(HOST, PORT);
  13978. auto res1 = cli.Get(std::string("/static/") + fname);
  13979. ASSERT_TRUE(res1);
  13980. ASSERT_EQ(200, res1->status);
  13981. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13982. // Extremely large year that may overflow date parsing routines.
  13983. Headers h_large_date = {
  13984. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13985. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13986. ASSERT_TRUE(res_bad);
  13987. // Expect server to treat this as invalid/mismatch and return full content
  13988. EXPECT_EQ(200, res_bad->status);
  13989. // If-Range with extremely large date should be treated as mismatch -> full
  13990. // content (200)
  13991. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13992. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13993. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13994. ASSERT_TRUE(res_ifrange);
  13995. EXPECT_EQ(200, res_ifrange->status);
  13996. svr.stop();
  13997. t.join();
  13998. std::remove(fname);
  13999. }
  14000. TEST(ETagTest, NegativeFileModificationTime) {
  14001. using namespace httplib;
  14002. const char *fname = "ims_negative_mtime.txt";
  14003. const std::string content = "negative-mtime";
  14004. {
  14005. std::ofstream ofs(fname);
  14006. ofs << content;
  14007. ASSERT_TRUE(ofs.good());
  14008. }
  14009. // Try to set file mtime to a negative value. This may fail on some
  14010. // platforms/filesystems; if it fails, the test will still verify server
  14011. // behaves safely by performing a regular conditional request.
  14012. #if defined(__APPLE__) || defined(__linux__)
  14013. bool set_negative = false;
  14014. do {
  14015. struct timeval times[2];
  14016. // access time: now
  14017. times[0].tv_sec = time(nullptr);
  14018. times[0].tv_usec = 0;
  14019. // modification time: negative (e.g., -1)
  14020. times[1].tv_sec = -1;
  14021. times[1].tv_usec = 0;
  14022. if (utimes(fname, times) == 0) { set_negative = true; }
  14023. } while (0);
  14024. #else
  14025. bool set_negative = false;
  14026. #endif
  14027. Server svr;
  14028. svr.set_mount_point("/static", ".");
  14029. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14030. svr.wait_until_ready();
  14031. Client cli(HOST, PORT);
  14032. auto res1 = cli.Get(std::string("/static/") + fname);
  14033. ASSERT_TRUE(res1);
  14034. ASSERT_EQ(200, res1->status);
  14035. bool has_last_modified = res1->has_header("Last-Modified");
  14036. std::string last_modified;
  14037. if (has_last_modified) {
  14038. last_modified = res1->get_header_value("Last-Modified");
  14039. }
  14040. if (set_negative) {
  14041. // If we successfully set a negative mtime, ensure server returns a
  14042. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14043. // with an old date and ensure server handles it without crash.
  14044. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14045. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14046. ASSERT_TRUE(res2);
  14047. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14048. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14049. } else {
  14050. // Could not set negative mtime on this platform; fall back to verifying
  14051. // that normal invalid/malformed dates are treated safely (non-304).
  14052. Headers h_bad_date = {
  14053. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14054. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14055. ASSERT_TRUE(res_bad);
  14056. EXPECT_EQ(200, res_bad->status);
  14057. }
  14058. svr.stop();
  14059. t.join();
  14060. std::remove(fname);
  14061. }
  14062. //==============================================================================
  14063. // SSE Parsing Tests
  14064. //==============================================================================
  14065. class SSEParsingTest : public ::testing::Test {
  14066. protected:
  14067. // Test helper that mimics SSE parsing behavior
  14068. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14069. int &retry_ms) {
  14070. // Blank line signals end of event
  14071. if (line.empty() || line == "\r") { return true; }
  14072. // Lines starting with ':' are comments (ignored)
  14073. if (!line.empty() && line[0] == ':') { return false; }
  14074. // Find the colon separator
  14075. auto colon_pos = line.find(':');
  14076. if (colon_pos == std::string::npos) {
  14077. // Line with no colon is treated as field name with empty value
  14078. return false;
  14079. }
  14080. std::string field = line.substr(0, colon_pos);
  14081. std::string value;
  14082. // Value starts after colon, skip optional single space
  14083. if (colon_pos + 1 < line.size()) {
  14084. size_t value_start = colon_pos + 1;
  14085. if (line[value_start] == ' ') { value_start++; }
  14086. value = line.substr(value_start);
  14087. // Remove trailing \r if present
  14088. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14089. }
  14090. // Handle known fields
  14091. if (field == "event") {
  14092. msg.event = value;
  14093. } else if (field == "data") {
  14094. // Multiple data lines are concatenated with newlines
  14095. if (!msg.data.empty()) { msg.data += "\n"; }
  14096. msg.data += value;
  14097. } else if (field == "id") {
  14098. // Empty id is valid (clears the last event ID)
  14099. msg.id = value;
  14100. } else if (field == "retry") {
  14101. // Parse retry interval in milliseconds
  14102. {
  14103. int v = 0;
  14104. auto res =
  14105. detail::from_chars(value.data(), value.data() + value.size(), v);
  14106. if (res.ec == std::errc{}) { retry_ms = v; }
  14107. }
  14108. }
  14109. // Unknown fields are ignored per SSE spec
  14110. return false;
  14111. }
  14112. };
  14113. // Test: Single-line data
  14114. TEST_F(SSEParsingTest, SingleLineData) {
  14115. sse::SSEMessage msg;
  14116. int retry_ms = 3000;
  14117. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14118. EXPECT_EQ(msg.data, "hello");
  14119. EXPECT_EQ(msg.event, "message");
  14120. // Blank line ends event
  14121. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14122. }
  14123. // Test: Multi-line data
  14124. TEST_F(SSEParsingTest, MultiLineData) {
  14125. sse::SSEMessage msg;
  14126. int retry_ms = 3000;
  14127. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14128. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14129. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14130. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14131. }
  14132. // Test: Custom event types
  14133. TEST_F(SSEParsingTest, CustomEventType) {
  14134. sse::SSEMessage msg;
  14135. int retry_ms = 3000;
  14136. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14137. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14138. EXPECT_EQ(msg.event, "update");
  14139. EXPECT_EQ(msg.data, "payload");
  14140. }
  14141. // Test: Event ID handling
  14142. TEST_F(SSEParsingTest, EventIdHandling) {
  14143. sse::SSEMessage msg;
  14144. int retry_ms = 3000;
  14145. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14146. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14147. EXPECT_EQ(msg.id, "12345");
  14148. }
  14149. // Test: Empty event ID (clears last event ID)
  14150. TEST_F(SSEParsingTest, EmptyEventId) {
  14151. sse::SSEMessage msg;
  14152. msg.id = "previous";
  14153. int retry_ms = 3000;
  14154. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14155. EXPECT_EQ(msg.id, "");
  14156. }
  14157. // Test: Retry field parsing
  14158. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14159. sse::SSEMessage msg;
  14160. int retry_ms = 3000;
  14161. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14162. EXPECT_EQ(retry_ms, 5000);
  14163. }
  14164. // Test: Invalid retry value
  14165. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14166. sse::SSEMessage msg;
  14167. int retry_ms = 3000;
  14168. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14169. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14170. }
  14171. // Test: Comments (lines starting with :)
  14172. TEST_F(SSEParsingTest, CommentsIgnored) {
  14173. sse::SSEMessage msg;
  14174. int retry_ms = 3000;
  14175. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14176. EXPECT_EQ(msg.data, "");
  14177. EXPECT_EQ(msg.event, "message");
  14178. }
  14179. // Test: Colon in value
  14180. TEST_F(SSEParsingTest, ColonInValue) {
  14181. sse::SSEMessage msg;
  14182. int retry_ms = 3000;
  14183. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14184. EXPECT_EQ(msg.data, "hello:world:test");
  14185. }
  14186. // Test: Line with no colon (field name only)
  14187. TEST_F(SSEParsingTest, FieldNameOnly) {
  14188. sse::SSEMessage msg;
  14189. int retry_ms = 3000;
  14190. // According to SSE spec, this is treated as field name with empty value
  14191. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14192. // Since we don't recognize "data" without colon, data should be empty
  14193. EXPECT_EQ(msg.data, "");
  14194. }
  14195. // Test: Trailing \r handling
  14196. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14197. sse::SSEMessage msg;
  14198. int retry_ms = 3000;
  14199. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14200. EXPECT_EQ(msg.data, "hello");
  14201. }
  14202. // Test: Unknown fields ignored
  14203. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14204. sse::SSEMessage msg;
  14205. int retry_ms = 3000;
  14206. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14207. EXPECT_EQ(msg.data, "");
  14208. EXPECT_EQ(msg.event, "message");
  14209. }
  14210. // Test: Space after colon is optional
  14211. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14212. sse::SSEMessage msg1, msg2;
  14213. int retry_ms = 3000;
  14214. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14215. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14216. EXPECT_EQ(msg1.data, "hello");
  14217. EXPECT_EQ(msg2.data, "hello");
  14218. }
  14219. // Test: SSEMessage clear
  14220. TEST_F(SSEParsingTest, MessageClear) {
  14221. sse::SSEMessage msg;
  14222. msg.event = "custom";
  14223. msg.data = "some data";
  14224. msg.id = "123";
  14225. msg.clear();
  14226. EXPECT_EQ(msg.event, "message");
  14227. EXPECT_EQ(msg.data, "");
  14228. EXPECT_EQ(msg.id, "");
  14229. }
  14230. // Test: Complete event parsing
  14231. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14232. sse::SSEMessage msg;
  14233. int retry_ms = 3000;
  14234. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14235. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14236. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14237. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14238. // Blank line ends event
  14239. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14240. EXPECT_EQ(msg.event, "notification");
  14241. EXPECT_EQ(msg.id, "evt-42");
  14242. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14243. EXPECT_EQ(retry_ms, 1000);
  14244. }
  14245. //==============================================================================
  14246. // Integration Tests with Server
  14247. //==============================================================================
  14248. class SSEIntegrationTest : public ::testing::Test {
  14249. protected:
  14250. void SetUp() override {
  14251. stop_server_.store(false);
  14252. events_.clear();
  14253. server_ = httplib::detail::make_unique<Server>();
  14254. setup_server();
  14255. start_server();
  14256. }
  14257. void TearDown() override {
  14258. stop_server_.store(true);
  14259. event_cv_.notify_all();
  14260. server_->stop();
  14261. if (server_thread_.joinable()) { server_thread_.join(); }
  14262. }
  14263. void setup_server() {
  14264. // Simple SSE endpoint
  14265. server_->Get("/events", [this](const Request &req, Response &res) {
  14266. auto last_id = req.get_header_value("Last-Event-ID");
  14267. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14268. res.set_chunked_content_provider(
  14269. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14270. std::unique_lock<std::mutex> lock(event_mutex_);
  14271. if (event_cv_.wait_for(
  14272. lock, std::chrono::milliseconds(200), [this] {
  14273. return !events_.empty() || stop_server_.load();
  14274. })) {
  14275. if (stop_server_.load()) { return false; }
  14276. if (!events_.empty()) {
  14277. std::string event = events_.front();
  14278. events_.erase(events_.begin());
  14279. sink.write(event.data(), event.size());
  14280. return true;
  14281. }
  14282. }
  14283. return !stop_server_.load();
  14284. });
  14285. });
  14286. // Endpoint that returns error
  14287. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14288. res.status = 500;
  14289. res.set_content("Internal Server Error", "text/plain");
  14290. });
  14291. // Endpoint for custom event types
  14292. server_->Get("/custom-events", [](const Request &, Response &res) {
  14293. res.set_chunked_content_provider(
  14294. "text/event-stream", [](size_t offset, DataSink &sink) {
  14295. if (offset == 0) {
  14296. std::string event = "event: update\ndata: updated\n\n"
  14297. "event: delete\ndata: deleted\n\n";
  14298. sink.write(event.data(), event.size());
  14299. }
  14300. return false; // End stream after sending
  14301. });
  14302. });
  14303. }
  14304. void start_server() {
  14305. port_ = server_->bind_to_any_port(HOST);
  14306. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14307. // Wait for server to start
  14308. while (!server_->is_running()) {
  14309. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14310. }
  14311. }
  14312. int get_port() const { return port_; }
  14313. void send_event(const std::string &event) {
  14314. std::lock_guard<std::mutex> lock(event_mutex_);
  14315. events_.push_back(event);
  14316. event_cv_.notify_all();
  14317. }
  14318. std::unique_ptr<Server> server_;
  14319. std::thread server_thread_;
  14320. std::mutex event_mutex_;
  14321. std::condition_variable event_cv_;
  14322. std::vector<std::string> events_;
  14323. std::atomic<bool> stop_server_{false};
  14324. std::string last_received_event_id_;
  14325. int port_ = 0;
  14326. };
  14327. // Test: Successful connection and on_open callback
  14328. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14329. // Add a simple endpoint that sends one event and closes
  14330. server_->Get("/simple-event", [](const Request &, Response &res) {
  14331. res.set_chunked_content_provider(
  14332. "text/event-stream", [](size_t offset, DataSink &sink) {
  14333. if (offset == 0) {
  14334. std::string event = "data: hello\n\n";
  14335. sink.write(event.data(), event.size());
  14336. }
  14337. return false; // Close stream after sending
  14338. });
  14339. });
  14340. Client client("localhost", get_port());
  14341. sse::SSEClient sse(client, "/simple-event");
  14342. std::atomic<bool> open_called{false};
  14343. std::atomic<bool> message_received{false};
  14344. sse.on_open([&open_called]() { open_called.store(true); });
  14345. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14346. if (msg.data == "hello") { message_received.store(true); }
  14347. });
  14348. sse.set_reconnect_interval(100);
  14349. sse.set_max_reconnect_attempts(1);
  14350. // Start async
  14351. sse.start_async();
  14352. // Wait for message to be processed
  14353. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14354. sse.stop();
  14355. EXPECT_TRUE(open_called.load());
  14356. EXPECT_TRUE(message_received.load());
  14357. }
  14358. // Test: on_message callback
  14359. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14360. // Endpoint that sends multiple events then closes
  14361. server_->Get("/multi-event", [](const Request &, Response &res) {
  14362. res.set_chunked_content_provider(
  14363. "text/event-stream", [](size_t offset, DataSink &sink) {
  14364. if (offset == 0) {
  14365. std::string events = "data: message1\n\ndata: message2\n\n";
  14366. sink.write(events.data(), events.size());
  14367. }
  14368. return false;
  14369. });
  14370. });
  14371. Client client("localhost", get_port());
  14372. sse::SSEClient sse(client, "/multi-event");
  14373. std::vector<std::string> received_messages;
  14374. std::mutex messages_mutex;
  14375. sse.on_message([&](const sse::SSEMessage &msg) {
  14376. std::lock_guard<std::mutex> lock(messages_mutex);
  14377. received_messages.push_back(msg.data);
  14378. });
  14379. sse.set_reconnect_interval(100);
  14380. sse.set_max_reconnect_attempts(1);
  14381. sse.start_async();
  14382. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14383. sse.stop();
  14384. std::lock_guard<std::mutex> lock(messages_mutex);
  14385. EXPECT_GE(received_messages.size(), 2u);
  14386. if (received_messages.size() >= 2) {
  14387. EXPECT_EQ(received_messages[0], "message1");
  14388. EXPECT_EQ(received_messages[1], "message2");
  14389. }
  14390. }
  14391. // Test: on_event for specific types
  14392. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14393. Client client("localhost", get_port());
  14394. sse::SSEClient sse(client, "/custom-events");
  14395. std::atomic<bool> update_received{false};
  14396. std::atomic<bool> delete_received{false};
  14397. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14398. if (msg.data == "updated") { update_received.store(true); }
  14399. });
  14400. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14401. if (msg.data == "deleted") { delete_received.store(true); }
  14402. });
  14403. sse.set_max_reconnect_attempts(1);
  14404. sse.start_async();
  14405. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14406. sse.stop();
  14407. EXPECT_TRUE(update_received.load());
  14408. EXPECT_TRUE(delete_received.load());
  14409. }
  14410. // Test: on_error callback on connection failure
  14411. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14412. // Connect to a non-existent port
  14413. Client client("localhost", 59999);
  14414. sse::SSEClient sse(client, "/events");
  14415. std::atomic<bool> error_called{false};
  14416. Error received_error = Error::Success;
  14417. sse.on_error([&](Error err) {
  14418. error_called.store(true);
  14419. received_error = err;
  14420. });
  14421. sse.set_reconnect_interval(50);
  14422. sse.set_max_reconnect_attempts(1);
  14423. sse.start_async();
  14424. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14425. sse.stop();
  14426. EXPECT_TRUE(error_called.load());
  14427. EXPECT_NE(received_error, Error::Success);
  14428. }
  14429. // Test: Last-Event-ID header sent on reconnect
  14430. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14431. // Endpoint that sends event with ID
  14432. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14433. res.set_chunked_content_provider(
  14434. "text/event-stream", [](size_t offset, DataSink &sink) {
  14435. if (offset == 0) {
  14436. std::string event = "id: evt-123\ndata: test\n\n";
  14437. sink.write(event.data(), event.size());
  14438. }
  14439. return false;
  14440. });
  14441. });
  14442. Client client("localhost", get_port());
  14443. sse::SSEClient sse(client, "/event-with-id");
  14444. std::atomic<bool> id_received{false};
  14445. sse.on_message([&](const sse::SSEMessage &msg) {
  14446. if (!msg.id.empty()) { id_received.store(true); }
  14447. });
  14448. sse.set_reconnect_interval(100);
  14449. sse.set_max_reconnect_attempts(1);
  14450. sse.start_async();
  14451. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14452. sse.stop();
  14453. EXPECT_TRUE(id_received.load());
  14454. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14455. }
  14456. // Test: Manual stop
  14457. TEST_F(SSEIntegrationTest, ManualStop) {
  14458. // Endpoint that sends one event and stays open briefly
  14459. std::atomic<bool> handler_running{true};
  14460. server_->Get("/stay-open", [&handler_running](const Request &,
  14461. Response &res) {
  14462. res.set_chunked_content_provider(
  14463. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14464. if (offset == 0) {
  14465. std::string event = "data: connected\n\n";
  14466. sink.write(event.data(), event.size());
  14467. }
  14468. // Keep connection open while handler_running is true
  14469. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14470. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14471. }
  14472. return false;
  14473. });
  14474. });
  14475. Client client("localhost", get_port());
  14476. sse::SSEClient sse(client, "/stay-open");
  14477. std::atomic<bool> connected{false};
  14478. sse.on_open([&connected]() { connected.store(true); });
  14479. sse.set_reconnect_interval(100);
  14480. sse.set_max_reconnect_attempts(1);
  14481. sse.start_async();
  14482. // Wait for connection to establish
  14483. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14484. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14485. }
  14486. EXPECT_TRUE(connected.load());
  14487. EXPECT_TRUE(sse.is_connected());
  14488. // Signal handler to stop
  14489. handler_running.store(false);
  14490. // Stop SSE client
  14491. sse.stop();
  14492. EXPECT_FALSE(sse.is_connected());
  14493. }
  14494. // Test: SSEClient with custom headers
  14495. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14496. // Setup a server endpoint that checks for custom header
  14497. std::atomic<bool> header_received{false};
  14498. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14499. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14500. header_received.store(true);
  14501. }
  14502. res.set_chunked_content_provider("text/event-stream",
  14503. [](size_t, DataSink &) { return false; });
  14504. });
  14505. Client client("localhost", get_port());
  14506. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14507. sse::SSEClient sse(client, "/header-check", headers);
  14508. sse.set_max_reconnect_attempts(1);
  14509. sse.start_async();
  14510. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14511. sse.stop();
  14512. EXPECT_TRUE(header_received.load());
  14513. }
  14514. // Test: Reconnect interval configuration
  14515. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14516. Client client("localhost", get_port());
  14517. sse::SSEClient sse(client, "/events");
  14518. auto &result = sse.set_reconnect_interval(500);
  14519. // Builder pattern should return reference to self
  14520. EXPECT_EQ(&result, &sse);
  14521. }
  14522. // Test: Max reconnect attempts
  14523. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14524. // Connect to non-existent port to force reconnects
  14525. Client client("localhost", 59998);
  14526. sse::SSEClient sse(client, "/events");
  14527. std::atomic<int> error_count{0};
  14528. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14529. sse.set_reconnect_interval(50);
  14530. sse.set_max_reconnect_attempts(2);
  14531. auto start = std::chrono::steady_clock::now();
  14532. sse.start(); // Blocking call
  14533. auto end = std::chrono::steady_clock::now();
  14534. // Should have stopped after 2 failed attempts
  14535. EXPECT_GE(error_count.load(), 2);
  14536. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14537. auto duration =
  14538. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14539. #ifdef _WIN32
  14540. // Windows is much slower for socket connection failures
  14541. EXPECT_LT(duration.count(), 7000);
  14542. #else
  14543. EXPECT_LT(duration.count(), 1000);
  14544. #endif
  14545. }
  14546. // Test: Multi-line data in integration
  14547. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14548. // Endpoint with multi-line data
  14549. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14550. res.set_chunked_content_provider(
  14551. "text/event-stream", [](size_t offset, DataSink &sink) {
  14552. if (offset == 0) {
  14553. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14554. sink.write(event.data(), event.size());
  14555. }
  14556. return false;
  14557. });
  14558. });
  14559. Client client("localhost", get_port());
  14560. sse::SSEClient sse(client, "/multiline-data");
  14561. std::string received_data;
  14562. std::mutex data_mutex;
  14563. sse.on_message([&](const sse::SSEMessage &msg) {
  14564. std::lock_guard<std::mutex> lock(data_mutex);
  14565. received_data = msg.data;
  14566. });
  14567. sse.set_reconnect_interval(100);
  14568. sse.set_max_reconnect_attempts(1);
  14569. sse.start_async();
  14570. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14571. sse.stop();
  14572. std::lock_guard<std::mutex> lock(data_mutex);
  14573. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14574. }
  14575. // Test: Auto-reconnect after server disconnection
  14576. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14577. std::atomic<int> connection_count{0};
  14578. std::atomic<int> message_count{0};
  14579. // Endpoint that sends one event and closes, forcing reconnect
  14580. server_->Get("/reconnect-test",
  14581. [&connection_count](const Request &, Response &res) {
  14582. connection_count.fetch_add(1);
  14583. res.set_chunked_content_provider(
  14584. "text/event-stream", [](size_t offset, DataSink &sink) {
  14585. if (offset == 0) {
  14586. std::string event = "data: hello\n\n";
  14587. sink.write(event.data(), event.size());
  14588. }
  14589. return false; // Close connection after sending
  14590. });
  14591. });
  14592. Client client("localhost", get_port());
  14593. sse::SSEClient sse(client, "/reconnect-test");
  14594. sse.on_message([&message_count](const sse::SSEMessage &) {
  14595. message_count.fetch_add(1);
  14596. });
  14597. sse.set_reconnect_interval(100);
  14598. sse.set_max_reconnect_attempts(3);
  14599. sse.start_async();
  14600. // Wait long enough for multiple reconnects
  14601. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14602. sse.stop();
  14603. // Should have connected multiple times (initial + reconnects)
  14604. EXPECT_GE(connection_count.load(), 2);
  14605. // Should have received messages from multiple connections
  14606. EXPECT_GE(message_count.load(), 2);
  14607. }
  14608. // Test: Last-Event-ID sent on reconnect
  14609. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14610. std::atomic<int> connection_count{0};
  14611. std::vector<std::string> received_last_event_ids;
  14612. std::mutex id_mutex;
  14613. // Endpoint that checks Last-Event-ID header and sends event with ID
  14614. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14615. int conn = connection_count.fetch_add(1);
  14616. // Capture the Last-Event-ID header from each connection
  14617. {
  14618. std::lock_guard<std::mutex> lock(id_mutex);
  14619. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14620. }
  14621. res.set_chunked_content_provider(
  14622. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14623. if (offset == 0) {
  14624. std::string event =
  14625. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14626. sink.write(event.data(), event.size());
  14627. }
  14628. return false;
  14629. });
  14630. });
  14631. Client client("localhost", get_port());
  14632. sse::SSEClient sse(client, "/reconnect-with-id");
  14633. sse.set_reconnect_interval(100);
  14634. sse.set_max_reconnect_attempts(3);
  14635. sse.start_async();
  14636. // Wait for at least 2 connections
  14637. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14638. sse.stop();
  14639. // Verify behavior
  14640. std::lock_guard<std::mutex> lock(id_mutex);
  14641. EXPECT_GE(received_last_event_ids.size(), 2u);
  14642. // First connection should have no Last-Event-ID
  14643. if (!received_last_event_ids.empty()) {
  14644. EXPECT_EQ(received_last_event_ids[0], "");
  14645. }
  14646. // Second connection should have Last-Event-ID from first connection
  14647. if (received_last_event_ids.size() >= 2) {
  14648. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14649. }
  14650. }
  14651. // Test: set_headers updates headers used on reconnect
  14652. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14653. std::vector<std::string> received_tokens;
  14654. std::mutex token_mutex;
  14655. // Endpoint that captures Authorization header
  14656. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14657. {
  14658. std::lock_guard<std::mutex> lock(token_mutex);
  14659. received_tokens.push_back(req.get_header_value("Authorization"));
  14660. }
  14661. res.set_chunked_content_provider(
  14662. "text/event-stream", [](size_t offset, DataSink &sink) {
  14663. if (offset == 0) {
  14664. std::string event = "data: hello\n\n";
  14665. sink.write(event.data(), event.size());
  14666. }
  14667. return false; // Close connection to trigger reconnect
  14668. });
  14669. });
  14670. Client client("localhost", get_port());
  14671. Headers headers = {{"Authorization", "Bearer old-token"}};
  14672. sse::SSEClient sse(client, "/auth-check", headers);
  14673. // Update headers on each successful connection
  14674. sse.on_open(
  14675. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14676. sse.set_reconnect_interval(100);
  14677. sse.set_max_reconnect_attempts(3);
  14678. sse.start_async();
  14679. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14680. sse.stop();
  14681. std::lock_guard<std::mutex> lock(token_mutex);
  14682. ASSERT_GE(received_tokens.size(), 2u);
  14683. // First connection uses original header
  14684. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14685. // Second connection uses updated header from set_headers
  14686. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14687. }
  14688. // Test: 401 allows reconnection (so on_error can refresh headers)
  14689. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14690. std::atomic<int> connection_count{0};
  14691. // Endpoint: returns 401 on first attempt, 200 on second
  14692. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14693. int conn = connection_count.fetch_add(1);
  14694. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14695. res.status = StatusCode::Unauthorized_401;
  14696. res.set_content("Unauthorized", "text/plain");
  14697. return;
  14698. }
  14699. res.set_chunked_content_provider(
  14700. "text/event-stream", [](size_t offset, DataSink &sink) {
  14701. if (offset == 0) {
  14702. std::string event = "data: authenticated\n\n";
  14703. sink.write(event.data(), event.size());
  14704. }
  14705. return false;
  14706. });
  14707. });
  14708. Client client("localhost", get_port());
  14709. Headers headers = {{"Authorization", "Bearer expired"}};
  14710. sse::SSEClient sse(client, "/auth-retry", headers);
  14711. std::atomic<bool> message_received{false};
  14712. // Refresh token on error
  14713. sse.on_error(
  14714. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14715. sse.on_message([&](const sse::SSEMessage &msg) {
  14716. if (msg.data == "authenticated") { message_received.store(true); }
  14717. });
  14718. sse.set_reconnect_interval(100);
  14719. sse.set_max_reconnect_attempts(3);
  14720. sse.start_async();
  14721. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14722. sse.stop();
  14723. // Should have reconnected after 401 and succeeded with new token
  14724. EXPECT_GE(connection_count.load(), 2);
  14725. EXPECT_TRUE(message_received.load());
  14726. }
  14727. TEST(Issue2318Test, EmptyHostString) {
  14728. {
  14729. httplib::Client cli_empty("", PORT);
  14730. auto res = cli_empty.Get("/");
  14731. ASSERT_FALSE(res);
  14732. EXPECT_EQ(httplib::Error::Connection, res.error());
  14733. }
  14734. {
  14735. httplib::Client cli(" ", PORT);
  14736. auto res = cli.Get("/");
  14737. ASSERT_FALSE(res);
  14738. EXPECT_EQ(httplib::Error::Connection, res.error());
  14739. }
  14740. }
  14741. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14742. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14743. Server svr;
  14744. // Set a small payload limit (1KB)
  14745. svr.set_payload_max_length(1024);
  14746. svr.Post("/test", [&](const Request &req, Response &res) {
  14747. res.set_content("Body size: " + std::to_string(req.body.size()),
  14748. "text/plain");
  14749. });
  14750. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14751. auto se = detail::scope_exit([&] {
  14752. svr.stop();
  14753. listen_thread.join();
  14754. });
  14755. svr.wait_until_ready();
  14756. // Create data that compresses well but exceeds limit when decompressed
  14757. // 8KB of repeated null bytes compresses to a very small size
  14758. std::string original_data(8 * 1024, '\0');
  14759. // Compress the data using gzip
  14760. std::string compressed_data;
  14761. detail::gzip_compressor compressor;
  14762. compressor.compress(original_data.data(), original_data.size(), true,
  14763. [&](const char *data, size_t size) {
  14764. compressed_data.append(data, size);
  14765. return true;
  14766. });
  14767. // Verify compression worked (compressed should be much smaller)
  14768. ASSERT_LT(compressed_data.size(), original_data.size());
  14769. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14770. // Send compressed data with Content-Encoding: gzip
  14771. Client cli(HOST, PORT);
  14772. Headers headers = {{"Content-Encoding", "gzip"}};
  14773. auto res =
  14774. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14775. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14776. ASSERT_TRUE(res);
  14777. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14778. }
  14779. #endif
  14780. // ============================================================================
  14781. // OpenSSL-Specific Tests
  14782. // ============================================================================
  14783. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14784. X509 *readCertificate(const std::string &strFileName) {
  14785. std::ifstream inStream(strFileName);
  14786. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14787. std::istreambuf_iterator<char>());
  14788. if (strCertPEM.empty()) return (nullptr);
  14789. BIO *pbCert = BIO_new(BIO_s_mem());
  14790. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14791. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14792. BIO_free(pbCert);
  14793. return (pCert);
  14794. }
  14795. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14796. std::ifstream inStream(strFileName);
  14797. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14798. std::istreambuf_iterator<char>());
  14799. if (strPrivateKeyPEM.empty()) return (nullptr);
  14800. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14801. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14802. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14803. BIO_free(pbPrivKey);
  14804. return (pPrivateKey);
  14805. }
  14806. TEST(BindServerTest, UpdateCerts) {
  14807. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14808. int port = svr.bind_to_any_port("0.0.0.0");
  14809. ASSERT_TRUE(svr.is_valid());
  14810. ASSERT_TRUE(port > 0);
  14811. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14812. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14813. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14814. ASSERT_TRUE(cert != nullptr);
  14815. ASSERT_TRUE(ca_cert != nullptr);
  14816. ASSERT_TRUE(key != nullptr);
  14817. X509_STORE *cert_store = X509_STORE_new();
  14818. X509_STORE_add_cert(cert_store, ca_cert);
  14819. // svr.update_certs(cert, key, cert_store); // deprecated
  14820. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14821. CLIENT_CA_CERT_FILE);
  14822. ASSERT_TRUE(svr.is_valid());
  14823. svr.stop();
  14824. X509_STORE_free(cert_store);
  14825. X509_free(cert);
  14826. X509_free(ca_cert);
  14827. EVP_PKEY_free(key);
  14828. }
  14829. // Test that update_certs() updates client CA list correctly
  14830. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14831. // Start with file-based constructor
  14832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14833. ASSERT_TRUE(svr.is_valid());
  14834. // Initially no client CA list should be set
  14835. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14836. ASSERT_TRUE(ssl_ctx != nullptr);
  14837. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14838. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14839. EXPECT_EQ(0, count_before);
  14840. // Now update with client CA (PEM string)
  14841. std::string cert_pem, key_pem, ca_pem;
  14842. read_file(SERVER_CERT_FILE, cert_pem);
  14843. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14844. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14845. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14846. ASSERT_TRUE(svr.is_valid());
  14847. // Now client CA list should be set
  14848. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14849. ASSERT_TRUE(ca_list_after != nullptr);
  14850. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14851. }
  14852. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14853. // Test that the file-path SSLServer constructor properly sets the client CA
  14854. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14856. ASSERT_TRUE(svr.is_valid());
  14857. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14858. ASSERT_TRUE(ssl_ctx != nullptr);
  14859. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14860. ASSERT_TRUE(ca_list != nullptr);
  14861. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14862. }
  14863. #endif
  14864. // ============================================================================
  14865. // MbedTLS-Specific Tests
  14866. // ============================================================================
  14867. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14868. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14869. using namespace httplib::tls;
  14870. // Track if callback was invoked
  14871. bool callback_invoked = false;
  14872. // The callback receives void* ctx which is actually MbedTlsContext*
  14873. // We can access the mbedtls_ssl_config via the context
  14874. auto setup_callback = [&callback_invoked](void *ctx) {
  14875. callback_invoked = true;
  14876. // Cast to MbedTlsContext* to access the ssl config
  14877. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14878. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14879. // Use static variables to hold certificate data (simplified for test)
  14880. static mbedtls_x509_crt own_cert;
  14881. static mbedtls_pk_context own_key;
  14882. static mbedtls_x509_crt ca_chain;
  14883. static bool initialized = false;
  14884. if (!initialized) {
  14885. mbedtls_x509_crt_init(&own_cert);
  14886. mbedtls_pk_init(&own_key);
  14887. mbedtls_x509_crt_init(&ca_chain);
  14888. // Load server certificate
  14889. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14890. return false;
  14891. }
  14892. // Load server private key
  14893. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14894. #if MBEDTLS_VERSION_MAJOR >= 3
  14895. ,
  14896. mbedtls_ctr_drbg_random, nullptr
  14897. #endif
  14898. ) != 0) {
  14899. return false;
  14900. }
  14901. // Load CA chain for client verification
  14902. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14903. return false;
  14904. }
  14905. initialized = true;
  14906. }
  14907. // Configure the SSL config
  14908. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14909. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14910. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14911. // Set minimum TLS version using mbedTLS native API
  14912. #if MBEDTLS_VERSION_MAJOR >= 3
  14913. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14914. #else
  14915. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14916. MBEDTLS_SSL_MINOR_VERSION_3);
  14917. #endif
  14918. return true;
  14919. };
  14920. SSLServer svr(setup_callback);
  14921. ASSERT_TRUE(svr.is_valid());
  14922. ASSERT_TRUE(callback_invoked);
  14923. svr.Get("/test", [&](const Request &req, Response &res) {
  14924. res.set_content("test", "text/plain");
  14925. auto cert = req.peer_cert();
  14926. ASSERT_TRUE(static_cast<bool>(cert));
  14927. auto common_name = cert.subject_cn();
  14928. EXPECT_EQ("Common Name", common_name);
  14929. });
  14930. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14931. auto se = detail::scope_exit([&] {
  14932. svr.stop();
  14933. t.join();
  14934. ASSERT_FALSE(svr.is_running());
  14935. });
  14936. svr.wait_until_ready();
  14937. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14938. cli.enable_server_certificate_verification(false);
  14939. cli.set_connection_timeout(30);
  14940. auto res = cli.Get("/test");
  14941. ASSERT_TRUE(res);
  14942. ASSERT_EQ(StatusCode::OK_200, res->status);
  14943. }
  14944. #endif
  14945. // WebSocket Tests
  14946. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14947. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14948. // defining the meaning of these bits has been negotiated.
  14949. auto make_frame = [](uint8_t first_byte) {
  14950. std::string frame;
  14951. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14952. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14953. frame += "Hello";
  14954. return frame;
  14955. };
  14956. // RSV1 set (0x40)
  14957. {
  14958. detail::BufferStream strm;
  14959. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14960. ws::Opcode opcode;
  14961. std::string payload;
  14962. bool fin;
  14963. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14964. false, 1024));
  14965. }
  14966. // RSV2 set (0x20)
  14967. {
  14968. detail::BufferStream strm;
  14969. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14970. ws::Opcode opcode;
  14971. std::string payload;
  14972. bool fin;
  14973. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14974. false, 1024));
  14975. }
  14976. // RSV3 set (0x10)
  14977. {
  14978. detail::BufferStream strm;
  14979. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14980. ws::Opcode opcode;
  14981. std::string payload;
  14982. bool fin;
  14983. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14984. false, 1024));
  14985. }
  14986. // No RSV bits set - should succeed
  14987. {
  14988. detail::BufferStream strm;
  14989. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14990. ws::Opcode opcode;
  14991. std::string payload;
  14992. bool fin;
  14993. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14994. false, 1024));
  14995. EXPECT_EQ(ws::Opcode::Text, opcode);
  14996. EXPECT_EQ("Hello", payload);
  14997. EXPECT_TRUE(fin);
  14998. }
  14999. }
  15000. TEST(WebSocketTest, ControlFrameValidation) {
  15001. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15002. // payload length <= 125.
  15003. // Ping with FIN=0 - must be rejected
  15004. {
  15005. detail::BufferStream strm;
  15006. std::string frame;
  15007. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15008. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15009. strm.write(frame.data(), frame.size());
  15010. ws::Opcode opcode;
  15011. std::string payload;
  15012. bool fin;
  15013. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15014. false, 1024));
  15015. }
  15016. // Close with FIN=0 - must be rejected
  15017. {
  15018. detail::BufferStream strm;
  15019. std::string frame;
  15020. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15021. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15022. strm.write(frame.data(), frame.size());
  15023. ws::Opcode opcode;
  15024. std::string payload;
  15025. bool fin;
  15026. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15027. false, 1024));
  15028. }
  15029. // Ping with payload_len=126 (extended length) - must be rejected
  15030. {
  15031. detail::BufferStream strm;
  15032. std::string frame;
  15033. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15034. frame += static_cast<char>(126); // payload_len=126 (>125)
  15035. frame += static_cast<char>(0x00); // extended length high byte
  15036. frame += static_cast<char>(126); // extended length low byte
  15037. frame += std::string(126, 'x');
  15038. strm.write(frame.data(), frame.size());
  15039. ws::Opcode opcode;
  15040. std::string payload;
  15041. bool fin;
  15042. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15043. false, 1024));
  15044. }
  15045. // Ping with FIN=1 and payload_len=125 - should succeed
  15046. {
  15047. detail::BufferStream strm;
  15048. std::string frame;
  15049. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15050. frame += static_cast<char>(125); // payload_len=125
  15051. frame += std::string(125, 'x');
  15052. strm.write(frame.data(), frame.size());
  15053. ws::Opcode opcode;
  15054. std::string payload;
  15055. bool fin;
  15056. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15057. false, 1024));
  15058. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15059. EXPECT_EQ(125u, payload.size());
  15060. EXPECT_TRUE(fin);
  15061. }
  15062. }
  15063. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15064. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15065. // length MUST be 0.
  15066. // MSB set - must be rejected
  15067. {
  15068. detail::BufferStream strm;
  15069. std::string frame;
  15070. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15071. frame += static_cast<char>(127); // 64-bit extended length
  15072. frame += static_cast<char>(0x80); // MSB set (invalid)
  15073. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15074. strm.write(frame.data(), frame.size());
  15075. ws::Opcode opcode;
  15076. std::string payload;
  15077. bool fin;
  15078. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15079. false, 1024));
  15080. }
  15081. // MSB clear - should pass length parsing (will be rejected by max_len,
  15082. // but that's a different check; use a small length to verify)
  15083. {
  15084. detail::BufferStream strm;
  15085. std::string frame;
  15086. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15087. frame += static_cast<char>(127); // 64-bit extended length
  15088. frame += std::string(7, '\0'); // high bytes = 0
  15089. frame += static_cast<char>(0x03); // length = 3
  15090. frame += "abc";
  15091. strm.write(frame.data(), frame.size());
  15092. ws::Opcode opcode;
  15093. std::string payload;
  15094. bool fin;
  15095. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15096. false, 1024));
  15097. EXPECT_EQ(ws::Opcode::Text, opcode);
  15098. EXPECT_EQ("abc", payload);
  15099. }
  15100. }
  15101. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15102. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15103. // Valid UTF-8
  15104. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15105. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15106. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15107. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15108. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15109. // Invalid UTF-8
  15110. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15111. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15112. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15113. EXPECT_FALSE(
  15114. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15115. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15116. }
  15117. TEST(WebSocketTest, ConnectAndDisconnect) {
  15118. Server svr;
  15119. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15120. std::string msg;
  15121. while (ws.read(msg)) {}
  15122. });
  15123. auto port = svr.bind_to_any_port(HOST);
  15124. std::thread t([&]() { svr.listen_after_bind(); });
  15125. svr.wait_until_ready();
  15126. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15127. ASSERT_TRUE(client.connect());
  15128. EXPECT_TRUE(client.is_open());
  15129. client.close();
  15130. EXPECT_FALSE(client.is_open());
  15131. svr.stop();
  15132. t.join();
  15133. }
  15134. TEST(WebSocketTest, ValidURL) {
  15135. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15136. EXPECT_TRUE(ws1.is_valid());
  15137. ws::WebSocketClient ws2("ws://example.com/path");
  15138. EXPECT_TRUE(ws2.is_valid());
  15139. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15140. EXPECT_TRUE(ws3.is_valid());
  15141. #ifdef CPPHTTPLIB_SSL_ENABLED
  15142. ws::WebSocketClient wss1("wss://example.com/path");
  15143. EXPECT_TRUE(wss1.is_valid());
  15144. ws::WebSocketClient wss2("wss://example.com:443/path");
  15145. EXPECT_TRUE(wss2.is_valid());
  15146. #endif
  15147. }
  15148. TEST(WebSocketTest, InvalidURL) {
  15149. // No scheme
  15150. ws::WebSocketClient ws1("localhost:8080/path");
  15151. EXPECT_FALSE(ws1.is_valid());
  15152. // No path
  15153. ws::WebSocketClient ws2("ws://localhost:8080");
  15154. EXPECT_FALSE(ws2.is_valid());
  15155. // Empty string
  15156. ws::WebSocketClient ws3("");
  15157. EXPECT_FALSE(ws3.is_valid());
  15158. // Missing host
  15159. ws::WebSocketClient ws4("ws://:8080/path");
  15160. EXPECT_FALSE(ws4.is_valid());
  15161. // Port number overflow — should not crash
  15162. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15163. EXPECT_FALSE(ws5.is_valid());
  15164. // Port out of range
  15165. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15166. EXPECT_FALSE(ws6.is_valid());
  15167. }
  15168. TEST(WebSocketTest, UnsupportedScheme) {
  15169. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15170. ws::WebSocketClient ws1("http://localhost:8080/path");
  15171. EXPECT_FALSE(ws1.is_valid());
  15172. ws::WebSocketClient ws2("https://localhost:8080/path");
  15173. EXPECT_FALSE(ws2.is_valid());
  15174. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15175. EXPECT_FALSE(ws3.is_valid());
  15176. #else
  15177. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15178. std::invalid_argument);
  15179. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15180. std::invalid_argument);
  15181. #endif
  15182. }
  15183. TEST(WebSocketTest, ConnectWhenInvalid) {
  15184. ws::WebSocketClient ws("not a valid url");
  15185. EXPECT_FALSE(ws.is_valid());
  15186. EXPECT_FALSE(ws.connect());
  15187. }
  15188. TEST(WebSocketTest, DefaultPort) {
  15189. ws::WebSocketClient ws1("ws://example.com/path");
  15190. EXPECT_TRUE(ws1.is_valid());
  15191. // ws:// defaults to port 80 (verified by successful parse)
  15192. #ifdef CPPHTTPLIB_SSL_ENABLED
  15193. ws::WebSocketClient ws2("wss://example.com/path");
  15194. EXPECT_TRUE(ws2.is_valid());
  15195. // wss:// defaults to port 443 (verified by successful parse)
  15196. #endif
  15197. }
  15198. TEST(WebSocketTest, IPv6LiteralAddress) {
  15199. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15200. EXPECT_TRUE(ws1.is_valid());
  15201. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15202. EXPECT_TRUE(ws2.is_valid());
  15203. }
  15204. TEST(WebSocketTest, ComplexPath) {
  15205. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15206. EXPECT_TRUE(ws1.is_valid());
  15207. ws::WebSocketClient ws2("ws://localhost:8080/");
  15208. EXPECT_TRUE(ws2.is_valid());
  15209. }
  15210. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15211. Server svr;
  15212. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15213. std::string msg;
  15214. while (ws.read(msg)) {}
  15215. });
  15216. auto port = svr.bind_to_any_port(HOST);
  15217. std::thread t([&]() { svr.listen_after_bind(); });
  15218. svr.wait_until_ready();
  15219. auto another_host = "example.com";
  15220. auto wrong_ip = "192.0.2.1";
  15221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15222. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15223. ASSERT_TRUE(client.connect());
  15224. EXPECT_TRUE(client.is_open());
  15225. client.close();
  15226. svr.stop();
  15227. t.join();
  15228. }
  15229. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15230. Server svr;
  15231. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15232. std::string msg;
  15233. while (ws.read(msg)) {}
  15234. });
  15235. auto port = svr.bind_to_any_port(HOST);
  15236. std::thread t([&]() { svr.listen_after_bind(); });
  15237. svr.wait_until_ready();
  15238. auto wrong_ip = "192.0.2.1";
  15239. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15240. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15241. client.set_connection_timeout(1);
  15242. client.set_read_timeout(1);
  15243. client.set_write_timeout(1);
  15244. EXPECT_FALSE(client.connect());
  15245. EXPECT_FALSE(client.is_open());
  15246. svr.stop();
  15247. t.join();
  15248. }
  15249. class WebSocketIntegrationTest : public ::testing::Test {
  15250. protected:
  15251. void SetUp() override {
  15252. server_ = httplib::detail::make_unique<Server>();
  15253. setup_server();
  15254. start_server();
  15255. }
  15256. void TearDown() override {
  15257. server_->stop();
  15258. if (server_thread_.joinable()) { server_thread_.join(); }
  15259. }
  15260. void setup_server() {
  15261. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15262. std::string msg;
  15263. ws::ReadResult ret;
  15264. while ((ret = ws.read(msg))) {
  15265. if (ret == ws::Binary) {
  15266. ws.send(msg.data(), msg.size());
  15267. } else {
  15268. ws.send(msg);
  15269. }
  15270. }
  15271. });
  15272. server_->WebSocket("/ws-echo-string",
  15273. [](const Request &, ws::WebSocket &ws) {
  15274. std::string msg;
  15275. while (ws.read(msg)) {
  15276. ws.send("echo: " + msg);
  15277. }
  15278. });
  15279. server_->WebSocket(
  15280. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15281. // Echo back request metadata
  15282. ws.send("path:" + req.path);
  15283. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15284. std::string msg;
  15285. while (ws.read(msg)) {}
  15286. });
  15287. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15288. std::string msg;
  15289. ws.read(msg); // wait for a message
  15290. ws.close();
  15291. });
  15292. server_->WebSocket("/ws-close-status",
  15293. [](const Request &, ws::WebSocket &ws) {
  15294. std::string msg;
  15295. ws.read(msg); // wait for a message
  15296. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15297. });
  15298. server_->WebSocket(
  15299. "/ws-subprotocol",
  15300. [](const Request &, ws::WebSocket &ws) {
  15301. std::string msg;
  15302. while (ws.read(msg)) {
  15303. ws.send(msg);
  15304. }
  15305. },
  15306. [](const std::vector<std::string> &protocols) -> std::string {
  15307. for (const auto &p : protocols) {
  15308. if (p == "graphql-ws") { return p; }
  15309. }
  15310. return "";
  15311. });
  15312. }
  15313. void start_server() {
  15314. port_ = server_->bind_to_any_port(HOST);
  15315. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15316. server_->wait_until_ready();
  15317. }
  15318. std::unique_ptr<Server> server_;
  15319. std::thread server_thread_;
  15320. int port_ = 0;
  15321. };
  15322. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15323. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15324. "/ws-echo");
  15325. ASSERT_TRUE(client.connect());
  15326. ASSERT_TRUE(client.is_open());
  15327. ASSERT_TRUE(client.send("Hello WebSocket"));
  15328. std::string msg;
  15329. EXPECT_EQ(ws::Text, client.read(msg));
  15330. EXPECT_EQ("Hello WebSocket", msg);
  15331. client.close();
  15332. }
  15333. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15335. "/ws-echo");
  15336. ASSERT_TRUE(client.connect());
  15337. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15338. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15339. std::string msg;
  15340. EXPECT_EQ(ws::Binary, client.read(msg));
  15341. EXPECT_EQ(binary_data, msg);
  15342. client.close();
  15343. }
  15344. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15345. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15346. "/ws-echo");
  15347. ASSERT_TRUE(client.connect());
  15348. for (int i = 0; i < 10; i++) {
  15349. auto text = "message " + std::to_string(i);
  15350. ASSERT_TRUE(client.send(text));
  15351. std::string msg;
  15352. ASSERT_TRUE(client.read(msg));
  15353. EXPECT_EQ(text, msg);
  15354. }
  15355. client.close();
  15356. }
  15357. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15358. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15359. "/ws-close");
  15360. ASSERT_TRUE(client.connect());
  15361. // Send a message to trigger the server to close
  15362. ASSERT_TRUE(client.send("trigger close"));
  15363. // The server will close, so read should return false
  15364. std::string msg;
  15365. EXPECT_FALSE(client.read(msg));
  15366. EXPECT_FALSE(client.is_open());
  15367. }
  15368. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15369. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15370. "/ws-echo");
  15371. ASSERT_TRUE(client.connect());
  15372. // 128KB message
  15373. std::string large_data(128 * 1024, 'X');
  15374. ASSERT_TRUE(client.send(large_data));
  15375. std::string msg;
  15376. ASSERT_TRUE(client.read(msg));
  15377. EXPECT_EQ(large_data, msg);
  15378. client.close();
  15379. }
  15380. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15381. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15382. "/ws-echo");
  15383. ASSERT_TRUE(client.connect());
  15384. const int num_threads = 4;
  15385. std::vector<std::thread> threads;
  15386. std::atomic<int> send_count{0};
  15387. for (int t = 0; t < num_threads; t++) {
  15388. threads.emplace_back([&client, &send_count, t]() {
  15389. for (int i = 0; i < 5; i++) {
  15390. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15391. if (client.send(text)) { send_count++; }
  15392. }
  15393. });
  15394. }
  15395. for (auto &th : threads) {
  15396. th.join();
  15397. }
  15398. int received = 0;
  15399. std::string msg;
  15400. while (received < send_count.load()) {
  15401. if (!client.read(msg)) { break; }
  15402. received++;
  15403. }
  15404. EXPECT_EQ(send_count.load(), received);
  15405. client.close();
  15406. }
  15407. TEST_F(WebSocketIntegrationTest, ReadString) {
  15408. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15409. "/ws-echo-string");
  15410. ASSERT_TRUE(client.connect());
  15411. ASSERT_TRUE(client.send("hello"));
  15412. std::string msg;
  15413. ASSERT_TRUE(client.read(msg));
  15414. EXPECT_EQ("echo: hello", msg);
  15415. ASSERT_TRUE(client.send("world"));
  15416. ASSERT_TRUE(client.read(msg));
  15417. EXPECT_EQ("echo: world", msg);
  15418. client.close();
  15419. }
  15420. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15421. Headers headers = {{"X-Test-Header", "test-value"}};
  15422. ws::WebSocketClient client(
  15423. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15424. ASSERT_TRUE(client.connect());
  15425. std::string msg;
  15426. ASSERT_TRUE(client.read(msg));
  15427. EXPECT_EQ("path:/ws-request-info", msg);
  15428. ASSERT_TRUE(client.read(msg));
  15429. EXPECT_EQ("header:test-value", msg);
  15430. client.close();
  15431. }
  15432. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15434. "/ws-echo");
  15435. client.set_read_timeout(1, 0); // 1 second
  15436. ASSERT_TRUE(client.connect());
  15437. // Don't send anything — server echo handler waits for a message,
  15438. // so read() should time out and return false.
  15439. std::string msg;
  15440. EXPECT_FALSE(client.read(msg));
  15441. }
  15442. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15443. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15444. "/ws-echo");
  15445. client.set_read_timeout(5, 0);
  15446. ASSERT_TRUE(client.connect());
  15447. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15448. // The server should reject it and close the connection.
  15449. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15450. client.send(oversized);
  15451. // The server's read() should have failed due to payload limit,
  15452. // so our read() should return false (connection closed).
  15453. std::string msg;
  15454. EXPECT_FALSE(client.read(msg));
  15455. }
  15456. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15457. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15458. "/ws-echo");
  15459. client.set_read_timeout(10, 0);
  15460. ASSERT_TRUE(client.connect());
  15461. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15462. // This should succeed.
  15463. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15464. ASSERT_TRUE(client.send(at_limit));
  15465. std::string msg;
  15466. ASSERT_TRUE(client.read(msg));
  15467. EXPECT_EQ(at_limit.size(), msg.size());
  15468. client.close();
  15469. }
  15470. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15471. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15472. "/nonexistent");
  15473. EXPECT_FALSE(client.connect());
  15474. EXPECT_FALSE(client.is_open());
  15475. }
  15476. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15477. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15478. "/ws-echo");
  15479. ASSERT_TRUE(client.connect());
  15480. ASSERT_TRUE(client.send(""));
  15481. std::string msg;
  15482. EXPECT_EQ(ws::Text, client.read(msg));
  15483. EXPECT_EQ("", msg);
  15484. client.close();
  15485. }
  15486. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15487. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15488. "/ws-echo");
  15489. // First connection
  15490. ASSERT_TRUE(client.connect());
  15491. ASSERT_TRUE(client.send("first"));
  15492. std::string msg;
  15493. ASSERT_TRUE(client.read(msg));
  15494. EXPECT_EQ("first", msg);
  15495. client.close();
  15496. EXPECT_FALSE(client.is_open());
  15497. // Reconnect using the same client object
  15498. ASSERT_TRUE(client.connect());
  15499. ASSERT_TRUE(client.is_open());
  15500. ASSERT_TRUE(client.send("second"));
  15501. ASSERT_TRUE(client.read(msg));
  15502. EXPECT_EQ("second", msg);
  15503. client.close();
  15504. }
  15505. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15506. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15507. "/ws-close-status");
  15508. ASSERT_TRUE(client.connect());
  15509. // Trigger the server to close with GoingAway status
  15510. ASSERT_TRUE(client.send("trigger"));
  15511. // read() should return false after receiving the close frame
  15512. std::string msg;
  15513. EXPECT_FALSE(client.read(msg));
  15514. EXPECT_FALSE(client.is_open());
  15515. }
  15516. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15517. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15518. "/ws-echo");
  15519. ASSERT_TRUE(client.connect());
  15520. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15521. EXPECT_FALSE(client.is_open());
  15522. }
  15523. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15524. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15525. ws::WebSocketClient client(
  15526. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15527. ASSERT_TRUE(client.connect());
  15528. // Server should have selected graphql-ws
  15529. EXPECT_EQ("graphql-ws", client.subprotocol());
  15530. client.close();
  15531. }
  15532. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15533. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15534. ws::WebSocketClient client(
  15535. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15536. ASSERT_TRUE(client.connect());
  15537. // Server should not have selected any subprotocol
  15538. EXPECT_TRUE(client.subprotocol().empty());
  15539. client.close();
  15540. }
  15541. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15542. // Connect without requesting any subprotocol
  15543. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15544. "/ws-subprotocol");
  15545. ASSERT_TRUE(client.connect());
  15546. EXPECT_TRUE(client.subprotocol().empty());
  15547. client.close();
  15548. }
  15549. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15550. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15551. "/ws-echo");
  15552. client.set_tcp_nodelay(true);
  15553. client.set_connection_timeout(3, 0);
  15554. bool socket_options_called = false;
  15555. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15556. ASSERT_TRUE(client.connect());
  15557. ASSERT_TRUE(client.is_open());
  15558. EXPECT_TRUE(socket_options_called);
  15559. ASSERT_TRUE(client.send("hello"));
  15560. std::string msg;
  15561. auto result = client.read(msg);
  15562. EXPECT_EQ(result, ws::ReadResult::Text);
  15563. EXPECT_EQ(msg, "hello");
  15564. client.close();
  15565. }
  15566. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15567. Server svr;
  15568. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15569. if (!req.has_header("Authorization")) {
  15570. res.status = StatusCode::Unauthorized_401;
  15571. res.set_content("Unauthorized", "text/plain");
  15572. return Server::HandlerResponse::Handled;
  15573. }
  15574. return Server::HandlerResponse::Unhandled;
  15575. });
  15576. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15577. std::string msg;
  15578. while (ws.read(msg)) {
  15579. ws.send(msg);
  15580. }
  15581. });
  15582. auto port = svr.bind_to_any_port("localhost");
  15583. std::thread t([&]() { svr.listen_after_bind(); });
  15584. svr.wait_until_ready();
  15585. // Without Authorization header - should be rejected before upgrade
  15586. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15587. EXPECT_FALSE(client1.connect());
  15588. // With Authorization header - should succeed
  15589. Headers headers = {{"Authorization", "Bearer token123"}};
  15590. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15591. headers);
  15592. ASSERT_TRUE(client2.connect());
  15593. ASSERT_TRUE(client2.send("hello"));
  15594. std::string msg;
  15595. ASSERT_TRUE(client2.read(msg));
  15596. EXPECT_EQ("hello", msg);
  15597. client2.close();
  15598. svr.stop();
  15599. t.join();
  15600. }
  15601. TEST(WebSocketTest, QueryStringInHandshake) {
  15602. Server svr;
  15603. std::mutex mtx;
  15604. std::string received_target;
  15605. std::string received_token;
  15606. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15607. {
  15608. std::lock_guard<std::mutex> lock(mtx);
  15609. received_target = req.target;
  15610. if (req.has_param("token")) {
  15611. received_token = req.get_param_value("token");
  15612. }
  15613. }
  15614. std::string msg;
  15615. while (ws.read(msg)) {
  15616. ws.send(msg);
  15617. }
  15618. });
  15619. auto port = svr.bind_to_any_port("localhost");
  15620. std::thread t([&]() { svr.listen_after_bind(); });
  15621. svr.wait_until_ready();
  15622. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15623. "/ws?token=ABC&session=123");
  15624. ASSERT_TRUE(client.connect());
  15625. // Round-trip ensures the handler has run and captured the request.
  15626. ASSERT_TRUE(client.send("hello"));
  15627. std::string msg;
  15628. ASSERT_TRUE(client.read(msg));
  15629. EXPECT_EQ("hello", msg);
  15630. client.close();
  15631. {
  15632. std::lock_guard<std::mutex> lock(mtx);
  15633. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15634. EXPECT_EQ("ABC", received_token);
  15635. }
  15636. svr.stop();
  15637. t.join();
  15638. }
  15639. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15640. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15641. protected:
  15642. void SetUp() override {
  15643. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15644. SERVER_PRIVATE_KEY_FILE);
  15645. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15646. std::string msg;
  15647. ws::ReadResult ret;
  15648. while ((ret = ws.read(msg))) {
  15649. if (ret == ws::Binary) {
  15650. ws.send(msg.data(), msg.size());
  15651. } else {
  15652. ws.send(msg);
  15653. }
  15654. }
  15655. });
  15656. port_ = server_->bind_to_any_port(HOST);
  15657. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15658. server_->wait_until_ready();
  15659. }
  15660. void TearDown() override {
  15661. server_->stop();
  15662. if (server_thread_.joinable()) { server_thread_.join(); }
  15663. }
  15664. std::unique_ptr<SSLServer> server_;
  15665. std::thread server_thread_;
  15666. int port_ = 0;
  15667. };
  15668. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15669. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15670. "/ws-echo");
  15671. client.enable_server_certificate_verification(false);
  15672. ASSERT_TRUE(client.connect());
  15673. ASSERT_TRUE(client.is_open());
  15674. ASSERT_TRUE(client.send("Hello WSS"));
  15675. std::string msg;
  15676. EXPECT_EQ(ws::Text, client.read(msg));
  15677. EXPECT_EQ("Hello WSS", msg);
  15678. client.close();
  15679. }
  15680. #endif
  15681. #ifdef CPPHTTPLIB_SSL_ENABLED
  15682. class WebSocketSSLCATest : public ::testing::Test {
  15683. protected:
  15684. void SetUp() override {
  15685. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  15686. SERVER_PRIVATE_KEY_FILE);
  15687. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15688. std::string msg;
  15689. while (ws.read(msg)) {
  15690. ws.send(msg);
  15691. }
  15692. });
  15693. port_ = server_->bind_to_any_port("127.0.0.1");
  15694. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15695. server_->wait_until_ready();
  15696. }
  15697. void TearDown() override {
  15698. server_->stop();
  15699. if (server_thread_.joinable()) { server_thread_.join(); }
  15700. }
  15701. std::string url() const {
  15702. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  15703. }
  15704. std::unique_ptr<SSLServer> server_;
  15705. std::thread server_thread_;
  15706. int port_ = 0;
  15707. };
  15708. // A custom CA loaded as PEM verifies the server with full certificate
  15709. // verification enabled
  15710. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  15711. ws::WebSocketClient client(url());
  15712. std::string cert;
  15713. read_file(SERVER_CERT2_FILE, cert);
  15714. client.load_ca_cert_store(cert.c_str(), cert.size());
  15715. ASSERT_TRUE(client.connect());
  15716. ASSERT_TRUE(client.send("hello"));
  15717. std::string msg;
  15718. EXPECT_EQ(ws::Text, client.read(msg));
  15719. EXPECT_EQ("hello", msg);
  15720. client.close();
  15721. }
  15722. // A custom CA that does not cover the server must fail verification (the
  15723. // custom CA is exclusive; system certs are not loaded alongside it)
  15724. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  15725. ws::WebSocketClient client(url());
  15726. std::string cert;
  15727. read_file(CLIENT_CA_CERT_FILE, cert);
  15728. client.load_ca_cert_store(cert.c_str(), cert.size());
  15729. ASSERT_FALSE(client.connect());
  15730. }
  15731. // Regression test: reconnecting with a native custom CA store used to reuse
  15732. // a store handle the previous TLS context had already freed (use-after-free
  15733. // under the OpenSSL backend). The context now lives as long as the client.
  15734. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  15735. ws::WebSocketClient client(url());
  15736. std::string cert;
  15737. read_file(SERVER_CERT2_FILE, cert);
  15738. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15739. ASSERT_TRUE(client.connect());
  15740. client.close();
  15741. ASSERT_TRUE(client.connect());
  15742. ASSERT_TRUE(client.send("again"));
  15743. std::string msg;
  15744. EXPECT_EQ(ws::Text, client.read(msg));
  15745. EXPECT_EQ("again", msg);
  15746. client.close();
  15747. }
  15748. // Regression test: a certificate with a trusted chain but no identity match
  15749. // for the server IP must be rejected. The Mbed TLS backend used to skip
  15750. // verification entirely for IP hosts, so this connection succeeded there.
  15751. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  15752. // chain verification while the identity check must still fail.
  15753. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  15754. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15755. ASSERT_TRUE(svr.is_valid());
  15756. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  15757. std::string msg;
  15758. while (ws.read(msg)) {
  15759. ws.send(msg);
  15760. }
  15761. });
  15762. auto port = svr.bind_to_any_port("127.0.0.1");
  15763. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15764. auto se = detail::scope_exit([&] {
  15765. svr.stop();
  15766. t.join();
  15767. });
  15768. svr.wait_until_ready();
  15769. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  15770. "/echo");
  15771. std::string cert;
  15772. read_file(SERVER_CERT_FILE, cert);
  15773. client.load_ca_cert_store(cert.c_str(), cert.size());
  15774. ASSERT_FALSE(client.connect());
  15775. }
  15776. #endif
  15777. #if !defined(_WIN32)
  15778. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15779. auto secret_dir = std::string("./symlink_test_secret");
  15780. auto served_dir = std::string("./symlink_test_served");
  15781. auto secret_file = secret_dir + "/secret.txt";
  15782. auto symlink_path = served_dir + "/escape";
  15783. // Setup: create directories and files
  15784. mkdir(secret_dir.c_str(), 0755);
  15785. mkdir(served_dir.c_str(), 0755);
  15786. {
  15787. std::ofstream ofs(secret_file);
  15788. ofs << "SECRET_DATA";
  15789. }
  15790. // Create symlink using absolute path so it resolves correctly
  15791. #ifdef PATH_MAX
  15792. char abs_secret[PATH_MAX];
  15793. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15794. #else
  15795. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15796. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15797. ASSERT_NE(nullptr, abs_secret);
  15798. #endif
  15799. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15800. auto se = detail::scope_exit([&] {
  15801. unlink(symlink_path.c_str());
  15802. unlink(secret_file.c_str());
  15803. rmdir(served_dir.c_str());
  15804. rmdir(secret_dir.c_str());
  15805. });
  15806. Server svr;
  15807. svr.set_mount_point("/", served_dir);
  15808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15809. auto se2 = detail::scope_exit([&] {
  15810. svr.stop();
  15811. listen_thread.join();
  15812. });
  15813. svr.wait_until_ready();
  15814. Client cli("localhost", PORT);
  15815. // Symlink pointing outside base dir should be blocked
  15816. auto res = cli.Get("/escape/secret.txt");
  15817. ASSERT_TRUE(res);
  15818. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15819. }
  15820. #endif
  15821. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15822. // A GET request with Content-Length to a static file handler must have its
  15823. // body drained before the keep-alive connection is reused. Otherwise the
  15824. // unread body bytes are interpreted as the next HTTP request.
  15825. //
  15826. // The body is sent AFTER receiving the first response (as in the original
  15827. // PoC) so that the stream_line_reader cannot buffer it together with the
  15828. // headers of the first request.
  15829. Server svr;
  15830. svr.set_mount_point("/", "./www");
  15831. std::atomic<int> smuggled_count(0);
  15832. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15833. smuggled_count++;
  15834. res.set_content("oops", "text/plain");
  15835. });
  15836. auto port = svr.bind_to_any_port("localhost");
  15837. thread t = thread([&] { svr.listen_after_bind(); });
  15838. auto se = detail::scope_exit([&] {
  15839. svr.stop();
  15840. t.join();
  15841. });
  15842. svr.wait_until_ready();
  15843. auto error = Error::Success;
  15844. auto sock = detail::create_client_socket(
  15845. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15846. /*connection_timeout_sec=*/2, 0,
  15847. /*read_timeout_sec=*/2, 0,
  15848. /*write_timeout_sec=*/2, 0, std::string(), error);
  15849. ASSERT_NE(INVALID_SOCKET, sock);
  15850. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15851. // The "smuggled" request will be sent as the body of the outer GET
  15852. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15853. "Host: localhost\r\n"
  15854. "Connection: close\r\n"
  15855. "\r\n";
  15856. // Step 1: Send only the outer request headers (no body yet)
  15857. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15858. "Host: localhost\r\n"
  15859. "Content-Length: " +
  15860. std::to_string(smuggled.size()) +
  15861. "\r\n"
  15862. "\r\n";
  15863. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15864. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15865. // Step 2: Read the first response (server serves file without reading body)
  15866. std::string first_response;
  15867. char buf[4096];
  15868. for (;;) {
  15869. auto n = recv(sock, buf, sizeof(buf), 0);
  15870. if (n <= 0) break;
  15871. first_response.append(buf, static_cast<size_t>(n));
  15872. // Stop once we have a complete response (headers + body)
  15873. auto hdr_end = first_response.find("\r\n\r\n");
  15874. if (hdr_end != std::string::npos) {
  15875. // Check for Content-Length to know when the body is complete
  15876. auto cl_pos = first_response.find("Content-Length:");
  15877. if (cl_pos != std::string::npos) {
  15878. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15879. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15880. auto cl = std::stoul(
  15881. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15882. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15883. } else {
  15884. break; // No Content-Length, assume headers-only response
  15885. }
  15886. }
  15887. }
  15888. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15889. // Step 3: Now send the body, which looks like a new HTTP request.
  15890. // On a vulnerable server the keep-alive loop reads this as a second request.
  15891. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15892. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15893. // Step 4: Try to read a second response (should NOT exist after fix)
  15894. std::string second_response;
  15895. for (;;) {
  15896. auto n = recv(sock, buf, sizeof(buf), 0);
  15897. if (n <= 0) break;
  15898. second_response.append(buf, static_cast<size_t>(n));
  15899. }
  15900. // The smuggled request must NOT have been processed
  15901. EXPECT_EQ(0, smuggled_count.load());
  15902. }
  15903. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15904. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15905. // must be rejected with 400 Bad Request.
  15906. Server svr;
  15907. svr.Post("/test", [&](const Request &, Response &res) {
  15908. res.set_content("ok", "text/plain");
  15909. });
  15910. thread t = thread([&] { svr.listen(HOST, PORT); });
  15911. auto se = detail::scope_exit([&] {
  15912. svr.stop();
  15913. t.join();
  15914. ASSERT_FALSE(svr.is_running());
  15915. });
  15916. svr.wait_until_ready();
  15917. // Exact "chunked"
  15918. {
  15919. auto req = "POST /test HTTP/1.1\r\n"
  15920. "Host: localhost\r\n"
  15921. "Content-Length: 5\r\n"
  15922. "Transfer-Encoding: chunked\r\n"
  15923. "Connection: close\r\n"
  15924. "\r\n"
  15925. "hello";
  15926. std::string response;
  15927. ASSERT_TRUE(send_request(1, req, &response));
  15928. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15929. response.substr(0, response.find("\r\n")));
  15930. }
  15931. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15932. {
  15933. auto req = "POST /test HTTP/1.1\r\n"
  15934. "Host: localhost\r\n"
  15935. "Content-Length: 5\r\n"
  15936. "Transfer-Encoding: gzip, chunked\r\n"
  15937. "Connection: close\r\n"
  15938. "\r\n"
  15939. "hello";
  15940. std::string response;
  15941. ASSERT_TRUE(send_request(1, req, &response));
  15942. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15943. response.substr(0, response.find("\r\n")));
  15944. }
  15945. }
  15946. // Regression for issue #2450: a DELETE without Content-Length on a
  15947. // keep-alive connection must not let the post-response drain consume the
  15948. // next request's bytes.
  15949. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15950. Server svr;
  15951. std::atomic<int> delete_count(0);
  15952. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15953. delete_count++;
  15954. res.status = StatusCode::NoContent_204;
  15955. });
  15956. auto port = svr.bind_to_any_port(HOST);
  15957. thread t = thread([&] { svr.listen_after_bind(); });
  15958. auto se = detail::scope_exit([&] {
  15959. svr.stop();
  15960. t.join();
  15961. });
  15962. svr.wait_until_ready();
  15963. auto error = Error::Success;
  15964. auto sock = detail::create_client_socket(
  15965. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15966. /*connection_timeout_sec=*/2, 0,
  15967. /*read_timeout_sec=*/2, 0,
  15968. /*write_timeout_sec=*/2, 0, std::string(), error);
  15969. ASSERT_NE(INVALID_SOCKET, sock);
  15970. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15971. auto send_request_and_read_response = [&](const std::string &req,
  15972. std::string &out) -> bool {
  15973. auto sent = send(sock, req.data(), req.size(), 0);
  15974. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15975. char buf[4096];
  15976. for (;;) {
  15977. auto n = recv(sock, buf, sizeof(buf), 0);
  15978. if (n <= 0) { return !out.empty(); }
  15979. out.append(buf, static_cast<size_t>(n));
  15980. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  15981. }
  15982. };
  15983. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  15984. "Host: localhost\r\n"
  15985. "\r\n";
  15986. std::string resp1;
  15987. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  15988. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  15989. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  15990. "Host: localhost\r\n"
  15991. "Connection: close\r\n"
  15992. "\r\n";
  15993. std::string resp2;
  15994. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  15995. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  15996. EXPECT_EQ(2, delete_count.load());
  15997. }
  15998. namespace no_proxy_test {
  15999. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16000. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16001. // calling listen().
  16002. class ScopedServer {
  16003. public:
  16004. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16005. ~ScopedServer() {
  16006. svr_.stop();
  16007. if (th_.joinable()) { th_.join(); }
  16008. }
  16009. Server &svr() { return svr_; }
  16010. int port() const { return port_; }
  16011. void listen() {
  16012. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16013. svr_.wait_until_ready();
  16014. }
  16015. private:
  16016. Server svr_;
  16017. std::thread th_;
  16018. int port_ = 0;
  16019. };
  16020. class ProxyAndTargetServers {
  16021. public:
  16022. ProxyAndTargetServers() {
  16023. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16024. proxy_hits_++;
  16025. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16026. res.set_content("via-proxy", "text/plain");
  16027. });
  16028. target_.Get(".*", [this](const Request &req, Response &res) {
  16029. target_hits_++;
  16030. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16031. res.set_content("direct", "text/plain");
  16032. });
  16033. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16034. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16035. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16036. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16037. proxy_mock_.wait_until_ready();
  16038. target_.wait_until_ready();
  16039. }
  16040. ~ProxyAndTargetServers() {
  16041. proxy_mock_.stop();
  16042. target_.stop();
  16043. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16044. if (target_thread_.joinable()) { target_thread_.join(); }
  16045. }
  16046. Server &proxy_mock() { return proxy_mock_; }
  16047. Server &target() { return target_; }
  16048. int proxy_port() const { return proxy_port_; }
  16049. int target_port() const { return target_port_; }
  16050. int proxy_hits() const { return proxy_hits_.load(); }
  16051. int target_hits() const { return target_hits_.load(); }
  16052. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16053. void reset_counters() {
  16054. proxy_hits_ = 0;
  16055. target_hits_ = 0;
  16056. last_had_proxy_authz_ = false;
  16057. }
  16058. private:
  16059. Server proxy_mock_;
  16060. Server target_;
  16061. std::thread proxy_thread_;
  16062. std::thread target_thread_;
  16063. int proxy_port_ = 0;
  16064. int target_port_ = 0;
  16065. std::atomic<int> proxy_hits_{0};
  16066. std::atomic<int> target_hits_{0};
  16067. std::atomic<bool> last_had_proxy_authz_{false};
  16068. };
  16069. inline std::unique_ptr<Client> make_client(const std::string &host,
  16070. ProxyAndTargetServers &s) {
  16071. auto cli = detail::make_unique<Client>(host, s.target_port());
  16072. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16073. cli->set_proxy("127.0.0.1", s.proxy_port());
  16074. return cli;
  16075. }
  16076. } // namespace no_proxy_test
  16077. using no_proxy_test::make_client;
  16078. using no_proxy_test::ProxyAndTargetServers;
  16079. TEST(NoProxyTest, ExactHostnameBypasses) {
  16080. ProxyAndTargetServers s;
  16081. auto cli = make_client("example.com", s);
  16082. cli->set_no_proxy({"example.com"});
  16083. auto res = cli->Get("/");
  16084. ASSERT_TRUE(res);
  16085. EXPECT_EQ(0, s.proxy_hits());
  16086. EXPECT_EQ(1, s.target_hits());
  16087. }
  16088. TEST(NoProxyTest, SubdomainBypasses) {
  16089. ProxyAndTargetServers s;
  16090. auto cli = make_client("foo.example.com", s);
  16091. cli->set_no_proxy({"example.com"});
  16092. auto res = cli->Get("/");
  16093. ASSERT_TRUE(res);
  16094. EXPECT_EQ(0, s.proxy_hits());
  16095. EXPECT_EQ(1, s.target_hits());
  16096. }
  16097. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16098. // Regression guard: "evilexample.com" must not be considered a subdomain
  16099. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16100. // check would let traffic bypass the proxy and leak credentials direct
  16101. // to the attacker host.
  16102. ProxyAndTargetServers s;
  16103. auto cli = make_client("evilexample.com", s);
  16104. cli->set_no_proxy({"example.com"});
  16105. auto res = cli->Get("/");
  16106. ASSERT_TRUE(res);
  16107. EXPECT_GE(s.proxy_hits(), 1);
  16108. EXPECT_EQ(0, s.target_hits());
  16109. }
  16110. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16111. ProxyAndTargetServers s;
  16112. auto cli = make_client("example.com.evil.com", s);
  16113. cli->set_no_proxy({"example.com"});
  16114. auto res = cli->Get("/");
  16115. ASSERT_TRUE(res);
  16116. EXPECT_GE(s.proxy_hits(), 1);
  16117. EXPECT_EQ(0, s.target_hits());
  16118. }
  16119. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16120. ProxyAndTargetServers s;
  16121. auto cli = make_client("example.com", s);
  16122. cli->set_no_proxy({".example.com"});
  16123. auto res = cli->Get("/");
  16124. ASSERT_TRUE(res);
  16125. EXPECT_EQ(0, s.proxy_hits());
  16126. EXPECT_EQ(1, s.target_hits());
  16127. }
  16128. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16129. ProxyAndTargetServers s;
  16130. auto cli = make_client("Example.COM", s);
  16131. cli->set_no_proxy({"EXAMPLE.com"});
  16132. auto res = cli->Get("/");
  16133. ASSERT_TRUE(res);
  16134. EXPECT_EQ(0, s.proxy_hits());
  16135. EXPECT_EQ(1, s.target_hits());
  16136. }
  16137. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16138. ProxyAndTargetServers s;
  16139. auto cli = make_client("example.com.", s);
  16140. cli->set_no_proxy({"example.com"});
  16141. auto res = cli->Get("/");
  16142. ASSERT_TRUE(res);
  16143. EXPECT_EQ(0, s.proxy_hits());
  16144. EXPECT_EQ(1, s.target_hits());
  16145. }
  16146. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16147. // Trailing dots must be normalized on BOTH sides — host and entry.
  16148. // An implementation that only strips the host-side trailing dot would
  16149. // fail to match host "example.com" against entry "example.com." because
  16150. // a literal substring search would compare 11 chars against 12.
  16151. ProxyAndTargetServers s;
  16152. auto cli = make_client("example.com", s);
  16153. cli->set_no_proxy({"example.com."});
  16154. auto res = cli->Get("/");
  16155. ASSERT_TRUE(res);
  16156. EXPECT_EQ(0, s.proxy_hits());
  16157. EXPECT_EQ(1, s.target_hits());
  16158. }
  16159. TEST(NoProxyTest, WildcardBypassesEverything) {
  16160. ProxyAndTargetServers s;
  16161. auto cli = make_client("anything.invalid.test", s);
  16162. cli->set_no_proxy({"*"});
  16163. auto res = cli->Get("/");
  16164. ASSERT_TRUE(res);
  16165. EXPECT_EQ(0, s.proxy_hits());
  16166. EXPECT_EQ(1, s.target_hits());
  16167. }
  16168. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16169. ProxyAndTargetServers s;
  16170. Client cli("127.0.0.1", s.target_port());
  16171. cli.set_proxy("127.0.0.1", s.proxy_port());
  16172. cli.set_no_proxy({"127.0.0.1"});
  16173. auto res = cli.Get("/");
  16174. ASSERT_TRUE(res);
  16175. EXPECT_EQ(0, s.proxy_hits());
  16176. EXPECT_EQ(1, s.target_hits());
  16177. }
  16178. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16179. ProxyAndTargetServers s;
  16180. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16181. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16182. cli.set_proxy("127.0.0.1", s.proxy_port());
  16183. cli.set_no_proxy({"::1"});
  16184. auto res = cli.Get("/");
  16185. ASSERT_TRUE(res);
  16186. EXPECT_EQ(0, s.proxy_hits());
  16187. EXPECT_EQ(1, s.target_hits());
  16188. }
  16189. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16190. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16191. // must still be recognized as IPv6 for CIDR matching. Implementations
  16192. // that detect IPv6 only when the host begins with '[' would parse the
  16193. // host as a hostname and miss the match.
  16194. ProxyAndTargetServers s;
  16195. Client cli("fe80::1", s.target_port());
  16196. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16197. cli.set_proxy("127.0.0.1", s.proxy_port());
  16198. cli.set_no_proxy({"fe80::/10"});
  16199. auto res = cli.Get("/");
  16200. ASSERT_TRUE(res);
  16201. EXPECT_EQ(0, s.proxy_hits());
  16202. EXPECT_EQ(1, s.target_hits());
  16203. }
  16204. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16205. ProxyAndTargetServers s;
  16206. Client cli("::1", s.target_port());
  16207. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16208. cli.set_proxy("127.0.0.1", s.proxy_port());
  16209. cli.set_no_proxy({"[::1]"});
  16210. auto res = cli.Get("/");
  16211. ASSERT_TRUE(res);
  16212. EXPECT_EQ(0, s.proxy_hits());
  16213. EXPECT_EQ(1, s.target_hits());
  16214. }
  16215. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16216. ProxyAndTargetServers s;
  16217. Client cli("fe80::1", s.target_port());
  16218. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16219. cli.set_proxy("127.0.0.1", s.proxy_port());
  16220. cli.set_no_proxy({"[fe80::]/10"});
  16221. auto res = cli.Get("/");
  16222. ASSERT_TRUE(res);
  16223. EXPECT_EQ(0, s.proxy_hits());
  16224. EXPECT_EQ(1, s.target_hits());
  16225. }
  16226. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16227. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16228. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16229. // tricks via address-family conversion.
  16230. ProxyAndTargetServers s;
  16231. Client cli("::ffff:127.0.0.1", s.target_port());
  16232. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16233. cli.set_proxy("127.0.0.1", s.proxy_port());
  16234. cli.set_no_proxy({"127.0.0.1"});
  16235. auto res = cli.Get("/");
  16236. ASSERT_TRUE(res);
  16237. EXPECT_GE(s.proxy_hits(), 1);
  16238. EXPECT_EQ(0, s.target_hits());
  16239. }
  16240. TEST(NoProxyTest, IPv4CidrMatch) {
  16241. ProxyAndTargetServers s;
  16242. Client cli("127.0.0.1", s.target_port());
  16243. cli.set_proxy("127.0.0.1", s.proxy_port());
  16244. cli.set_no_proxy({"127.0.0.0/8"});
  16245. auto res = cli.Get("/");
  16246. ASSERT_TRUE(res);
  16247. EXPECT_EQ(0, s.proxy_hits());
  16248. EXPECT_EQ(1, s.target_hits());
  16249. }
  16250. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16251. ProxyAndTargetServers s;
  16252. Client cli("127.0.0.1", s.target_port());
  16253. cli.set_proxy("127.0.0.1", s.proxy_port());
  16254. cli.set_no_proxy({"10.0.0.0/8"});
  16255. auto res = cli.Get("/");
  16256. ASSERT_TRUE(res);
  16257. EXPECT_GE(s.proxy_hits(), 1);
  16258. EXPECT_EQ(0, s.target_hits());
  16259. }
  16260. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16261. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16262. // IPv4 target matches.
  16263. ProxyAndTargetServers s;
  16264. Client cli("127.0.0.1", s.target_port());
  16265. cli.set_proxy("127.0.0.1", s.proxy_port());
  16266. cli.set_no_proxy({"0.0.0.0/0"});
  16267. auto res = cli.Get("/");
  16268. ASSERT_TRUE(res);
  16269. EXPECT_EQ(0, s.proxy_hits());
  16270. EXPECT_EQ(1, s.target_hits());
  16271. }
  16272. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16273. ProxyAndTargetServers s;
  16274. Client cli("127.0.0.1", s.target_port());
  16275. cli.set_proxy("127.0.0.1", s.proxy_port());
  16276. cli.set_no_proxy({"127.0.0.1"});
  16277. auto res = cli.Get("/");
  16278. ASSERT_TRUE(res);
  16279. EXPECT_EQ(0, s.proxy_hits());
  16280. EXPECT_EQ(1, s.target_hits());
  16281. }
  16282. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16283. ProxyAndTargetServers s;
  16284. Client cli("127.0.0.1", s.target_port());
  16285. cli.set_proxy("127.0.0.1", s.proxy_port());
  16286. cli.set_no_proxy({"127.0.0.0/33"});
  16287. auto res = cli.Get("/");
  16288. ASSERT_TRUE(res);
  16289. EXPECT_GE(s.proxy_hits(), 1);
  16290. EXPECT_EQ(0, s.target_hits());
  16291. }
  16292. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16293. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16294. ProxyAndTargetServers s;
  16295. Client cli("127.0.0.1", s.target_port());
  16296. cli.set_proxy("127.0.0.1", s.proxy_port());
  16297. cli.set_no_proxy({"127.0.0.1/"});
  16298. auto res = cli.Get("/");
  16299. ASSERT_TRUE(res);
  16300. EXPECT_GE(s.proxy_hits(), 1);
  16301. EXPECT_EQ(0, s.target_hits());
  16302. }
  16303. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16304. ProxyAndTargetServers s;
  16305. auto cli = make_client("internal.corp", s);
  16306. cli->set_proxy_basic_auth("u", "p");
  16307. cli->set_no_proxy({"internal.corp"});
  16308. auto res = cli->Get("/");
  16309. ASSERT_TRUE(res);
  16310. EXPECT_EQ(1, s.target_hits());
  16311. EXPECT_EQ(0, s.proxy_hits());
  16312. EXPECT_FALSE(s.last_had_proxy_authz())
  16313. << "Proxy-Authorization must not be sent direct to the target";
  16314. }
  16315. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16316. ProxyAndTargetServers s;
  16317. auto cli = make_client("public.example", s);
  16318. cli->set_proxy_basic_auth("u", "p");
  16319. cli->set_no_proxy({"internal.corp"}); // does not match
  16320. auto res = cli->Get("/");
  16321. ASSERT_TRUE(res);
  16322. EXPECT_GE(s.proxy_hits(), 1);
  16323. EXPECT_TRUE(s.last_had_proxy_authz());
  16324. }
  16325. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16326. ProxyAndTargetServers s;
  16327. auto cli = make_client("anything.test", s);
  16328. auto res = cli->Get("/");
  16329. ASSERT_TRUE(res);
  16330. EXPECT_GE(s.proxy_hits(), 1);
  16331. EXPECT_EQ(0, s.target_hits());
  16332. }
  16333. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16334. ProxyAndTargetServers s;
  16335. auto cli = make_client("example.com", s);
  16336. cli->set_no_proxy({"example.com:8080"});
  16337. auto res = cli->Get("/");
  16338. ASSERT_TRUE(res);
  16339. EXPECT_GE(s.proxy_hits(), 1);
  16340. EXPECT_EQ(0, s.target_hits());
  16341. }
  16342. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16343. ProxyAndTargetServers s;
  16344. auto cli = make_client("anything.test", s);
  16345. cli->set_no_proxy({"", " ", "\t"});
  16346. auto res = cli->Get("/");
  16347. ASSERT_TRUE(res);
  16348. EXPECT_GE(s.proxy_hits(), 1);
  16349. EXPECT_EQ(0, s.target_hits());
  16350. }
  16351. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16352. // An entry with leading/trailing whitespace must still match — env-style
  16353. // values are commonly pasted with stray spaces and an implementation
  16354. // that feeds the raw token directly to inet_pton would fail to match
  16355. // valid CIDRs because of the spaces.
  16356. ProxyAndTargetServers s;
  16357. Client cli("127.0.0.1", s.target_port());
  16358. cli.set_proxy("127.0.0.1", s.proxy_port());
  16359. cli.set_no_proxy({" 127.0.0.0/8 "});
  16360. auto res = cli.Get("/");
  16361. ASSERT_TRUE(res);
  16362. EXPECT_EQ(0, s.proxy_hits());
  16363. EXPECT_EQ(1, s.target_hits());
  16364. }
  16365. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16366. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16367. // go direct and must NOT carry Proxy-Authorization.
  16368. std::atomic<int> proxy_hits{0};
  16369. std::atomic<int> target_hits{0};
  16370. std::atomic<bool> target_saw_authz{false};
  16371. no_proxy_test::ScopedServer proxy_mock, target;
  16372. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16373. proxy_hits++;
  16374. res.status = 302;
  16375. res.set_header("Location", "http://127.0.0.1:" +
  16376. std::to_string(target.port()) + "/landed");
  16377. });
  16378. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16379. target_hits++;
  16380. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16381. res.set_content("direct", "text/plain");
  16382. });
  16383. proxy_mock.listen();
  16384. target.listen();
  16385. Client cli("public.example", target.port());
  16386. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16387. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16388. cli.set_proxy_basic_auth("u", "p");
  16389. cli.set_no_proxy({"127.0.0.1"});
  16390. cli.set_follow_location(true);
  16391. auto res = cli.Get("/redir");
  16392. ASSERT_TRUE(res);
  16393. EXPECT_GE(proxy_hits.load(), 1);
  16394. EXPECT_GE(target_hits.load(), 1);
  16395. EXPECT_FALSE(target_saw_authz.load());
  16396. }
  16397. #ifdef CPPHTTPLIB_SSL_ENABLED
  16398. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16399. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16400. // proxy creds would be sent to the (possibly hostile) origin.
  16401. std::atomic<int> target_hits{0};
  16402. std::atomic<bool> target_saw_proxy_authz{false};
  16403. no_proxy_test::ScopedServer target;
  16404. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16405. target_hits++;
  16406. if (req.has_header("Proxy-Authorization")) {
  16407. target_saw_proxy_authz = true;
  16408. }
  16409. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16410. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16411. "nonce=\"abc\", algorithm=MD5");
  16412. });
  16413. target.listen();
  16414. // The proxy address is set to the target's port: the bypass MUST kick in;
  16415. // if it doesn't, the test still routes "via proxy" to the same server and
  16416. // the Proxy-Authorization assertion below catches the leak.
  16417. Client cli("evil.example", target.port());
  16418. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16419. cli.set_proxy("127.0.0.1", target.port());
  16420. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16421. cli.set_no_proxy({"evil.example"});
  16422. auto res = cli.Get("/x");
  16423. ASSERT_TRUE(res);
  16424. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16425. EXPECT_EQ(1, target_hits.load());
  16426. EXPECT_FALSE(target_saw_proxy_authz.load());
  16427. }
  16428. #endif
  16429. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16430. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16431. std::atomic<int> proxy_hits{0};
  16432. std::atomic<int> bypass_hits{0};
  16433. std::atomic<bool> proxy_saw_c_url{false};
  16434. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16435. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16436. proxy_hits++;
  16437. if (req.path.find("/start") != std::string::npos) {
  16438. res.status = 302;
  16439. res.set_header("Location", "http://127.0.0.1:" +
  16440. std::to_string(bypass_server.port()) +
  16441. "/middle");
  16442. return;
  16443. }
  16444. if (req.path.find("/end") != std::string::npos) {
  16445. proxy_saw_c_url = true;
  16446. res.set_content("c-via-proxy", "text/plain");
  16447. return;
  16448. }
  16449. res.set_content("unexpected", "text/plain");
  16450. });
  16451. // public.example's "advertised" port is arbitrary (the request never lands
  16452. // there — it goes through the proxy), but use a dynamic value to stay
  16453. // friendly with sharded parallel runs.
  16454. int public_port = bypass_server.port();
  16455. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16456. bypass_hits++;
  16457. res.status = 302;
  16458. res.set_header("Location", "http://public.example:" +
  16459. std::to_string(public_port) + "/end");
  16460. });
  16461. proxy_mock.listen();
  16462. bypass_server.listen();
  16463. Client cli("public.example", public_port);
  16464. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16465. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16466. cli.set_no_proxy({"127.0.0.1"});
  16467. cli.set_follow_location(true);
  16468. auto res = cli.Get("/start");
  16469. ASSERT_TRUE(res);
  16470. EXPECT_EQ(StatusCode::OK_200, res->status);
  16471. EXPECT_EQ("c-via-proxy", res->body);
  16472. EXPECT_GE(proxy_hits.load(), 2);
  16473. EXPECT_GE(bypass_hits.load(), 1);
  16474. EXPECT_TRUE(proxy_saw_c_url.load());
  16475. }
  16476. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16477. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16478. // request reconnects to the correct endpoint.
  16479. std::atomic<int> proxy_hits{0};
  16480. std::atomic<int> target_hits{0};
  16481. no_proxy_test::ScopedServer proxy_mock, target;
  16482. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16483. proxy_hits++;
  16484. res.set_content("via-proxy", "text/plain");
  16485. });
  16486. target.svr().Get(".*", [&](const Request &, Response &res) {
  16487. target_hits++;
  16488. res.set_content("direct", "text/plain");
  16489. });
  16490. proxy_mock.listen();
  16491. target.listen();
  16492. Client cli("public.example", target.port());
  16493. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16494. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16495. cli.set_keep_alive(true);
  16496. auto res1 = cli.Get("/a");
  16497. ASSERT_TRUE(res1);
  16498. EXPECT_EQ("via-proxy", res1->body);
  16499. EXPECT_EQ(1, proxy_hits.load());
  16500. EXPECT_EQ(0, target_hits.load());
  16501. cli.set_no_proxy({"public.example"});
  16502. auto res2 = cli.Get("/b");
  16503. ASSERT_TRUE(res2);
  16504. EXPECT_EQ("direct", res2->body);
  16505. EXPECT_EQ(1, proxy_hits.load());
  16506. EXPECT_EQ(1, target_hits.load());
  16507. }
  16508. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16509. namespace proxy_tunnel_test {
  16510. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16511. class ScopedSSLServer {
  16512. public:
  16513. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16514. port_ = svr_.bind_to_any_port("127.0.0.1");
  16515. }
  16516. ~ScopedSSLServer() {
  16517. svr_.stop();
  16518. if (th_.joinable()) { th_.join(); }
  16519. }
  16520. SSLServer &svr() { return svr_; }
  16521. int port() const { return port_; }
  16522. void listen() {
  16523. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16524. svr_.wait_until_ready();
  16525. }
  16526. private:
  16527. SSLServer svr_;
  16528. std::thread th_;
  16529. int port_ = 0;
  16530. };
  16531. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16532. class ScopedConnectProxy {
  16533. public:
  16534. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16535. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16536. if (listen_fd_ < 0) { return; }
  16537. int yes = 1;
  16538. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16539. sockaddr_in a{};
  16540. a.sin_family = AF_INET;
  16541. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16542. a.sin_port = 0;
  16543. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16544. return;
  16545. }
  16546. socklen_t alen = sizeof(a);
  16547. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16548. 0) {
  16549. return;
  16550. }
  16551. port_ = ntohs(a.sin_port);
  16552. if (::listen(listen_fd_, 1) != 0) { return; }
  16553. th_ = std::thread([this] { run(); });
  16554. }
  16555. ~ScopedConnectProxy() {
  16556. stop_ = true;
  16557. if (listen_fd_ >= 0) {
  16558. ::shutdown(listen_fd_, SHUT_RDWR);
  16559. ::close(listen_fd_);
  16560. }
  16561. if (th_.joinable()) { th_.join(); }
  16562. }
  16563. int port() const { return port_; }
  16564. int connect_hits() const { return connect_hits_.load(); }
  16565. private:
  16566. void run() {
  16567. while (!stop_.load()) {
  16568. fd_set rfds;
  16569. FD_ZERO(&rfds);
  16570. FD_SET(listen_fd_, &rfds);
  16571. timeval tv{0, 100 * 1000};
  16572. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16573. if (sel <= 0) { continue; }
  16574. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16575. if (client_fd < 0) { continue; }
  16576. std::string req;
  16577. char buf[2048];
  16578. while (req.find("\r\n\r\n") == std::string::npos) {
  16579. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16580. if (n <= 0) { break; }
  16581. req.append(buf, static_cast<size_t>(n));
  16582. }
  16583. if (req.compare(0, 7, "CONNECT") != 0) {
  16584. ::close(client_fd);
  16585. continue;
  16586. }
  16587. connect_hits_++;
  16588. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16589. ::send(client_fd, ok, std::strlen(ok), 0);
  16590. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16591. sockaddr_in o{};
  16592. o.sin_family = AF_INET;
  16593. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16594. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16595. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16596. 0) {
  16597. ::close(client_fd);
  16598. ::close(origin_fd);
  16599. continue;
  16600. }
  16601. auto forward = [](int from, int to) {
  16602. char b[8192];
  16603. for (;;) {
  16604. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16605. if (n <= 0) { break; }
  16606. ssize_t off = 0;
  16607. while (off < n) {
  16608. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16609. if (s <= 0) {
  16610. off = n;
  16611. break;
  16612. }
  16613. off += s;
  16614. }
  16615. }
  16616. ::shutdown(to, SHUT_WR);
  16617. };
  16618. std::thread t1([&] { forward(client_fd, origin_fd); });
  16619. std::thread t2([&] { forward(origin_fd, client_fd); });
  16620. t1.join();
  16621. t2.join();
  16622. ::close(client_fd);
  16623. ::close(origin_fd);
  16624. }
  16625. }
  16626. int forward_port_ = -1;
  16627. int listen_fd_ = -1;
  16628. int port_ = 0;
  16629. std::thread th_;
  16630. std::atomic<bool> stop_{false};
  16631. std::atomic<int> connect_hits_{0};
  16632. };
  16633. } // namespace proxy_tunnel_test
  16634. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16635. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16636. // retry; otherwise proxy creds would be sent to the origin.
  16637. std::atomic<int> origin_hits{0};
  16638. std::atomic<bool> origin_saw_proxy_authz{false};
  16639. proxy_tunnel_test::ScopedSSLServer origin;
  16640. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16641. origin_hits++;
  16642. if (req.has_header("Proxy-Authorization")) {
  16643. origin_saw_proxy_authz = true;
  16644. }
  16645. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16646. res.set_header("Proxy-Authenticate",
  16647. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16648. "algorithm=MD5");
  16649. });
  16650. origin.listen();
  16651. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16652. ASSERT_NE(0, proxy.port());
  16653. SSLClient cli(HOST, origin.port());
  16654. cli.enable_server_certificate_verification(false);
  16655. cli.set_proxy(HOST, proxy.port());
  16656. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16657. auto res = cli.Get("/x");
  16658. ASSERT_TRUE(res);
  16659. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16660. EXPECT_EQ(1, origin_hits.load());
  16661. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16662. EXPECT_EQ(1, proxy.connect_hits());
  16663. }
  16664. #endif